diff --git a/workloads/transformersjs/benchmark.js b/workloads/transformersjs/benchmark.js index 2e7d359b..2694a471 100644 --- a/workloads/transformersjs/benchmark.js +++ b/workloads/transformersjs/benchmark.js @@ -14,6 +14,35 @@ class URL { } globalThis.URL = URL; +class Headers { + constructor(init) { + this._headers = new Map(); + if (init instanceof Headers) { + for (const [k, v] of init._headers) { + this._headers.set(k.toLowerCase(), v); + } + } else if (init) { + for (const [k, v] of Object.entries(init)) { + this._headers.set(k.toLowerCase(), String(v)); + } + } + } + get(key) { return this._headers.get(key.toLowerCase()) ?? null; } + set(key, value) { this._headers.set(key.toLowerCase(), String(value)); } + has(key) { return this._headers.has(key.toLowerCase()); } + delete(key) { this._headers.delete(key.toLowerCase()); } + [Symbol.iterator]() { return this._headers.entries(); } +} +if (typeof globalThis.Headers === 'undefined') { + globalThis.Headers = Headers; +} + +// We run ONNX Runtime single-threaded (numThreads = 1), so no pthread workers +// are spawned. Delete Atomics.waitAsync so Emscripten's pthread mailbox init +// in ort-wasm-simd-threaded.mjs does not register a never-resolved async waiter +// that keeps the JSC shell alive after the benchmark completes. +delete Atomics.waitAsync; + // Polyfill fetch for shell-compatibility and to cache / preload model weights etc. let preload = { /* Initialized in init() below due to async. */ }; @@ -29,6 +58,7 @@ async function redirectingFetch(url) { return { ok: true, status: 200, + headers: new Headers(), arrayBuffer() { return preload[url]; }, async blob() { return { @@ -41,6 +71,7 @@ async function redirectingFetch(url) { throw new Error(`Unexpected resource requested in benchmark: ${url}`); }; +globalThis.fetch ??= redirectingFetch; // JetStream benchmark harness. Reuse for two different Transformers.js tasks. // Assumes `preloadFiles(module)`, `initPipeline(pipelineFromTransformersJs)`, @@ -80,6 +111,7 @@ class Benchmark { env.allowRemoteModels = false; env.allowLocalModels = true; env.localModelPath = './workloads/transformersjs/build/models/'; + env.fetch = redirectingFetch; // Always select the Wasm backend, nothing else. delete env.backends.onnx.webgl; diff --git a/workloads/transformersjs/build.log b/workloads/transformersjs/build.log index 2aaa93cc..8d58d3c6 100644 --- a/workloads/transformersjs/build.log +++ b/workloads/transformersjs/build.log @@ -1,5 +1,7 @@ -Built on 2025-08-20T13:30:51Z +Built on 2026-10-28T16:40:00Z Installing Node dependencies... +Transformers.js version: 4.3.2 +ONNX Runtime Web version: 1.31.0-dev.20260914-8d85527a0 Download and convert audio input(s)... Converted 4.25s of audio from 'jfk.wav', 2 channel(s), 44100 Hz, 16 bit, 176000 samples diff --git a/workloads/transformersjs/build.sh b/workloads/transformersjs/build.sh index d6297eaf..8ab3ee40 100755 --- a/workloads/transformersjs/build.sh +++ b/workloads/transformersjs/build.sh @@ -17,6 +17,11 @@ pushd util/ npm install popd +TRANSFORMERS_VERSION="$(grep -m1 '"version":' util/node_modules/@huggingface/transformers/package.json | cut -d '"' -f 4)" +ORT_VERSION="$(grep -m1 '"version":' util/node_modules/onnxruntime-web/package.json | cut -d '"' -f 4)" +echo "Transformers.js version: ${TRANSFORMERS_VERSION}" | tee -a "$BUILD_LOG" +echo "ONNX Runtime Web version: ${ORT_VERSION}" | tee -a "$BUILD_LOG" + echo "Download and convert audio input(s)..." | tee -a "$BUILD_LOG" wget https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav | tee -a "$BUILD_LOG" # Shorten the audio file to one sentence in the middle, to speed up a single iteration. @@ -30,7 +35,6 @@ node util/test-models.mjs echo "Copy library files into build/..." | tee -a "$BUILD_LOG" cp util/node_modules/@huggingface/transformers/dist/transformers.js build/ -git apply transformers.js.patch # Transformers.js packages the ONNX runtime JSEP build by default, even when # only using the Wasm backend, which would be fine with the non-JSEP build. diff --git a/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.mjs b/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.mjs index eb14fedb..9ccde901 100644 --- a/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.mjs +++ b/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.mjs @@ -1,70 +1,59 @@ -var ortWasmThreaded = (() => { - var _scriptName = import.meta.url; - - return ( -async function(moduleArg = {}) { - var moduleRtn; - -var f=moduleArg,aa,ba,ca=new Promise((a,b)=>{aa=a;ba=b}),da="object"==typeof window,k="undefined"!=typeof WorkerGlobalScope,l="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&"renderer"!=process.type,m=k&&self.name?.startsWith("em-pthread");if(l){const {createRequire:a}=await import("module");var require=a(import.meta.url),n=require("worker_threads");global.Worker=n.Worker;m=(k=!n.jb)&&"em-pthread"==n.workerData} -f.mountExternalData=(a,b)=>{a.startsWith("./")&&(a=a.substring(2));(f.Sa||(f.Sa=new Map)).set(a,b)};f.unmountExternalData=()=>{delete f.Sa};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,lb:!0})).buffer.constructor,ea=Object.assign({},f),fa="./this.program",q=(a,b)=>{throw b;},r="",ha,t; -if(l){var fs=require("fs"),ia=require("path");import.meta.url.startsWith("data:")||(r=ia.dirname(require("url").fileURLToPath(import.meta.url))+"/");t=a=>{a=u(a)?new URL(a):a;return fs.readFileSync(a)};ha=async a=>{a=u(a)?new URL(a):a;return fs.readFileSync(a,void 0)};!f.thisProgram&&1{process.exitCode=a;throw b;}}else if(da||k)k?r=self.location.href:"undefined"!=typeof document&&document.currentScript&& -(r=document.currentScript.src),_scriptName&&(r=_scriptName),r.startsWith("blob:")?r="":r=r.slice(0,r.replace(/[?#].*/,"").lastIndexOf("/")+1),l||(k&&(t=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer";b.send(null);return new Uint8Array(b.response)}),ha=async a=>{if(u(a))return new Promise((c,d)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?c(e.response):d(e.status)};e.onerror=d;e.send(null)}); -var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);});var ja=console.log.bind(console),ka=console.error.bind(console);l&&(ja=(...a)=>fs.writeSync(1,a.join(" ")+"\n"),ka=(...a)=>fs.writeSync(2,a.join(" ")+"\n"));var la=ja,w=ka;Object.assign(f,ea);ea=null;var x=f.wasmBinary,y,ma,z=!1,A,B,na,oa,pa,qa,ra,C,sa,u=a=>a.startsWith("file://");function D(){y.buffer!=B.buffer&&E();return B}function F(){y.buffer!=B.buffer&&E();return na} -function ta(){y.buffer!=B.buffer&&E();return oa}function G(){y.buffer!=B.buffer&&E();return pa}function H(){y.buffer!=B.buffer&&E();return qa}function va(){y.buffer!=B.buffer&&E();return ra}function I(){y.buffer!=B.buffer&&E();return sa} -if(m){var wa;if(l){var xa=n.parentPort;xa.on("message",b=>onmessage({data:b}));Object.assign(globalThis,{self:global,postMessage:b=>xa.postMessage(b)})}var ya=!1;w=function(...b){b=b.join(" ");l?fs.writeSync(2,b+"\n"):console.error(b)};self.alert=function(...b){postMessage({Ra:"alert",text:b.join(" "),eb:J()})};self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var c=b.data,d=c.Ra;if("load"===d){let e=[];self.onmessage=g=>e.push(g);self.startWorker=()=>{postMessage({Ra:"loaded"}); -for(let g of e)a(g);self.onmessage=a};for(const g of c.Za)if(!f[g]||f[g].proxy)f[g]=(...h)=>{postMessage({Ra:"callHandler",Ya:g,args:h})},"print"==g&&(la=f[g]),"printErr"==g&&(w=f[g]);y=c.gb;E();wa(c.hb)}else if("run"===d){za(c.Qa);Aa(c.Qa,0,0,1,0,0);Ba();Ca(c.Qa);ya||=!0;try{Da(c.bb,c.Va)}catch(e){if("unwind"!=e)throw e;}}else"setimmediate"!==c.target&&("checkMailbox"===d?ya&&K():d&&(w(`worker: received unknown command ${d}`),w(c)))}catch(e){throw Ea(),e;}}self.onmessage=a} -function E(){var a=y.buffer;f.HEAP8=B=new Int8Array(a);f.HEAP16=oa=new Int16Array(a);f.HEAPU8=na=new Uint8Array(a);f.HEAPU16=new Uint16Array(a);f.HEAP32=pa=new Int32Array(a);f.HEAPU32=qa=new Uint32Array(a);f.HEAPF32=ra=new Float32Array(a);f.HEAPF64=sa=new Float64Array(a);f.HEAP64=C=new BigInt64Array(a);f.HEAPU64=new BigUint64Array(a)}m||(y=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),E());function Fa(){m?startWorker(f):L.$()}var M=0,N=null; -function Ga(){M--;if(0==M&&N){var a=N;N=null;a()}}function O(a){a="Aborted("+a+")";w(a);z=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");ba(a);throw a;}var Ha;async function Ia(a){if(!x)try{var b=await ha(a);return new Uint8Array(b)}catch{}if(a==Ha&&x)a=new Uint8Array(x);else if(t)a=t(a);else throw"both async and sync fetching of the wasm failed";return a} -async function Ja(a,b){try{var c=await Ia(a);return await WebAssembly.instantiate(c,b)}catch(d){w(`failed to asynchronously prepare wasm: ${d}`),O(d)}}async function Ka(a){var b=Ha;if(!x&&"function"==typeof WebAssembly.instantiateStreaming&&!u(b)&&!l)try{var c=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(c,a)}catch(d){w(`wasm streaming compile failed: ${d}`),w("falling back to ArrayBuffer instantiation")}return Ja(b,a)} -function La(){Ma={j:Na,b:Oa,E:Pa,f:Qa,U:Ra,A:Sa,C:Ta,V:Ua,S:Va,L:Wa,R:Xa,n:Ya,B:Za,y:$a,T:ab,z:bb,_:cb,O:db,w:eb,F:fb,t:gb,i:hb,N:Ca,X:ib,I:jb,J:kb,K:lb,G:mb,H:nb,u:ob,q:pb,Z:qb,o:rb,k:sb,Y:tb,d:ub,W:vb,x:wb,c:xb,e:yb,h:zb,v:Ab,s:Bb,r:Cb,P:Db,Q:Eb,D:Fb,g:Gb,m:Hb,M:Ib,l:Jb,a:y,p:Kb};return{a:Ma}} -var Mb={794988:(a,b,c,d,e)=>{if("undefined"==typeof f||!f.Sa)return 1;a=Lb(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=f.Sa.get(a);if(!a)return 2;b=Number(b>>>0);c=Number(c>>>0);d=Number(d>>>0);if(b+c>a.byteLength)return 3;try{const g=a.subarray(b,b+c);switch(e){case 0:F().set(g,d>>>0);break;case 1:f.ib?f.ib(d,g):f.kb(d,g);break;default:return 4}return 0}catch{return 4}},795812:()=>"undefined"!==typeof wasmOffsetConverter};function Na(){return"undefined"!==typeof wasmOffsetConverter} -class Nb{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} -var Ob=a=>{a.terminate();a.onmessage=()=>{}},Pb=[],Sb=a=>{0==Q.length&&(Qb(),Rb(Q[0]));var b=Q.pop();if(!b)return 6;R.push(b);S[a.Qa]=b;b.Qa=a.Qa;var c={Ra:"run",bb:a.ab,Va:a.Va,Qa:a.Qa};l&&b.unref();b.postMessage(c,a.Xa);return 0},T=0,V=(a,b,...c)=>{for(var d=2*c.length,e=Tb(),g=Ub(8*d),h=g>>>3,p=0;p>>0]=v)}a=Vb(a,0,d,g,b);U(e);return a}; -function Kb(a){if(m)return V(0,1,a);A=a;if(!(0{A=a;if(m)throw Wb(a),"unwind";Kb(a)},Q=[],R=[],Xb=[],S={};function Yb(){for(var a=f.numThreads-1;a--;)Qb();Pb.unshift(()=>{M++;Zb(()=>Ga())})}var ac=a=>{var b=a.Qa;delete S[b];Q.push(a);R.splice(R.indexOf(a),1);a.Qa=0;$b(b)};function Ba(){Xb.forEach(a=>a())} -var Rb=a=>new Promise(b=>{a.onmessage=g=>{g=g.data;var h=g.Ra;if(g.Ta&&g.Ta!=J()){var p=S[g.Ta];p?p.postMessage(g,g.Xa):w(`Internal error! Worker sent a message "${h}" to target pthread ${g.Ta}, but that thread no longer exists!`)}else if("checkMailbox"===h)K();else if("spawnThread"===h)Sb(g);else if("cleanupThread"===h)ac(S[g.cb]);else if("loaded"===h)a.loaded=!0,l&&!a.Qa&&a.unref(),b(a);else if("alert"===h)alert(`Thread ${g.eb}: ${g.text}`);else if("setimmediate"===g.target)a.postMessage(g);else if("callHandler"=== -h)f[g.Ya](...g.args);else h&&w(`worker sent an unknown command ${h}`)};a.onerror=g=>{w(`${"worker sent an error!"} ${g.filename}:${g.lineno}: ${g.message}`);throw g;};l&&(a.on("message",g=>a.onmessage({data:g})),a.on("error",g=>a.onerror(g)));var c=[],d=[],e;for(e of d)f.propertyIsEnumerable(e)&&c.push(e);a.postMessage({Ra:"load",Za:c,gb:y,hb:ma})});function Zb(a){m?a():Promise.all(Q.map(Rb)).then(a)} -function Qb(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Q.push(a)}var za=a=>{E();var b=H()[a+52>>>2>>>0];a=H()[a+56>>>2>>>0];bc(b,b-a);U(b)},W=[],cc,Da=(a,b)=>{T=0;var c=W[a];c||(a>=W.length&&(W.length=a+1),W[a]=c=cc.get(a));a=c(b);0>>=0;var d=new ec(a);b>>>=0;c>>>=0;H()[d.Ua+16>>>2>>>0]=0;H()[d.Ua+4>>>2>>>0]=b;H()[d.Ua+8>>>2>>>0]=c;fc=a;gc++;throw fc;}function hc(a,b,c,d){return m?V(2,1,a,b,c,d):Pa(a,b,c,d)}function Pa(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;if("undefined"==typeof SharedArrayBuffer)return 6;var e=[];if(m&&0===e.length)return hc(a,b,c,d);a={ab:c,Qa:a,Va:d,Xa:e};return m?(a.Ra="spawnThread",postMessage(a,e),0):Sb(a)} -var ic="undefined"!=typeof TextDecoder?new TextDecoder:void 0,jc=(a,b=0,c=NaN)=>{b>>>=0;var d=b+c;for(c=b;a[c]&&!(c>=d);)++c;if(16e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320| -e&1023))}}else d+=String.fromCharCode(e)}return d},Lb=(a,b)=>(a>>>=0)?jc(F(),a,b):"";function Qa(a,b,c){return m?V(3,1,a,b,c):0}function Ra(a,b){if(m)return V(4,1,a,b)} -var X=(a,b,c)=>{var d=F();b>>>=0;if(0=h){var p=a.charCodeAt(++g);h=65536+((h&1023)<<10)|p&1023}if(127>=h){if(b>=c)break;d[b++>>>0]=h}else{if(2047>=h){if(b+1>=c)break;d[b++>>>0]=192|h>>6}else{if(65535>=h){if(b+2>=c)break;d[b++>>>0]=224|h>>12}else{if(b+3>=c)break;d[b++>>>0]=240|h>>18;d[b++>>>0]=128|h>>12&63}d[b++>>>0]=128|h>>6&63}d[b++>>>0]=128|h&63}}d[b>>>0]=0;a=b-e}else a=0;return a}; -function Sa(a,b){if(m)return V(5,1,a,b)}function Ta(a,b,c){if(m)return V(6,1,a,b,c)}function Ua(a,b,c){return m?V(7,1,a,b,c):0}function Va(a,b){if(m)return V(8,1,a,b)}function Wa(a,b,c){if(m)return V(9,1,a,b,c)}function Xa(a,b,c,d){if(m)return V(10,1,a,b,c,d)}function Ya(a,b,c,d){if(m)return V(11,1,a,b,c,d)}function Za(a,b,c,d){if(m)return V(12,1,a,b,c,d)}function $a(a){if(m)return V(13,1,a)}function ab(a,b){if(m)return V(14,1,a,b)}function bb(a,b,c){if(m)return V(15,1,a,b,c)}var cb=()=>O(""); -function db(a){Aa(a>>>0,!k,1,!da,131072,!1);Ba()}var kc=a=>{if(!z)try{if(a(),!(0>>=0;"function"===typeof Atomics.fb&&(Atomics.fb(G(),a>>>2,a).value.then(K),a+=128,Atomics.store(G(),a>>>2,1))}var K=()=>{var a=J();a&&(Ca(a),kc(lc))};function eb(a,b){a>>>=0;a==b>>>0?setTimeout(K):m?postMessage({Ta:a,Ra:"checkMailbox"}):(a=S[a])&&a.postMessage({Ra:"checkMailbox"})} -var mc=[];function fb(a,b,c,d,e){b>>>=0;d/=2;mc.length=d;c=e>>>0>>>3;for(e=0;e>>0];return(b?Mb[b]:nc[a])(...mc)}var gb=()=>{T=0};function hb(a){a>>>=0;m?postMessage({Ra:"cleanupThread",cb:a}):ac(S[a])}function ib(a){l&&S[a>>>0].ref()} -function jb(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);G()[b>>>2>>>0]=a.getUTCSeconds();G()[b+4>>>2>>>0]=a.getUTCMinutes();G()[b+8>>>2>>>0]=a.getUTCHours();G()[b+12>>>2>>>0]=a.getUTCDate();G()[b+16>>>2>>>0]=a.getUTCMonth();G()[b+20>>>2>>>0]=a.getUTCFullYear()-1900;G()[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;G()[b+28>>>2>>>0]=a} -var oc=a=>0===a%4&&(0!==a%100||0===a%400),pc=[0,31,60,91,121,152,182,213,244,274,305,335],qc=[0,31,59,90,120,151,181,212,243,273,304,334]; -function kb(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);G()[b>>>2>>>0]=a.getSeconds();G()[b+4>>>2>>>0]=a.getMinutes();G()[b+8>>>2>>>0]=a.getHours();G()[b+12>>>2>>>0]=a.getDate();G()[b+16>>>2>>>0]=a.getMonth();G()[b+20>>>2>>>0]=a.getFullYear()-1900;G()[b+24>>>2>>>0]=a.getDay();var c=(oc(a.getFullYear())?pc:qc)[a.getMonth()]+a.getDate()-1|0;G()[b+28>>>2>>>0]=c;G()[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());c=(new Date(a.getFullYear(),6,1)).getTimezoneOffset(); -var d=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();a=(c!=d&&a.getTimezoneOffset()==Math.min(d,c))|0;G()[b+32>>>2>>>0]=a} -function lb(a){a>>>=0;var b=new Date(G()[a+20>>>2>>>0]+1900,G()[a+16>>>2>>>0],G()[a+12>>>2>>>0],G()[a+8>>>2>>>0],G()[a+4>>>2>>>0],G()[a>>>2>>>0],0),c=G()[a+32>>>2>>>0],d=b.getTimezoneOffset(),e=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),g=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),h=Math.min(g,e);0>c?G()[a+32>>>2>>>0]=Number(e!=g&&h==d):0>>2>>>0]=b.getDay();c=(oc(b.getFullYear())?pc:qc)[b.getMonth()]+ -b.getDate()-1|0;G()[a+28>>>2>>>0]=c;G()[a>>>2>>>0]=b.getSeconds();G()[a+4>>>2>>>0]=b.getMinutes();G()[a+8>>>2>>>0]=b.getHours();G()[a+12>>>2>>>0]=b.getDate();G()[a+16>>>2>>>0]=b.getMonth();G()[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function mb(a,b,c,d,e,g,h){return m?V(16,1,a,b,c,d,e,g,h):-52}function nb(a,b,c,d,e,g){if(m)return V(17,1,a,b,c,d,e,g)}var Y={},xb=()=>performance.timeOrigin+performance.now(); -function ob(a,b){if(m)return V(18,1,a,b);Y[a]&&(clearTimeout(Y[a].id),delete Y[a]);if(!b)return 0;var c=setTimeout(()=>{delete Y[a];kc(()=>rc(a,performance.timeOrigin+performance.now()))},b);Y[a]={id:c,mb:b};return 0} -function pb(a,b,c,d){a>>>=0;b>>>=0;c>>>=0;d>>>=0;var e=(new Date).getFullYear(),g=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var h=Math.max(g,e);H()[a>>>2>>>0]=60*h;G()[b>>>2>>>0]=Number(g!=e);b=p=>{var v=Math.abs(p);return`UTC${0<=p?"-":"+"}${String(Math.floor(v/60)).padStart(2,"0")}${String(v%60).padStart(2,"0")}`};a=b(g);b=b(e);eDate.now(),sc=1; -function qb(a,b,c){if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(sc)a=performance.timeOrigin+performance.now();else return 52;C[c>>>0>>>3]=BigInt(Math.round(1E6*a));return 0}var tc=[];function rb(a,b,c){a>>>=0;b>>>=0;c>>>=0;tc.length=0;for(var d;d=F()[b++>>>0];){var e=105!=d;e&=112!=d;c+=e&&c%8?4:0;tc.push(112==d?H()[c>>>2>>>0]:106==d?C[c>>>3]:105==d?G()[c>>>2>>>0]:I()[c>>>3>>>0]);c+=e?8:4}return Mb[a](...tc)}var sb=()=>{};function ub(a,b){return w(Lb(a>>>0,b>>>0))} -var vb=()=>{T+=1;throw"unwind";};function wb(){return 4294901760}var yb=()=>l?require("os").cpus().length:navigator.hardwareConcurrency;function zb(){O("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER");return 0} -function Ab(a){a>>>=0;var b=F().length;if(a<=b||4294901760=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,a+100663296);a:{d=(Math.min(4294901760,65536*Math.ceil(Math.max(a,d)/65536))-y.buffer.byteLength+65535)/65536|0;try{y.grow(d);E();var e=1;break a}catch(g){}e=void 0}if(e)return!0}return!1}var uc=()=>{O("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER");return 0},Z={},vc=a=>{a.forEach(b=>{var c=uc();c&&(Z[c]=b)})}; -function Bb(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();vc(a);Z.Wa=uc();Z.$a=a;return Z.Wa}function Cb(a,b,c){a>>>=0;b>>>=0;if(Z.Wa==a)var d=Z.$a;else d=Error().stack.toString().split("\n"),"Error"==d[0]&&d.shift(),vc(d);for(var e=3;d[e]&&uc()!=a;)++e;for(a=0;a>>2>>>0]=uc();return a} -var wc={},yc=()=>{if(!xc){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:fa||"./this.program"},b;for(b in wc)void 0===wc[b]?delete a[b]:a[b]=wc[b];var c=[];for(b in a)c.push(`${b}=${a[b]}`);xc=c}return xc},xc; -function Db(a,b){if(m)return V(19,1,a,b);a>>>=0;b>>>=0;var c=0;yc().forEach((d,e)=>{var g=b+c;e=H()[a+4*e>>>2>>>0]=g;for(g=0;g>>0]=d.charCodeAt(g);D()[e>>>0]=0;c+=d.length+1});return 0}function Eb(a,b){if(m)return V(20,1,a,b);a>>>=0;b>>>=0;var c=yc();H()[a>>>2>>>0]=c.length;var d=0;c.forEach(e=>d+=e.length+1);H()[b>>>2>>>0]=d;return 0}function Gb(a){return m?V(21,1,a):52}function Hb(a,b,c,d){return m?V(22,1,a,b,c,d):52}function Ib(a,b,c,d){return m?V(23,1,a,b,c,d):70} -var zc=[null,[],[]];function Jb(a,b,c,d){if(m)return V(24,1,a,b,c,d);b>>>=0;c>>>=0;d>>>=0;for(var e=0,g=0;g>>2>>>0],p=H()[b+4>>>2>>>0];b+=8;for(var v=0;v>>0],ua=zc[a];0===P||10===P?((1===a?la:w)(jc(ua)),ua.length=0):ua.push(P)}e+=p}H()[d>>>2>>>0]=e;return 0}m||Yb();var nc=[Kb,Wb,hc,Qa,Ra,Sa,Ta,Ua,Va,Wa,Xa,Ya,Za,$a,ab,bb,mb,nb,ob,Db,Eb,Gb,Hb,Ib,Jb],Ma,L; -(async function(){function a(d,e){L=d.exports;L=Ac();Xb.push(L.Da);cc=L.Ea;ma=e;Ga();return L}M++;var b=La();if(f.instantiateWasm)return new Promise(d=>{f.instantiateWasm(b,(e,g)=>{a(e,g);d(e.exports)})});if(m)return new Promise(d=>{wa=e=>{var g=new WebAssembly.Instance(e,La());d(a(g,e))}});Ha??=f.locateFile?f.locateFile?f.locateFile("ort-wasm-simd-threaded.wasm",r):r+"ort-wasm-simd-threaded.wasm":(new URL("ort-wasm-simd-threaded.wasm",import.meta.url)).href;try{var c=await Ka(b);return a(c.instance, -c.module)}catch(d){return ba(d),Promise.reject(d)}})();f._OrtInit=(a,b)=>(f._OrtInit=L.aa)(a,b);f._OrtGetLastError=(a,b)=>(f._OrtGetLastError=L.ba)(a,b);f._OrtCreateSessionOptions=(a,b,c,d,e,g,h,p,v,P)=>(f._OrtCreateSessionOptions=L.ca)(a,b,c,d,e,g,h,p,v,P);f._OrtAppendExecutionProvider=(a,b,c,d,e)=>(f._OrtAppendExecutionProvider=L.da)(a,b,c,d,e);f._OrtAddFreeDimensionOverride=(a,b,c)=>(f._OrtAddFreeDimensionOverride=L.ea)(a,b,c); -f._OrtAddSessionConfigEntry=(a,b,c)=>(f._OrtAddSessionConfigEntry=L.fa)(a,b,c);f._OrtReleaseSessionOptions=a=>(f._OrtReleaseSessionOptions=L.ga)(a);f._OrtCreateSession=(a,b,c)=>(f._OrtCreateSession=L.ha)(a,b,c);f._OrtReleaseSession=a=>(f._OrtReleaseSession=L.ia)(a);f._OrtGetInputOutputCount=(a,b,c)=>(f._OrtGetInputOutputCount=L.ja)(a,b,c);f._OrtGetInputOutputMetadata=(a,b,c,d)=>(f._OrtGetInputOutputMetadata=L.ka)(a,b,c,d);f._OrtFree=a=>(f._OrtFree=L.la)(a); -f._OrtCreateTensor=(a,b,c,d,e,g)=>(f._OrtCreateTensor=L.ma)(a,b,c,d,e,g);f._OrtGetTensorData=(a,b,c,d,e)=>(f._OrtGetTensorData=L.na)(a,b,c,d,e);f._OrtReleaseTensor=a=>(f._OrtReleaseTensor=L.oa)(a);f._OrtCreateRunOptions=(a,b,c,d)=>(f._OrtCreateRunOptions=L.pa)(a,b,c,d);f._OrtAddRunConfigEntry=(a,b,c)=>(f._OrtAddRunConfigEntry=L.qa)(a,b,c);f._OrtReleaseRunOptions=a=>(f._OrtReleaseRunOptions=L.ra)(a);f._OrtCreateBinding=a=>(f._OrtCreateBinding=L.sa)(a); -f._OrtBindInput=(a,b,c)=>(f._OrtBindInput=L.ta)(a,b,c);f._OrtBindOutput=(a,b,c,d)=>(f._OrtBindOutput=L.ua)(a,b,c,d);f._OrtClearBoundOutputs=a=>(f._OrtClearBoundOutputs=L.va)(a);f._OrtReleaseBinding=a=>(f._OrtReleaseBinding=L.wa)(a);f._OrtRunWithBinding=(a,b,c,d,e)=>(f._OrtRunWithBinding=L.xa)(a,b,c,d,e);f._OrtRun=(a,b,c,d,e,g,h,p)=>(f._OrtRun=L.ya)(a,b,c,d,e,g,h,p);f._OrtEndProfiling=a=>(f._OrtEndProfiling=L.za)(a);var J=()=>(J=L.Aa)();f._free=a=>(f._free=L.Ba)(a);f._malloc=a=>(f._malloc=L.Ca)(a); -var Aa=(a,b,c,d,e,g)=>(Aa=L.Fa)(a,b,c,d,e,g),Ea=()=>(Ea=L.Ga)(),Vb=(a,b,c,d,e)=>(Vb=L.Ha)(a,b,c,d,e),$b=a=>($b=L.Ia)(a),dc=a=>(dc=L.Ja)(a),rc=(a,b)=>(rc=L.Ka)(a,b),lc=()=>(lc=L.La)(),bc=(a,b)=>(bc=L.Ma)(a,b),U=a=>(U=L.Na)(a),Ub=a=>(Ub=L.Oa)(a),Tb=()=>(Tb=L.Pa)();function Ac(){var a=L;a=Object.assign({},a);var b=d=>()=>d()>>>0,c=d=>e=>d(e)>>>0;a.Aa=b(a.Aa);a.Ca=c(a.Ca);a.Oa=c(a.Oa);a.Pa=b(a.Pa);a.__cxa_get_exception_ptr=c(a.__cxa_get_exception_ptr);return a}f.stackSave=()=>Tb();f.stackRestore=a=>U(a); -f.stackAlloc=a=>Ub(a);f.setValue=function(a,b,c="i8"){c.endsWith("*")&&(c="*");switch(c){case "i1":D()[a>>>0]=b;break;case "i8":D()[a>>>0]=b;break;case "i16":ta()[a>>>1>>>0]=b;break;case "i32":G()[a>>>2>>>0]=b;break;case "i64":C[a>>>3]=BigInt(b);break;case "float":va()[a>>>2>>>0]=b;break;case "double":I()[a>>>3>>>0]=b;break;case "*":H()[a>>>2>>>0]=b;break;default:O(`invalid type for setValue: ${c}`)}}; -f.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return D()[a>>>0];case "i8":return D()[a>>>0];case "i16":return ta()[a>>>1>>>0];case "i32":return G()[a>>>2>>>0];case "i64":return C[a>>>3];case "float":return va()[a>>>2>>>0];case "double":return I()[a>>>3>>>0];case "*":return H()[a>>>2>>>0];default:O(`invalid type for getValue: ${b}`)}};f.UTF8ToString=Lb;f.stringToUTF8=X; -f.lengthBytesUTF8=a=>{for(var b=0,c=0;c=d?b++:2047>=d?b+=2:55296<=d&&57343>=d?(b+=4,++c):b+=3}return b};function Bc(){if(0{a.startsWith("./")&&(a=a.substring(2));(h.Tb||(h.Tb=new Map)).set(a,b)}; +h.unmountExternalData=()=>{delete h.Tb;delete h.mc;delete h.lc;delete h.nc};var SharedArrayBuffer=globalThis.SharedArrayBuffer??(new WebAssembly.Memory({initial:0,maximum:0,shared:!0})).buffer.constructor,ca="./this.program",da=(a,b)=>{throw b;},ea=import.meta.url,fa="",ha,ia; +if(m){var fs=require("fs");ea.startsWith("file:")&&(fa=require("path").dirname(require("url").fileURLToPath(ea))+"/");ia=a=>{a=ja(a)?new URL(a):a;return fs.readFileSync(a)};ha=async a=>{a=ja(a)?new URL(a):a;return fs.readFileSync(a,void 0)};1{process.exitCode=a;throw b;}}else if(aa||k){try{fa=(new URL(".",ea)).href}catch{}m||(k&&(ia=a=>{var b=new XMLHttpRequest;b.open("GET",a,!1);b.responseType="arraybuffer"; +b.send(null);return new Uint8Array(b.response)}),ha=async a=>{if(ja(a))return new Promise((d,c)=>{var e=new XMLHttpRequest;e.open("GET",a,!0);e.responseType="arraybuffer";e.onload=()=>{200==e.status||0==e.status&&e.response?d(e.response):c(e.status)};e.onerror=c;e.send(null)});var b=await fetch(a,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url);})}var ka=console.log.bind(console),la=console.error.bind(console); +if(m){var ma=require("util"),na=a=>"object"==typeof a?ma.inspect(a):a;ka=(...a)=>fs.writeSync(1,a.map(na).join(" ")+"\n");la=(...a)=>fs.writeSync(2,a.map(na).join(" ")+"\n")}var oa=ka,p=la,q,r,pa=!1,t,ja=a=>a.startsWith("file://");function v(){x.buffer!=z.buffer&&qa()}var ra,sa; +if(m&&n){var ta=ba.parentPort;ta.on("message",a=>global.onmessage?.({data:a}));Object.assign(globalThis,{self:global,postMessage:a=>ta.postMessage(a)});process.on("uncaughtException",a=>{postMessage({Rb:"uncaughtException",error:a});process.exit(1)})}var ua; +if(n){var va=!1;self.onunhandledrejection=b=>{throw b.reason||b;};function a(b){try{var d=b.data,c=d.Rb;if("load"===c){let e=[];self.onmessage=f=>e.push(f);ua=()=>{postMessage({Rb:"loaded"});for(let f of e)a(f);self.onmessage=a};for(const f of d.ac)if(!h[f]||h[f].proxy)h[f]=(...g)=>{postMessage({Rb:"callHandler",$b:f,args:g})},"print"==f&&(oa=h[f]),"printErr"==f&&(p=h[f]);x=d.fc;qa();r=d.hc;wa();xa()}else if("run"===c){ya(d.Qb);za(d.Qb,0,0,1,0,0);Aa();Ba(d.Qb);va||=!0;try{Ca(d.dc,d.Vb)}catch(e){if("unwind"!= +e)throw e;}}else"setimmediate"!==d.target&&("checkMailbox"===c?va&&Da():c&&(p(`worker: received unknown command ${c}`),p(d)))}catch(e){throw Ea(),e;}}self.onmessage=a}var z,A,Fa,C,D,Ga,G,H,Ha=!1;function qa(){var a=x.buffer;h.HEAP8=z=new Int8Array(a);Fa=new Int16Array(a);h.HEAPU8=A=new Uint8Array(a);new Uint16Array(a);h.HEAP32=C=new Int32Array(a);h.HEAPU32=D=new Uint32Array(a);Ga=new Float32Array(a);G=new Float64Array(a);H=new BigInt64Array(a);new BigUint64Array(a)} +function Ia(){Ha=!0;n?ua():I.Va()}function J(a){a="Aborted("+a+")";p(a);pa=!0;a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info.");sa?.(a);throw a;}var Ja;async function Ka(a){if(!q)try{var b=await ha(a);return new Uint8Array(b)}catch{}if(a==Ja&&q)a=new Uint8Array(q);else if(ia)a=ia(a);else throw"both async and sync fetching of the wasm failed";return a} +async function La(a,b){try{var d=await Ka(a);return await WebAssembly.instantiate(d,b)}catch(c){p(`failed to asynchronously prepare wasm: ${c}`),J(c)}}async function Na(a){var b=Ja;if(!q&&!ja(b)&&!m)try{var d=fetch(b,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(d,a)}catch(c){p(`wasm streaming compile failed: ${c}`),p("falling back to ArrayBuffer instantiation")}return La(b,a)} +function Oa(){Pa={T:Qa,f:Ra,w:Sa,e:Ta,k:Ua,h:Va,L:Wa,b:Xa,G:Ya,ua:Za,j:$a,M:ab,La:bb,qa:cb,sa:db,Ma:eb,Ja:fb,Ca:gb,Ia:hb,Z:ib,ra:jb,oa:kb,Ka:lb,pa:mb,Ra:nb,Fa:ob,ma:pb,va:qb,ja:rb,U:sb,Ea:Ba,Oa:tb,za:ub,Aa:vb,Ba:wb,xa:xb,ya:yb,ka:zb,Ta:Ab,Qa:Bb,W:Cb,V:Db,Pa:Eb,F:Fb,Na:Gb,na:Hb,u:Ib,H:Jb,S:Kb,la:Lb,ba:Mb,Ua:Nb,Ga:Ob,Ha:Pb,ta:Qb,I:Rb,wa:Sb,Y:Tb,Da:Ub,X:Vb,$:Wb,N:Xb,aa:Yb,O:Zb,v:$b,d:ac,m:bc,n:cc,r:dc,ca:ec,E:fc,o:gc,P:hc,C:ic,J:jc,da:kc,ea:lc,z:mc,fa:nc,Q:oc,ga:pc,y:qc,D:rc,c:sc,q:tc,i:uc,_:vc,l:wc, +p:xc,s:yc,t:zc,x:Ac,R:Bc,A:Cc,K:Dc,B:Ec,ha:Fc,ia:Gc,g:Hc,a:x,Sa:Ic};return{a:Pa}} +async function wa(){function a(c,e){I=c.exports;I=Jc();Kc.push(I.xb);c=I;h._OrtInit=c.Wa;h._OrtGetLastError=c.Xa;h._OrtCreateSessionOptions=c.Ya;h._OrtAppendExecutionProvider=c.Za;h._OrtAddFreeDimensionOverride=c._a;h._OrtAddSessionConfigEntry=c.$a;h._OrtReleaseSessionOptions=c.ab;h._OrtCreateSession=c.bb;h._OrtReleaseSession=c.cb;h._OrtGetInputOutputCount=c.db;h._OrtGetInputOutputMetadata=c.eb;h._OrtFree=c.fb;h._OrtCreateTensor=c.gb;h._OrtGetTensorData=c.hb;h._OrtReleaseTensor=c.ib;h._OrtCreateRunOptions= +c.jb;h._OrtAddRunConfigEntry=c.kb;h._OrtReleaseRunOptions=c.lb;h._OrtCreateBinding=c.mb;h._OrtBindInput=c.nb;h._OrtBindOutput=c.ob;h._OrtClearBoundOutputs=c.pb;h._OrtReleaseBinding=c.qb;h._OrtRunWithBinding=c.rb;h._OrtRun=c.sb;h._OrtEndProfiling=c.tb;Lc=c.ub;Mc=h._free=c.vb;Nc=h._malloc=c.wb;za=c.zb;Ea=c.Ab;Oc=c.Bb;Pc=c.Cb;Qc=c.Db;Rc=c.Eb;Sc=c.Fb;K=c.Gb;L=c.Hb;Tc=c.Ib;M=c.Jb;Uc=c.Kb;N=c.Lb;Vc=c.Mb;Wc=c.Nb;Xc=c.Ob;Yc=c.Pb;Zc=c.yb;r=e;return I}var b=Oa();if(h.instantiateWasm)return new Promise(c=>{h.instantiateWasm(b, +(e,f)=>{c(a(e,f))})});if(n){var d=new WebAssembly.Instance(r,Oa());return a(d,r)}Ja??=h.locateFile?h.locateFile?h.locateFile("ort-wasm-simd-threaded.wasm",fa):fa+"ort-wasm-simd-threaded.wasm":(new URL("ort-wasm-simd-threaded.wasm",import.meta.url)).href;return function(c){return a(c.instance,c.module)}(await Na(b))}class $c{name="ExitStatus";constructor(a){this.message=`Program terminated with exit(${a})`;this.status=a}} +var ad=a=>{a.terminate();a.onmessage=()=>{}},bd=[],O=0,P=null,ed=a=>{0==Q.length&&(cd(),dd(Q[0]));var b=Q.pop();if(!b)return 6;R.push(b);S[a.Qb]=b;b.Qb=a.Qb;var d={Rb:"run",dc:a.cc,Vb:a.Vb,Qb:a.Qb};m&&b.unref();b.postMessage(d,a.Zb);return 0},T=0,U=(a,b,...d)=>{var c=16*d.length,e=N(),f=Uc(c),g=f>>>3,l;for(l of d)"bigint"==typeof l?((v(),H)[g++>>>0]=1n,(v(),H)[g++>>>0]=l):((v(),H)[g++>>>0]=0n,(v(),G)[g++>>>0]=l);a=Oc(a,0,c,f,b);M(e);return a}; +function Ic(a){if(n)return U(0,1,a);t=a;if(!(0{t=a;if(n)throw fd(a),"unwind";Ic(a)},Q=[],R=[],Kc=[],S={};function gd(){for(var a=h.numThreads-1;a--;)cd();bd.push(async()=>{var b=hd();O++;await b;O--;0==O&&P&&(b=P,P=null,b())})}var jd=a=>{var b=a.Qb;delete S[b];Q.push(a);R.splice(R.indexOf(a),1);a.Qb=0;Pc(b)};function Aa(){Kc.forEach(a=>a())} +var dd=a=>new Promise(b=>{a.onmessage=f=>{var g=f.data;f=g.Rb;if(g.Ub&&g.Ub!=Lc()){var l=S[g.Ub];l?l.postMessage(g,g.Zb):p(`Internal error! Worker sent a message "${f}" to target pthread ${g.Ub}, but that thread no longer exists!`)}else if("checkMailbox"===f)Da();else if("spawnThread"===f)ed(g);else if("cleanupThread"===f)kd(()=>{jd(S[g.ec])});else if("loaded"===f)a.loaded=!0,m&&!a.Qb&&a.unref(),b(a);else if("setimmediate"===g.target)a.postMessage(g);else if("uncaughtException"===f)a.onerror(g.error); +else if("callHandler"===f)h[g.$b](...g.args);else f&&p(`worker sent an unknown command ${f}`)};a.onerror=f=>{p(`${"worker sent an error!"} ${f.filename}:${f.lineno}: ${f.message}`);throw f;};m&&(a.on("message",f=>a.onmessage({data:f})),a.on("error",f=>a.onerror(f)));var d=[],c=[],e;for(e of c)h.propertyIsEnumerable(e)&&d.push(e);a.postMessage({Rb:"load",ac:d,fc:x,hc:r})});async function hd(){if(!n)return Promise.all(Q.map(dd))} +function cd(){var a=new Worker(new URL(import.meta.url),{type:"module",workerData:"em-pthread",name:"em-pthread"});Q.push(a)}function ya(a){var b=(v(),D)[a+52>>>2>>>0];a=(v(),D)[a+56>>>2>>>0];Tc(b,b-a);M(b)}var ld=[],V=a=>{var b=ld[a];b||(ld[a]=b=Zc.get(a));return b},Ca=(a,b)=>{T=0;a=V(a)(b);0>>=0;var b=new od(a);0==(v(),z)[b.Sb+12>>>0]&&(pd(b,!0),nd--);qd(b,!1);md.push(b);return Yc(a)} +var W=0,Sa=()=>{K(0,0);var a=md.pop();Vc(a.Wb);W=0};function pd(a,b){b=b?1:0;(v(),z)[a.Sb+12>>>0]=b}function qd(a,b){b=b?1:0;(v(),z)[a.Sb+13>>>0]=b}class od{constructor(a){this.Wb=a;this.Sb=a-24}}var rd=a=>{var b=W;if(!b)return L(0),0;var d=new od(b);(v(),D)[d.Sb+16>>>2>>>0]=b;var c=(v(),D)[d.Sb+4>>>2>>>0];if(!c)return L(0),b;for(var e of a){if(0===e||e===c)break;if(Xc(e,c,d.Sb+16))return L(e),b}L(c);return b};function Ta(){return rd([])}function Ua(a){return rd([a>>>0])} +function Va(a,b,d,c){return rd([a>>>0,b>>>0,d>>>0,c>>>0])}var Wa=()=>{var a=md.pop();a||J("no exception to throw");var b=a.Wb;0==(v(),z)[a.Sb+13>>>0]&&(md.push(a),qd(a,!0),pd(a,!1),nd++);Wc(b);W=b;throw W;};function Xa(a,b,d){a>>>=0;var c=new od(a);b>>>=0;d>>>=0;(v(),D)[c.Sb+16>>>2>>>0]=0;(v(),D)[c.Sb+4>>>2>>>0]=b;(v(),D)[c.Sb+8>>>2>>>0]=d;Wc(a);W=a;nd++;throw W;}var Ya=()=>nd;function sd(a,b,d,c){return n?U(2,1,a,b,d,c):Za(a,b,d,c)} +function Za(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;if(!globalThis.SharedArrayBuffer)return 6;var e=[];if(n&&0===e.length)return sd(a,b,d,c);a={cc:d,Qb:a,Vb:c,Zb:e};return n?(a.Rb="spawnThread",postMessage(a,e),0):ed(a)}function $a(a){W||=a>>>0;throw W;} +var td=globalThis.TextDecoder&&new TextDecoder,ud=(a,b=0,d,c)=>{b>>>=0;var e=b;d=e+d;if(c)c=d;else{for(;a[e]&&!(e>=d);)++e;c=e}if(16d?e+=String.fromCharCode(d):(d-=65536,e+=String.fromCharCode(55296|d>>10,56320| +d&1023))}}else e+=String.fromCharCode(d);return e},vd=(a,b,d)=>(a>>>=0)?ud((v(),A),a,b,d):"";function ab(a,b,d){return n?U(3,1,a,b,d):0}function bb(a,b){if(n)return U(4,1,a,b)}function cb(a,b){if(n)return U(5,1,a,b)}function db(a,b,d){if(n)return U(6,1,a,b,d)}function eb(a,b,d){return n?U(7,1,a,b,d):0}function fb(a,b){if(n)return U(8,1,a,b)}function gb(a,b,d){if(n)return U(9,1,a,b,d)}function hb(a,b,d,c){if(n)return U(10,1,a,b,d,c)}function ib(a,b,d,c){if(n)return U(11,1,a,b,d,c)} +function jb(a,b,d,c){if(n)return U(12,1,a,b,d,c)}function kb(a){if(n)return U(13,1,a)}function lb(a,b){if(n)return U(14,1,a,b)}function mb(a,b,d){if(n)return U(15,1,a,b,d)}var nb=()=>J("");function ob(a){za(a>>>0,!k,1,!aa,131072,!1);Aa()} +var kd=a=>{if(!pa)try{if(a(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ba(a){a>>>=0;wd||(Atomics.waitAsync((v(),C),a>>>2,a).value.then(Da),a+=128,Atomics.store((v(),C),a>>>2,1))}var Da=()=>kd(()=>{var a=Lc();a&&(Ba(a),Sc())}); +function pb(a,b){a>>>=0;a==b>>>0?setTimeout(Da):n?postMessage({Ub:a,Rb:"checkMailbox"}):(a=S[a])&&a.postMessage({Rb:"checkMailbox"})}var xd=[];function qb(a,b,d,c,e){b>>>=0;e>>>=0;xd.length=0;d=e>>>3;for(c=e+c>>>3;d>>0]?f=(v(),H)[d++>>>0]:f=(v(),G)[d++>>>0];xd.push(f)}return(b?yd[b]:zd[a])(...xd)}var rb=()=>{T=0};function sb(a){a>>>=0;n?postMessage({Rb:"cleanupThread",ec:a}):jd(S[a])}function tb(a){m&&S[a>>>0].ref()} +function ub(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);(v(),C)[b>>>2>>>0]=a.getUTCSeconds();(v(),C)[b+4>>>2>>>0]=a.getUTCMinutes();(v(),C)[b+8>>>2>>>0]=a.getUTCHours();(v(),C)[b+12>>>2>>>0]=a.getUTCDate();(v(),C)[b+16>>>2>>>0]=a.getUTCMonth();(v(),C)[b+20>>>2>>>0]=a.getUTCFullYear()-1900;(v(),C)[b+24>>>2>>>0]=a.getUTCDay();a=(a.getTime()-Date.UTC(a.getUTCFullYear(),0,1,0,0,0,0))/864E5|0;(v(),C)[b+28>>>2>>>0]=a} +var Ad=a=>0===a%4&&(0!==a%100||0===a%400),Bd=[0,31,60,91,121,152,182,213,244,274,305,335],Cd=[0,31,59,90,120,151,181,212,243,273,304,334]; +function vb(a,b){a=-9007199254740992>a||9007199254740992>>=0;a=new Date(1E3*a);(v(),C)[b>>>2>>>0]=a.getSeconds();(v(),C)[b+4>>>2>>>0]=a.getMinutes();(v(),C)[b+8>>>2>>>0]=a.getHours();(v(),C)[b+12>>>2>>>0]=a.getDate();(v(),C)[b+16>>>2>>>0]=a.getMonth();(v(),C)[b+20>>>2>>>0]=a.getFullYear()-1900;(v(),C)[b+24>>>2>>>0]=a.getDay();var d=(Ad(a.getFullYear())?Bd:Cd)[a.getMonth()]+a.getDate()-1|0;(v(),C)[b+28>>>2>>>0]=d;(v(),C)[b+36>>>2>>>0]=-(60*a.getTimezoneOffset());d=(new Date(a.getFullYear(), +6,1)).getTimezoneOffset();var c=(new Date(a.getFullYear(),0,1)).getTimezoneOffset();a=(d!=c&&a.getTimezoneOffset()==Math.min(c,d))|0;(v(),C)[b+32>>>2>>>0]=a} +function wb(a){a>>>=0;var b=new Date((v(),C)[a+20>>>2>>>0]+1900,(v(),C)[a+16>>>2>>>0],(v(),C)[a+12>>>2>>>0],(v(),C)[a+8>>>2>>>0],(v(),C)[a+4>>>2>>>0],(v(),C)[a>>>2>>>0],0),d=(v(),C)[a+32>>>2>>>0],c=b.getTimezoneOffset(),e=(new Date(b.getFullYear(),6,1)).getTimezoneOffset(),f=(new Date(b.getFullYear(),0,1)).getTimezoneOffset(),g=Math.min(f,e);0>d?(v(),C)[a+32>>>2>>>0]=Number(e!=f&&g==c):0>>2>>>0]=b.getDay();d=(Ad(b.getFullYear())? +Bd:Cd)[b.getMonth()]+b.getDate()-1|0;(v(),C)[a+28>>>2>>>0]=d;(v(),C)[a>>>2>>>0]=b.getSeconds();(v(),C)[a+4>>>2>>>0]=b.getMinutes();(v(),C)[a+8>>>2>>>0]=b.getHours();(v(),C)[a+12>>>2>>>0]=b.getDate();(v(),C)[a+16>>>2>>>0]=b.getMonth();(v(),C)[a+20>>>2>>>0]=b.getYear();a=b.getTime();return BigInt(isNaN(a)?-1:a/1E3)}function xb(a,b,d,c,e,f,g){return n?U(16,1,a,b,d,c,e,f,g):-52}function yb(a,b,d,c,e,f){if(n)return U(17,1,a,b,d,c,e,f)}var X={},Ib=()=>performance.timeOrigin+performance.now(); +function zb(a,b){if(n)return U(18,1,a,b);X[a]&&(clearTimeout(X[a].id),delete X[a]);if(!b)return 0;var d=setTimeout(()=>{delete X[a];kd(()=>Rc(a,performance.timeOrigin+performance.now()))},b);X[a]={id:d,oc:b};return 0} +var Y=(a,b,d)=>{var c=(v(),A);b>>>=0;if(0=g){if(b>=d)break;c[b++>>>0]=g}else if(2047>=g){if(b+1>=d)break;c[b++>>>0]=192|g>>6;c[b++>>>0]=128|g&63}else if(65535>=g){if(b+2>=d)break;c[b++>>>0]=224|g>>12;c[b++>>>0]=128|g>>6&63;c[b++>>>0]=128|g&63}else{if(b+3>=d)break;c[b++>>>0]=240|g>>18;c[b++>>>0]=128|g>>12&63;c[b++>>>0]=128|g>>6&63;c[b++>>>0]=128|g&63;f++}}c[b>>>0]=0;a=b-e}else a=0;return a}; +function Ab(a,b,d,c){a>>>=0;b>>>=0;d>>>=0;c>>>=0;var e=(new Date).getFullYear(),f=(new Date(e,0,1)).getTimezoneOffset();e=(new Date(e,6,1)).getTimezoneOffset();var g=Math.max(f,e);(v(),D)[a>>>2>>>0]=60*g;(v(),C)[b>>>2>>>0]=Number(f!=e);b=l=>{var u=Math.abs(l);return`UTC${0<=l?"-":"+"}${String(Math.floor(u/60)).padStart(2,"0")}${String(u%60).padStart(2,"0")}`};a=b(f);b=b(e);eDate.now(),Dd=1; +function Bb(a,b,d){d>>>=0;if(!(0<=a&&3>=a))return 28;if(0===a)a=Date.now();else if(Dd)a=performance.timeOrigin+performance.now();else return 52;a=Math.round(1E6*a);(v(),H)[d>>>3>>>0]=BigInt(a);return 0}var Ed=[];function Cb(a,b,d){a>>>=0;b>>>=0;d>>>=0;Ed.length=0;for(var c;c=(v(),A)[b++>>>0];){var e=105!=c;e&=112!=c;d+=e&&d%8?4:0;Ed.push(112==c?(v(),D)[d>>>2>>>0]:106==c?(v(),H)[d>>>3>>>0]:105==c?(v(),C)[d>>>2>>>0]:(v(),G)[d>>>3>>>0]);d+=e?8:4}return yd[a](...Ed)}var Db=()=>{}; +function Fb(a,b){return p(vd(a>>>0,b>>>0))}var Gb=()=>{T+=1;throw"unwind";};function Hb(){return 4294901760}var Jb=()=>m?require("os").cpus().length:navigator.hardwareConcurrency,Z={},Fd=a=>{for(var b=0,d=0;d=c?b++:2047>=c?b+=2:55296<=c&&57343>=c?(b+=4,++d):b+=3}return b},Gd=a=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(a))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(a))?2147483648|+b[1]:0},Hd=a=>{for(var b of a)(a=Gd(b))&&(Z[a]=b)}; +function Mb(){var a=Error().stack.toString().split("\n");"Error"==a[0]&&a.shift();Hd(a);Z.Xb=Gd(a[3]);Z.bc=a;return Z.Xb}function Kb(a){a=Z[a>>>0];if(!a)return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(a))a=b[1];else if(b=/^(.+?)@/.exec(a))a=b[1];else return 0;Mc(Kb.Yb??0);b=Fd(a)+1;var d=Nc(b);d&&Y(a,d,b);Kb.Yb=d;return Kb.Yb} +function Lb(a){a>>>=0;var b=(v(),A).length;if(a<=b||4294901760=d;d*=2){var c=b*(1+.2/d);c=Math.min(c,a+100663296);a:{c=(Math.min(4294901760,65536*Math.ceil(Math.max(a,c)/65536))-x.buffer.byteLength+65535)/65536|0;try{x.grow(c);qa();var e=1;break a}catch(f){}e=void 0}if(e)return!0}return!1} +function Nb(a,b,d){a>>>=0;b>>>=0;if(Z.Xb==a)var c=Z.bc;else c=Error().stack.toString().split("\n"),"Error"==c[0]&&c.shift(),Hd(c);for(var e=3;c[e]&&Gd(c[e])!=a;)++e;for(a=0;a>>2>>>0]=Gd(c[a+e]);return a} +var Id={},Kd=()=>{if(!Jd){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:ca||"./this.program"},b;for(b in Id)void 0===Id[b]?delete a[b]:a[b]=Id[b];var d=[];for(b in a)d.push(`${b}=${a[b]}`);Jd=d}return Jd},Jd;function Ob(a,b){if(n)return U(19,1,a,b);a>>>=0;b>>>=0;var d=0,c=0,e;for(e of Kd()){var f=b+d;(v(),D)[a+c>>>2>>>0]=f;d+=Y(e,f,Infinity)+1;c+=4}return 0} +function Pb(a,b){if(n)return U(20,1,a,b);a>>>=0;b>>>=0;var d=Kd();(v(),D)[a>>>2>>>0]=d.length;a=0;for(var c of d)a+=Fd(c)+1;(v(),D)[b>>>2>>>0]=a;return 0}function Rb(a){return n?U(21,1,a):52}function Sb(a,b,d,c,e){return n?U(22,1,a,b,d,c,e):52}function Tb(a,b,d,c){return n?U(23,1,a,b,d,c):52}function Ub(a,b,d,c){return n?U(24,1,a,b,d,c):70}var Ld=[null,[],[]]; +function Vb(a,b,d,c){if(n)return U(25,1,a,b,d,c);b>>>=0;d>>>=0;c>>>=0;for(var e=0,f=0;f>>2>>>0],l=(v(),D)[b+4>>>2>>>0];b+=8;for(var u=0;u>>0],B=Ld[w];0===y||10===y?((1===w?oa:p)(ud(B)),B.length=0):B.push(y)}e+=l}(v(),D)[c>>>2>>>0]=e;return 0}function Hc(a){return a>>>0}n||gd();n||(x=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),qa());h.wasmBinary&&(q=h.wasmBinary);h.stackSave=()=>N();h.stackRestore=a=>M(a);h.stackAlloc=a=>Uc(a); +h.setValue=function(a,b,d="i8"){d.endsWith("*")&&(d="*");switch(d){case "i1":(v(),z)[a>>>0]=b;break;case "i8":(v(),z)[a>>>0]=b;break;case "i16":(v(),Fa)[a>>>1>>>0]=b;break;case "i32":(v(),C)[a>>>2>>>0]=b;break;case "i64":(v(),H)[a>>>3>>>0]=BigInt(b);break;case "float":(v(),Ga)[a>>>2>>>0]=b;break;case "double":(v(),G)[a>>>3>>>0]=b;break;case "*":(v(),D)[a>>>2>>>0]=b;break;default:J(`invalid type for setValue: ${d}`)}}; +h.getValue=function(a,b="i8"){b.endsWith("*")&&(b="*");switch(b){case "i1":return(v(),z)[a>>>0];case "i8":return(v(),z)[a>>>0];case "i16":return(v(),Fa)[a>>>1>>>0];case "i32":return(v(),C)[a>>>2>>>0];case "i64":return(v(),H)[a>>>3>>>0];case "float":return(v(),Ga)[a>>>2>>>0];case "double":return(v(),G)[a>>>3>>>0];case "*":return(v(),D)[a>>>2>>>0];default:J(`invalid type for getValue: ${b}`)}};h.UTF8ToString=vd;h.stringToUTF8=Y;h.lengthBytesUTF8=Fd; +var zd=[Ic,fd,sd,ab,bb,cb,db,eb,fb,gb,hb,ib,jb,kb,lb,mb,xb,yb,zb,Ob,Pb,Rb,Sb,Tb,Ub,Vb],yd={1043436:(a,b,d,c,e)=>{if("undefined"==typeof h||!h.Tb)return 1;a=vd(Number(a>>>0));a.startsWith("./")&&(a=a.substring(2));a=h.Tb.get(a);if(!a)return 2;b=Number(b>>>0);d=Number(d>>>0);c=Number(c>>>0);if(b+d>a.byteLength)return 3;try{const f=a.subarray(b,b+d);switch(e){case 0:(v(),A).set(f,c>>>0);break;case 1:h.ic?h.ic(c,f):h.kc(c,f);break;default:return 4}return 0}catch{return 4}},1044260:()=>"undefined"!==typeof wasmOffsetConverter}; +function Qa(){return"undefined"!==typeof wasmOffsetConverter}var Lc,Mc,Nc,za,Ea,Oc,Pc,Qc,Rc,Sc,K,L,Tc,M,Uc,N,Vc,Wc,Xc,Yc,Zc,Pa;function cc(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function bc(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function sc(a){var b=N();try{V(a)()}catch(d){M(b);if(d!==d+0)throw d;K(1,0)}}function ac(a,b){var d=N();try{return V(a)(b)}catch(c){M(d);if(c!==c+0)throw c;K(1,0)}} +function uc(a,b,d){var c=N();try{V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function tc(a,b){var d=N();try{V(a)(b)}catch(c){M(d);if(c!==c+0)throw c;K(1,0)}}function gc(a,b,d,c,e,f,g){var l=N();try{return V(a)(b,d,c,e,f,g)}catch(u){M(l);if(u!==u+0)throw u;K(1,0)}}function yc(a,b,d,c,e,f){var g=N();try{V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}function wc(a,b,d,c){var e=N();try{V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}} +function xc(a,b,d,c,e){var f=N();try{V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0)}}function zc(a,b,d,c,e,f,g){var l=N();try{V(a)(b,d,c,e,f,g)}catch(u){M(l);if(u!==u+0)throw u;K(1,0)}}function Gc(a,b,d,c,e,f,g){var l=N();try{V(a)(b,d,c,e,f,g)}catch(u){M(l);if(u!==u+0)throw u;K(1,0)}}function Fc(a,b,d,c,e,f,g,l){var u=N();try{V(a)(b,d,c,e,f,g,l)}catch(w){M(u);if(w!==w+0)throw w;K(1,0)}}function dc(a,b,d,c,e){var f=N();try{return V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0)}} +function mc(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function Ac(a,b,d,c,e,f,g,l){var u=N();try{V(a)(b,d,c,e,f,g,l)}catch(w){M(u);if(w!==w+0)throw w;K(1,0)}}function Dc(a,b,d,c,e,f,g,l,u,w,y,B){var E=N();try{V(a)(b,d,c,e,f,g,l,u,w,y,B)}catch(F){M(E);if(F!==F+0)throw F;K(1,0)}}function qc(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0);return 0n}} +function Bc(a,b,d,c,e,f,g,l,u){var w=N();try{V(a)(b,d,c,e,f,g,l,u)}catch(y){M(w);if(y!==y+0)throw y;K(1,0)}}function $b(a){var b=N();try{return V(a)()}catch(d){M(b);if(d!==d+0)throw d;K(1,0)}}function pc(a,b){var d=N();try{return V(a)(b)}catch(c){M(d);if(c!==c+0)throw c;K(1,0);return 0n}}function nc(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function oc(a){var b=N();try{return V(a)()}catch(d){M(b);if(d!==d+0)throw d;K(1,0);return 0n}} +function lc(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function kc(a,b,d,c,e){var f=N();try{return V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0)}}function jc(a,b,d,c,e,f){var g=N();try{return V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}function fc(a,b,d,c,e,f){var g=N();try{return V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}} +function ec(a,b,d,c,e,f){var g=N();try{return V(a)(b,d,c,e,f)}catch(l){M(g);if(l!==l+0)throw l;K(1,0)}}function hc(a,b,d,c,e,f,g,l){var u=N();try{return V(a)(b,d,c,e,f,g,l)}catch(w){M(u);if(w!==w+0)throw w;K(1,0)}}function rc(a,b,d,c,e){var f=N();try{return V(a)(b,d,c,e)}catch(g){M(f);if(g!==g+0)throw g;K(1,0);return 0n}}function Zb(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}} +function Xb(a,b,d,c){var e=N();try{return V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function ic(a,b,d,c,e,f,g,l,u,w,y,B){var E=N();try{return V(a)(b,d,c,e,f,g,l,u,w,y,B)}catch(F){M(E);if(F!==F+0)throw F;K(1,0)}}function Cc(a,b,d,c,e,f,g,l,u,w,y){var B=N();try{V(a)(b,d,c,e,f,g,l,u,w,y)}catch(E){M(B);if(E!==E+0)throw E;K(1,0)}}function Ec(a,b,d,c,e,f,g,l,u,w,y,B,E,F,Md,Nd){var Od=N();try{V(a)(b,d,c,e,f,g,l,u,w,y,B,E,F,Md,Nd)}catch(Ma){M(Od);if(Ma!==Ma+0)throw Ma;K(1,0)}} +function Yb(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function Wb(a,b,d){var c=N();try{return V(a)(b,d)}catch(e){M(c);if(e!==e+0)throw e;K(1,0)}}function vc(a,b,d,c){var e=N();try{V(a)(b,d,c)}catch(f){M(e);if(f!==f+0)throw f;K(1,0)}}function Jc(){var a=I;a=Object.assign({},a);var b=c=>()=>c()>>>0,d=c=>e=>c(e)>>>0;a.ub=b(a.ub);a.wb=d(a.wb);a.Kb=d(a.Kb);a.Lb=b(a.Lb);a.Pb=d(a.Pb);return a} +function xa(){if(0{ra=a;sa=b}); +;return moduleRtn}export default ortWasmThreaded;var isPthread=globalThis.self?.name?.startsWith("em-pthread");var isNode=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(isNode)isPthread=(await import("worker_threads")).workerData==="em-pthread";isPthread&&ortWasmThreaded(); diff --git a/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.wasm b/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.wasm index 8e3d3448..ea2919c2 100644 Binary files a/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.wasm and b/workloads/transformersjs/build/onnxruntime-web/ort-wasm-simd-threaded.wasm differ diff --git a/workloads/transformersjs/build/transformers.js b/workloads/transformersjs/build/transformers.js index e1c43113..1bbc9285 100644 --- a/workloads/transformersjs/build/transformers.js +++ b/workloads/transformersjs/build/transformers.js @@ -1,42371 +1,37313 @@ -/******/ var __webpack_modules__ = ({ - -/***/ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm": -/*!****************************************************************************!*\ - !*** ./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm ***! - \****************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = __webpack_require__.p + "ort-wasm-simd-threaded.jsep.wasm"; - -/***/ }), - -/***/ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb": -/*!**************************************************************!*\ - !*** ./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs ***! - \**************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = __webpack_require__.p + "ort.bundle.min.mjs"; - -/***/ }), - -/***/ "?2ce3": -/*!**********************************!*\ - !*** onnxruntime-node (ignored) ***! - \**********************************/ -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ "?7992": -/*!*************************!*\ - !*** node:fs (ignored) ***! - \*************************/ -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ "?5af5": -/*!***************************!*\ - !*** node:path (ignored) ***! - \***************************/ -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ "?2b25": -/*!***********************!*\ - !*** sharp (ignored) ***! - \***********************/ -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ "?db59": -/*!*************************!*\ - !*** node:fs (ignored) ***! - \*************************/ -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ "?383f": -/*!***************************!*\ - !*** node:path (ignored) ***! - \***************************/ -/***/ (() => { - -/* (ignored) */ - -/***/ }), - -/***/ "?fa4b": -/*!**************************!*\ - !*** node:url (ignored) ***! - \**************************/ -/***/ (() => { - -/* (ignored) */ +var __defProp = Object.defineProperty; +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; -/***/ }), +// ignore-modules:node:fs +var node_fs_default = {}; + +// ignore-modules:node:path +var node_path_default = {}; + +// ignore-modules:node:url +var node_url_default = {}; + +// src/env.js +var VERSION = "4.3.2"; +var HAS_SELF = typeof self !== "undefined"; +var IS_FS_AVAILABLE = !isEmpty(node_fs_default); +var IS_PATH_AVAILABLE = !isEmpty(node_path_default); +var IS_WEB_CACHE_AVAILABLE = HAS_SELF && "caches" in self; +var IS_DENO_RUNTIME = typeof globalThis.Deno !== "undefined"; +var IS_BUN_RUNTIME = typeof globalThis.Bun !== "undefined"; +var IS_DENO_WEB_RUNTIME = IS_DENO_RUNTIME && IS_WEB_CACHE_AVAILABLE && !IS_FS_AVAILABLE; +var IS_PROCESS_AVAILABLE = typeof process !== "undefined"; +var IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === "node" && !IS_DENO_WEB_RUNTIME; +var IS_BROWSER_ENV = typeof window !== "undefined" && typeof window.document !== "undefined"; +var IS_WEBWORKER_ENV = HAS_SELF && ["DedicatedWorkerGlobalScope", "ServiceWorkerGlobalScope", "SharedWorkerGlobalScope"].includes( + self.constructor?.name +); +var IS_WEB_ENV = IS_BROWSER_ENV || IS_WEBWORKER_ENV || IS_DENO_WEB_RUNTIME; +var IS_WEBGPU_AVAILABLE = IS_NODE_ENV || typeof navigator !== "undefined" && "gpu" in navigator; +var IS_WEBNN_AVAILABLE = typeof navigator !== "undefined" && "ml" in navigator; +var IS_CRYPTO_AVAILABLE = typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function"; +var IS_CHROME_AVAILABLE = ( + // @ts-ignore - chrome may not exist in all environments + typeof chrome !== "undefined" && typeof chrome.runtime !== "undefined" && typeof chrome.runtime.id === "string" +); +var IS_SERVICE_WORKER_ENV = ( + // @ts-ignore - ServiceWorkerGlobalScope may not exist in all environments + typeof ServiceWorkerGlobalScope !== "undefined" && HAS_SELF && self instanceof ServiceWorkerGlobalScope +); +var isSafariBelow26 = () => { + if (typeof navigator === "undefined") { + return false; + } + const userAgent = navigator.userAgent; + const isSafari = (navigator.vendor || "").indexOf("Apple") > -1 && !userAgent.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i) && !userAgent.includes("Chrome") && !userAgent.includes("Android"); + if (!isSafari) { + return false; + } + const match = userAgent.match(/Version\/(\d+)/); + return match ? parseInt(match[1], 10) < 26 : false; +}; +var IS_SAFARI_BELOW_26 = isSafariBelow26(); +var apis = Object.freeze({ + /** Whether we are running in a browser environment (and not a web worker) */ + IS_BROWSER_ENV, + /** Whether we are running in a web worker environment */ + IS_WEBWORKER_ENV, + /** Whether we are running in a web-like environment (browser, web worker, or Deno web runtime) */ + IS_WEB_ENV, + /** Whether we are running in a service worker environment */ + IS_SERVICE_WORKER_ENV, + /** Whether we are running in Deno's web runtime (CDN imports, Cache API available, no filesystem) */ + IS_DENO_WEB_RUNTIME, + /** Whether the Cache API is available */ + IS_WEB_CACHE_AVAILABLE, + /** Whether the WebGPU API is available */ + IS_WEBGPU_AVAILABLE, + /** Whether the WebNN API is available */ + IS_WEBNN_AVAILABLE, + /** Whether we are running in a Safari browser older than version 26. */ + IS_SAFARI_BELOW_26, + /** Whether the Node.js process API is available */ + IS_PROCESS_AVAILABLE, + /** Whether we are running in a Node.js-like environment (node, deno, bun) */ + IS_NODE_ENV, + /** Whether the filesystem API is available */ + IS_FS_AVAILABLE, + /** Whether the path API is available */ + IS_PATH_AVAILABLE, + /** Whether the crypto API is available */ + IS_CRYPTO_AVAILABLE, + /** Whether the Chrome runtime API is available */ + IS_CHROME_AVAILABLE +}); +var RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; +var dirname__ = "./"; +if (RUNNING_LOCALLY) { + const _import_meta_url = import.meta.url; + if (_import_meta_url) { + dirname__ = node_path_default.dirname(node_path_default.dirname(node_url_default.fileURLToPath(_import_meta_url))); + } else if (typeof __dirname !== "undefined") { + dirname__ = node_path_default.dirname(__dirname); + } +} +var DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? node_path_default.join(dirname__, "/.cache/") : null; +var DEFAULT_LOCAL_MODEL_PATH = "/models/"; +var localModelPath = RUNNING_LOCALLY ? node_path_default.join(dirname__, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH; +var DEFAULT_FETCH = typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : void 0; +var LogLevel = Object.freeze({ + /** All messages including debug output (value: 10) */ + DEBUG: 10, + /** Errors, warnings, and info messages (value: 20) */ + INFO: 20, + /** Errors and warnings (value: 30) */ + WARNING: 30, + /** Only error messages (value: 40) */ + ERROR: 40, + /** No logging output (value: 50) */ + NONE: 50 +}); +var logLevel = LogLevel.WARNING; +var env = { + version: VERSION, + /////////////////// Backends settings /////////////////// + // NOTE: These will be populated later by the backends themselves. + backends: { + // onnxruntime-web/onnxruntime-node + onnx: {} + }, + /////////////////// Logging settings /////////////////// + get logLevel() { + return logLevel; + }, + set logLevel(level) { + logLevel = level; + env.backends.onnx?.setLogLevel?.(level); + }, + /////////////////// Model settings /////////////////// + allowRemoteModels: true, + remoteHost: "https://huggingface.co/", + remotePathTemplate: "{model}/resolve/{revision}/", + allowLocalModels: !(IS_BROWSER_ENV || IS_WEBWORKER_ENV || IS_DENO_WEB_RUNTIME), + // Default to true for non-web environments, false for web environments + localModelPath, + useFS: IS_FS_AVAILABLE, + /////////////////// Cache settings /////////////////// + useBrowserCache: IS_WEB_CACHE_AVAILABLE, + useFSCache: IS_FS_AVAILABLE, + cacheDir: DEFAULT_CACHE_DIR, + useCustomCache: false, + customCache: null, + useWasmCache: IS_WEB_CACHE_AVAILABLE || IS_FS_AVAILABLE, + cacheKey: "transformers-cache", + experimental_useCrossOriginStorage: false, + /////////////////// Custom fetch ///////////////////// + fetch: DEFAULT_FETCH + ////////////////////////////////////////////////////// +}; +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} -/***/ "./node_modules/@huggingface/jinja/dist/index.js": -/*!*******************************************************!*\ - !*** ./node_modules/@huggingface/jinja/dist/index.js ***! - \*******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { +// src/utils/generic.js +var Callable = ( + /** @type {any} */ + class { + /** + * Creates a new instance of the Callable class. + */ + constructor() { + let closure = function(...args) { + return closure._call(...args); + }; + return Object.setPrototypeOf(closure, new.target.prototype); + } + /** + * This method should be implemented in subclasses to provide the + * functionality of the callable object. + * + * @param {any[]} args + * @throws {Error} If the subclass does not implement the `_call` method. + */ + _call(...args) { + throw Error("Must implement _call method in subclass"); + } + } +); -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Environment: () => (/* binding */ Environment), -/* harmony export */ Interpreter: () => (/* binding */ Interpreter), -/* harmony export */ Template: () => (/* binding */ Template), -/* harmony export */ parse: () => (/* binding */ parse), -/* harmony export */ tokenize: () => (/* binding */ tokenize) -/* harmony export */ }); -// src/lexer.ts -var TOKEN_TYPES = Object.freeze({ - Text: "Text", - // The text between Jinja statements or expressions - NumericLiteral: "NumericLiteral", - // e.g., 123, 1.0 - StringLiteral: "StringLiteral", - // 'string' - Identifier: "Identifier", - // Variables, functions, statements, booleans, etc. - Equals: "Equals", - // = - OpenParen: "OpenParen", - // ( - CloseParen: "CloseParen", - // ) - OpenStatement: "OpenStatement", - // {% - CloseStatement: "CloseStatement", - // %} - OpenExpression: "OpenExpression", - // {{ - CloseExpression: "CloseExpression", - // }} - OpenSquareBracket: "OpenSquareBracket", - // [ - CloseSquareBracket: "CloseSquareBracket", - // ] - OpenCurlyBracket: "OpenCurlyBracket", - // { - CloseCurlyBracket: "CloseCurlyBracket", - // } - Comma: "Comma", - // , - Dot: "Dot", - // . - Colon: "Colon", - // : - Pipe: "Pipe", - // | - CallOperator: "CallOperator", - // () - AdditiveBinaryOperator: "AdditiveBinaryOperator", - // + - ~ - MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator", - // * / % - ComparisonBinaryOperator: "ComparisonBinaryOperator", - // < > <= >= == != - UnaryOperator: "UnaryOperator", - // ! - + - Comment: "Comment" - // {# ... #} -}); -var Token = class { +// src/utils/core.js +function dispatchCallback(progress_callback, data) { + if (progress_callback) progress_callback(data); +} +var DefaultProgressCallback = class extends Callable { /** - * Constructs a new Token. - * @param {string} value The raw value as seen inside the source code. - * @param {TokenType} type The type of token. + * @param {ProgressCallback} callback The original callback. + * @param {FilesLoadingMap} files_loading Mutable map storing per-file progress. */ - constructor(value, type) { - this.value = value; - this.type = type; + constructor(callback, files_loading) { + super(); + this.callback = callback; + this.files_loading = files_loading; + this.loads = /* @__PURE__ */ new Map(); + } + /** + * @param {ProgressInfo} info + */ + _call(info) { + if (info.status === "progress") { + this.files_loading[info.file] = { + loaded: info.loaded, + total: info.total + }; + const loaded = Object.values(this.files_loading).reduce((acc, curr) => acc + curr.loaded, 0); + const total = Object.values(this.files_loading).reduce((acc, curr) => acc + curr.total, 0); + const progress = total > 0 ? loaded / total * 100 : 0; + this.callback({ + status: "progress_total", + name: info.name, + progress, + loaded, + total, + files: structuredClone(this.files_loading) + }); + } + this.callback(info); } }; -function isWord(char) { - return /\w/.test(char); +function isIntegralNumber(x) { + return Number.isInteger(x) || typeof x === "bigint"; } -function isInteger(char) { - return /[0-9]/.test(char); +function isNullishDimension(x) { + return x === null || x === void 0 || x === -1; } -var ORDERED_MAPPING_TABLE = [ - // Control sequences - ["{%", TOKEN_TYPES.OpenStatement], - ["%}", TOKEN_TYPES.CloseStatement], - ["{{", TOKEN_TYPES.OpenExpression], - ["}}", TOKEN_TYPES.CloseExpression], - // Single character tokens - ["(", TOKEN_TYPES.OpenParen], - [")", TOKEN_TYPES.CloseParen], - ["{", TOKEN_TYPES.OpenCurlyBracket], - ["}", TOKEN_TYPES.CloseCurlyBracket], - ["[", TOKEN_TYPES.OpenSquareBracket], - ["]", TOKEN_TYPES.CloseSquareBracket], - [",", TOKEN_TYPES.Comma], - [".", TOKEN_TYPES.Dot], - [":", TOKEN_TYPES.Colon], - ["|", TOKEN_TYPES.Pipe], - // Comparison operators - ["<=", TOKEN_TYPES.ComparisonBinaryOperator], - [">=", TOKEN_TYPES.ComparisonBinaryOperator], - ["==", TOKEN_TYPES.ComparisonBinaryOperator], - ["!=", TOKEN_TYPES.ComparisonBinaryOperator], - ["<", TOKEN_TYPES.ComparisonBinaryOperator], - [">", TOKEN_TYPES.ComparisonBinaryOperator], - // Arithmetic operators - ["+", TOKEN_TYPES.AdditiveBinaryOperator], - ["-", TOKEN_TYPES.AdditiveBinaryOperator], - ["~", TOKEN_TYPES.AdditiveBinaryOperator], - ["*", TOKEN_TYPES.MultiplicativeBinaryOperator], - ["/", TOKEN_TYPES.MultiplicativeBinaryOperator], - ["%", TOKEN_TYPES.MultiplicativeBinaryOperator], - // Assignment operator - ["=", TOKEN_TYPES.Equals] -]; -var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([ - ["n", "\n"], - // New line - ["t", " "], - // Horizontal tab - ["r", "\r"], - // Carriage return - ["b", "\b"], - // Backspace - ["f", "\f"], - // Form feed - ["v", "\v"], - // Vertical tab - ["'", "'"], - // Single quote - ['"', '"'], - // Double quote - ["\\", "\\"] - // Backslash -]); -function preprocess(template, options = {}) { - if (template.endsWith("\n")) { - template = template.slice(0, -1); - } - if (options.lstrip_blocks) { - template = template.replace(/^[ \t]*({[#%-])/gm, "$1"); +function calculateDimensions(arr) { + const dimensions = []; + let current = arr; + while (Array.isArray(current)) { + dimensions.push(current.length); + current = current[0]; } - if (options.trim_blocks) { - template = template.replace(/([#%-]})\n/g, "$1"); + return dimensions; +} +function mergeArrays(...arrs) { + return Array.prototype.concat.apply([], arrs); +} +function product(...a) { + return a.reduce((a2, b) => a2.flatMap((d) => b.map((e) => [d, e]))); +} +function calculateReflectOffset(i, w) { + return Math.abs((i + w) % (2 * w) - w); +} +function pick(o, props) { + return Object.assign( + {}, + ...props.map((prop) => { + if (o[prop] !== void 0) { + return { [prop]: o[prop] }; + } + }) + ); +} +function count(arr, value) { + let count2 = 0; + for (const v of arr) { + if (v === value) ++count2; } - return template.replace(/-%}\s*/g, "%}").replace(/\s*{%-/g, "{%").replace(/-}}\s*/g, "}}").replace(/\s*{{-/g, "{{").replace(/-#}\s*/g, "#}").replace(/\s*{#-/g, "{#").replace(/{%\s*(end)?generation\s*%}/gs, ""); + return count2; } -function tokenize(source, options = {}) { - const tokens = []; - const src = preprocess(source, options); - let cursorPosition = 0; - let curlyBracketDepth = 0; - const consumeWhile = (predicate) => { - let str = ""; - while (predicate(src[cursorPosition])) { - if (src[cursorPosition] === "\\") { - ++cursorPosition; - if (cursorPosition >= src.length) - throw new SyntaxError("Unexpected end of input"); - const escaped = src[cursorPosition++]; - const unescaped = ESCAPE_CHARACTERS.get(escaped); - if (unescaped === void 0) { - throw new SyntaxError(`Unexpected escaped character: ${escaped}`); + +// src/utils/logger.js +var logger = { + /** + * Log an error message. Only suppressed when logLevel is NONE. + * @param {...any} args - Arguments to log + */ + error(...args) { + if (env.logLevel <= LogLevel.ERROR) { + console.error(...args); + } + }, + /** + * Log a warning message. Shown when logLevel <= WARNING. + * @param {...any} args - Arguments to log + */ + warn(...args) { + if (env.logLevel <= LogLevel.WARNING) { + console.warn(...args); + } + }, + /** + * Log an info message. Shown when logLevel <= INFO. + * @param {...any} args - Arguments to log + */ + info(...args) { + if (env.logLevel <= LogLevel.INFO) { + console.log(...args); + } + }, + /** + * Log a debug message. Only shown when logLevel is DEBUG. + * @param {...any} args - Arguments to log + */ + debug(...args) { + if (env.logLevel <= LogLevel.DEBUG) { + console.log(...args); + } + }, + /** + * Log a message (alias for info). Shown when logLevel <= INFO. + * @param {...any} args - Arguments to log + */ + log(...args) { + this.info(...args); + } +}; + +// ../../node_modules/.pnpm/@huggingface+tokenizers@0.2.0/node_modules/@huggingface/tokenizers/dist/tokenizers.mjs +var DictionarySplitter = class { + /** + * @param dictionary The dictionary of words to use for splitting. + */ + constructor(dictionary) { + this.trie = this._build_trie(dictionary); + } + /** + * Builds a trie from the given dictionary. + * @param dictionary The dictionary of words to build the trie from. + * @returns The root node of the trie. + * @private + */ + _build_trie(dictionary) { + const trie = /* @__PURE__ */ Object.create(null); + for (const word of dictionary) { + let node = trie; + for (let i = 0; i < word.length; ++i) { + const char = word[i]; + node = node[char] ??= /* @__PURE__ */ Object.create(null); + } + node.end = word; + } + return trie; + } + /** + * Splits the input text into tokens based on the dictionary. + * @param text The input text to split. + * @returns An array of tokens. + */ + split(text) { + const result = []; + const n = text.length; + let start = 0; + let i = 0; + while (i < n) { + let node = this.trie; + let match = null; + let j2 = i; + while (j2 < n && (node = node[text[j2]])) { + if (node.end) { + match = node.end; + } + ++j2; + } + if (match) { + if (i > start) { + result.push(text.slice(start, i)); } - str += unescaped; - continue; + result.push(match); + i += match.length; + start = i; + } else { + ++i; } - str += src[cursorPosition++]; - if (cursorPosition >= src.length) - throw new SyntaxError("Unexpected end of input"); } - return str; - }; - main: - while (cursorPosition < src.length) { - const lastTokenType = tokens.at(-1)?.type; - if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) { - let text = ""; - while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression - !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{" || src[cursorPosition + 1] === "#"))) { - text += src[cursorPosition++]; - } - if (text.length > 0) { - tokens.push(new Token(text, TOKEN_TYPES.Text)); - continue; - } - } - if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") { - cursorPosition += 2; - let comment = ""; - while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") { - if (cursorPosition + 2 >= src.length) { - throw new SyntaxError("Missing end of comment tag"); + if (start < n) { + result.push(text.slice(start)); + } + return result; + } +}; +var DictionarySplitter_default = DictionarySplitter; +var AddedToken = class { + /** + * Creates a new instance of AddedToken. + * @param config Added token configuration object. + */ + constructor(config) { + this.content = config.content; + this.id = config.id; + this.single_word = config.single_word ?? false; + this.lstrip = config.lstrip ?? false; + this.rstrip = config.rstrip ?? false; + this.special = config.special ?? false; + this.normalized = config.normalized ?? !this.special; + } +}; +var AddedToken_default = AddedToken; +var compile_unicode_regexp = (source, flags) => { + try { + return new RegExp(source, flags); + } catch (error) { + if (!(error instanceof SyntaxError)) throw error; + const property_names = /* @__PURE__ */ new Map(); + const rewritten = source.replace( + /(\\[pP])\{([^}=]+)\}/g, + (text, p, n, offset) => { + let preceding_backslashes = 0; + for (let i = offset - 1; i >= 0 && source[i] === "\\"; --i) { + ++preceding_backslashes; + } + if (preceding_backslashes % 2 === 1) return text; + let property_name = property_names.get(n); + if (property_name === void 0) { + try { + new RegExp(`\\p{${n}}`, "u"); + property_name = n; + } catch { + property_name = `Script=${n}`; } - comment += src[cursorPosition++]; + property_names.set(n, property_name); } - tokens.push(new Token(comment, TOKEN_TYPES.Comment)); - cursorPosition += 2; + return `${p}{${property_name}}`; + } + ); + if (rewritten === source) throw error; + try { + return new RegExp(rewritten, flags); + } catch { + throw error; + } + } +}; +var clean_up_tokenization = (text) => text.replace(/ \./g, ".").replace(/ \?/g, "?").replace(/ \!/g, "!").replace(/ ,/g, ",").replace(/ \' /g, "'").replace(/ n't/g, "n't").replace(/ 'm/g, "'m").replace(/ 's/g, "'s").replace(/ 've/g, "'ve").replace(/ 're/g, "'re"); +var create_pattern = (pattern, invert = true) => { + if (pattern.Regex !== void 0) { + const regex = rewrite_oniguruma_to_js( + normalize_bloom_split_char_class(pattern.Regex) + ); + return compile_unicode_regexp(regex, "gu"); + } else if (pattern.String !== void 0) { + const escaped = escape_reg_exp(pattern.String); + return new RegExp(invert ? escaped : `(${escaped})`, "gu"); + } else { + console.warn("Unknown pattern type:", pattern); + return null; + } +}; +var UNICODE_WORD_CHARS_IN_CLASS = "\\p{Alphabetic}\\p{M}\\p{Nd}\\p{Pc}"; +var UNICODE_WORD_CHARS = `${UNICODE_WORD_CHARS_IN_CLASS}\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE`; +var UNICODE_WORD_CLASS = `[${UNICODE_WORD_CHARS}]`; +var UNICODE_NON_WORD_CLASS = `[^${UNICODE_WORD_CHARS}]`; +var UNICODE_WORD_BOUNDARY = `(?:(?|[:=!>])/; +var BRACED_ESCAPE_RE = /^\\([pPxu])\{([^}]*)\}/; +var QUANTIFIER_BRACE_RE = /^\{(\d+(?:,\d*)?|,\d+)\}/; +var POSIX_BRACKET_RE = /^\[:(\^?)(\p{Alphabetic}+):\]/u; +var EMPTY_NEGATED_POSIX_BRACKET_RE = /^\[:\^:\]/; +var UNSUPPORTED_POSIX_BRACKET_RE = /^\[(?:\.[^\]]*\.\]|=[^\]]*=\])/; +var FIXED_WIDTH_ESCAPE_RE = /^(?:\\x[0-9A-Fa-f]{2}|\\u[0-9A-Fa-f]{4}|\\c[A-Za-z])/; +var is_ascii_letter = (char) => char >= "A" && char <= "Z" || char >= "a" && char <= "z"; +var character_at = (text, index) => String.fromCodePoint(text.codePointAt(index)); +var get_ascii_folded_hex_atom = (hex) => { + if (!/^[0-9A-Fa-f]{1,8}$/.test(hex)) return null; + const code_point = Number.parseInt(hex, 16); + if (code_point > 127) return null; + const letter = String.fromCharCode(code_point); + return is_ascii_letter(letter) ? `[${letter.toLowerCase()}${letter.toUpperCase()}]` : null; +}; +var normalize_bloom_split_char_class = (regex) => regex.replace(/\[\^\(\\s\|\[([^\]]+)\]\)\]/g, "[^()|\\s$1]"); +var ANY_CODE_POINT = "[\\s\\S]"; +var MAX_CHARACTER_CLASS_NESTING_DEPTH = 256; +var create_character_class_operand = () => ({ + fragment: "", + alternatives: [], + tail: null, + contains_complex_set: false +}); +var throw_character_class_range_error = (index) => { + throw new SyntaxError( + `Unsupported range with a set-valued character-class operand at index ${index}` + ); +}; +var add_character_class_atom = (operand, atom, index, contains_complex_set = true) => { + if (operand.tail === "range") throw_character_class_range_error(index); + operand.alternatives.push(atom); + operand.tail = "set"; + operand.contains_complex_set = operand.contains_complex_set || contains_complex_set; +}; +var append_character_class_fragment = (operand, fragment, set_valued = false, index = -1) => { + if (set_valued && operand.tail === "range") { + throw_character_class_range_error(index); + } + if (operand.tail === "range") { + operand.fragment += fragment; + operand.tail = "complete_range"; + return; + } + operand.fragment += fragment; + operand.tail = set_valued ? "set" : "scalar"; + operand.contains_complex_set = operand.contains_complex_set || set_valued; +}; +var rewrite_character_class_escape = (regex, index, operand) => { + const braced = BRACED_ESCAPE_RE.exec(regex.slice(index)); + if (braced) { + const [text, kind, body] = braced; + if (kind === "P" && body === "Word") { + add_character_class_atom( + operand, + `[^${UNICODE_WORD_CHARS_IN_CLASS}]`, + index + ); + } else { + const replacement2 = kind === "x" ? `\\u{${body}}` : kind === "p" && body === "Word" ? UNICODE_WORD_CHARS_IN_CLASS : text; + append_character_class_fragment( + operand, + replacement2, + kind === "p" || kind === "P", + index + ); + } + return index + text.length; + } + const fixed_width = FIXED_WIDTH_ESCAPE_RE.exec(regex.slice(index)); + if (fixed_width) { + append_character_class_fragment(operand, fixed_width[0]); + return index + fixed_width[0].length; + } + if (index + 1 >= regex.length) { + throw new SyntaxError( + `Unterminated escape in character class at index ${index}` + ); + } + const next = character_at(regex, index + 1); + const next_end = index + 1 + next.length; + const raw_whitespace = RAW_WHITESPACE_ESCAPES.get(next); + if (raw_whitespace !== void 0) { + append_character_class_fragment(operand, raw_whitespace); + return next_end; + } + const complement = CLASS_COMPLEMENT_ALTERNATIVES.get(next); + if (complement !== void 0) { + add_character_class_atom(operand, complement, index); + return next_end; + } + const rewrite = CLASS_ESCAPE_REWRITES.get(next); + let replacement; + let set_valued = false; + if (rewrite !== void 0) { + replacement = rewrite; + set_valued = next !== "a" && next !== "e"; + } else if (/[A-Za-z0-9]/.test(next)) { + replacement = `\\${next}`; + } else if (JS_SYNTAX_CHARS.includes(next) || next === "-") { + replacement = `\\${next}`; + } else { + replacement = next; + } + append_character_class_fragment(operand, replacement, set_valued, index); + return next_end; +}; +var compile_character_set_union = (pieces) => { + if (pieces.length === 1) return pieces[0]; + return `(?:(?=(?:${pieces.join("|")}))${ANY_CODE_POINT})`; +}; +var compile_character_class_operand = (operand) => { + const pieces = operand.fragment.length === 0 ? operand.alternatives : [`[${operand.fragment}]`, ...operand.alternatives]; + return compile_character_set_union(pieces); +}; +var get_ascii_fold_additions = (positive_atom) => { + const membership = compile_unicode_regexp(`^(?:${positive_atom})$`, "u"); + let additions = ""; + for (let offset = 0; offset < 26; ++offset) { + const upper = String.fromCharCode(65 + offset); + const lower = String.fromCharCode(97 + offset); + const has_upper = membership.test(upper); + const has_lower = membership.test(lower); + if (has_upper !== has_lower) additions += has_upper ? lower : upper; + } + return additions; +}; +var parse_character_class = (regex, start, ascii_fold, apply_ascii_fold = true, nesting_depth = 1) => { + if (nesting_depth > MAX_CHARACTER_CLASS_NESTING_DEPTH) { + throw new SyntaxError( + `Maximum character-class nesting depth of ${MAX_CHARACTER_CLASS_NESTING_DEPTH} exceeded at index ${start}` + ); + } + let i = start + 1; + const negated = regex[i] === "^"; + if (negated) ++i; + const first_content_index = i; + const operands = [create_character_class_operand()]; + let operand = operands[0]; + let contains_nested_negated_complex_set = false; + while (i < regex.length) { + const char = character_at(regex, i); + if (char === "\\") { + i = rewrite_character_class_escape(regex, i, operand); + continue; + } + if (char === "]") { + if (i === first_content_index) { + append_character_class_fragment(operand, "\\]"); + ++i; continue; } - consumeWhile((char2) => /\s/.test(char2)); - const char = src[cursorPosition]; - if (char === "-" || char === "+") { - const lastTokenType2 = tokens.at(-1)?.type; - if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) { - throw new SyntaxError(`Unexpected character: ${char}`); - } - switch (lastTokenType2) { - case TOKEN_TYPES.Identifier: - case TOKEN_TYPES.NumericLiteral: - case TOKEN_TYPES.StringLiteral: - case TOKEN_TYPES.CloseParen: - case TOKEN_TYPES.CloseSquareBracket: - break; - default: { - ++cursorPosition; - const num = consumeWhile(isInteger); - tokens.push( - new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator) - ); - continue; - } + if (operand.tail === null) { + if (operands.length > 1) { + throw new SyntaxError( + `Malformed character-class intersection with an empty operand at index ${i}` + ); } + throw new SyntaxError(`Empty character class at index ${start}`); } - for (const [seq, type] of ORDERED_MAPPING_TABLE) { - if (seq === "}}" && curlyBracketDepth > 0) { - continue; - } - const slice2 = src.slice(cursorPosition, cursorPosition + seq.length); - if (slice2 === seq) { - tokens.push(new Token(seq, type)); - if (type === TOKEN_TYPES.OpenExpression) { - curlyBracketDepth = 0; - } else if (type === TOKEN_TYPES.OpenCurlyBracket) { - ++curlyBracketDepth; - } else if (type === TOKEN_TYPES.CloseCurlyBracket) { - --curlyBracketDepth; + const contains_complex_set = operands.some( + (candidate) => candidate.contains_complex_set + ); + if (negated && operands.length > 1 && contains_nested_negated_complex_set) { + throw new SyntaxError( + `Unsupported outer-negated character-class intersection with a nested negated class containing a Unicode property, POSIX class, or shorthand at index ${start}` + ); + } + const first_atom = compile_character_class_operand(operands[0]); + let positive_atom = first_atom; + if (operands.length > 1) { + let lookaheads = ""; + for (let j2 = 1; j2 < operands.length; ++j2) { + lookaheads += `(?=${compile_character_class_operand(operands[j2])})`; + } + positive_atom = `(?:${lookaheads}${first_atom})`; + } + const is_direct_class = operands.length === 1 && operand.alternatives.length === 0; + let direct_fragment = operand.fragment; + if (ascii_fold && apply_ascii_fold) { + const additions = get_ascii_fold_additions(positive_atom); + if (additions.length > 0) { + if (is_direct_class) { + direct_fragment += additions; + positive_atom = `[${direct_fragment}]`; + } else { + positive_atom = compile_character_set_union([ + positive_atom, + `[${additions}]` + ]); } - cursorPosition += seq.length; - continue main; } } - if (char === "'" || char === '"') { - ++cursorPosition; - const str = consumeWhile((c) => c !== char); - tokens.push(new Token(str, TOKEN_TYPES.StringLiteral)); - ++cursorPosition; - continue; + const atom = negated ? is_direct_class ? `[^${direct_fragment}]` : `(?:(?!${positive_atom})${ANY_CODE_POINT})` : positive_atom; + return { + atom, + end: i + 1, + negated, + contains_complex_set, + contains_nested_negated_complex_set + }; + } + if (regex.startsWith("&&", i)) { + if (operand.tail === null) { + throw new SyntaxError( + `Malformed character-class intersection with an empty operand at index ${i}` + ); } - if (isInteger(char)) { - let num = consumeWhile(isInteger); - if (src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) { - ++cursorPosition; - const frac = consumeWhile(isInteger); - num = `${num}.${frac}`; + operand = create_character_class_operand(); + operands.push(operand); + i += 2; + continue; + } + if (char === "[") { + const suffix = regex.slice(i); + if (EMPTY_NEGATED_POSIX_BRACKET_RE.test(suffix)) { + throw new SyntaxError( + `Malformed empty negated POSIX character class at index ${i}` + ); + } + const posix = POSIX_BRACKET_RE.exec(suffix); + if (posix) { + const [, posix_negated, name] = posix; + const fragment = POSIX_CLASS_FRAGMENTS.get(name); + if (fragment === void 0) { + throw new SyntaxError( + `Unsupported POSIX character class "${name}" at index ${i}` + ); + } + if (ascii_fold && posix_negated && (name === "lower" || name === "upper")) { + throw new SyntaxError( + `Unsupported negated POSIX ${name} class inside an inline case-insensitive group` + ); + } + if (posix_negated) { + add_character_class_atom(operand, `[^${fragment}]`, i); + } else { + append_character_class_fragment(operand, fragment, true, i); } - tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral)); + i += posix[0].length; continue; } - if (isWord(char)) { - const word = consumeWhile(isWord); - tokens.push(new Token(word, TOKEN_TYPES.Identifier)); - continue; + if (UNSUPPORTED_POSIX_BRACKET_RE.test(suffix)) { + throw new SyntaxError( + `Unsupported POSIX collating or equivalence bracket expression at index ${i}` + ); } - throw new SyntaxError(`Unexpected character: ${char}`); + const nested = parse_character_class( + regex, + i, + ascii_fold, + false, + nesting_depth + 1 + ); + add_character_class_atom( + operand, + nested.atom, + i, + nested.contains_complex_set + ); + contains_nested_negated_complex_set ||= nested.contains_nested_negated_complex_set || nested.negated && nested.contains_complex_set; + i = nested.end; + continue; + } + if (char === "-") { + const is_terminal_literal = regex[i + 1] === "]" || regex.startsWith("&&", i + 1); + if (operand.tail === "set" && !is_terminal_literal) { + throw_character_class_range_error(i); + } + if (operand.tail === null || operand.tail === "range" || operand.tail === "complete_range" || is_terminal_literal) { + append_character_class_fragment(operand, "\\-"); + } else { + operand.fragment += "-"; + operand.tail = "range"; + } + ++i; + continue; } - return tokens; -} - -// src/ast.ts -var Statement = class { - type = "Statement"; -}; -var Program = class extends Statement { - constructor(body) { - super(); - this.body = body; + append_character_class_fragment( + operand, + char === "^" && operand.fragment.length === 0 ? "\\^" : char + ); + i += char.length; } - type = "Program"; + throw new SyntaxError( + `${operands.length > 1 ? "Unterminated character-class intersection" : "Unterminated character class"} at index ${start}` + ); }; -var If = class extends Statement { - constructor(test, body, alternate) { - super(); - this.test = test; - this.body = body; - this.alternate = alternate; +var rewrite_oniguruma_to_js = (regex) => { + let out = ""; + let atom_start = -1; + let last_was_quantifier = false; + let ascii_fold = false; + const group_states = []; + const emit_atom = (text) => { + atom_start = out.length; + out += text; + last_was_quantifier = false; + }; + for (let i = 0; i < regex.length; ) { + const char = character_at(regex, i); + if (char === "\\") { + const braced = BRACED_ESCAPE_RE.exec(regex.slice(i)); + if (braced) { + const [text, kind, body] = braced; + let replacement2 = text; + if (kind === "x") { + const code_point_escape = `\\u{${body}}`; + replacement2 = ascii_fold ? get_ascii_folded_hex_atom(body) ?? code_point_escape : code_point_escape; + } else if (body === "Word") { + replacement2 = kind === "p" ? UNICODE_WORD_CLASS : UNICODE_NON_WORD_CLASS; + } + emit_atom(replacement2); + i += text.length; + continue; + } + const fixed_width = FIXED_WIDTH_ESCAPE_RE.exec(regex.slice(i)); + if (fixed_width) { + const text = fixed_width[0]; + const replacement2 = ascii_fold && text[1] !== "c" ? get_ascii_folded_hex_atom(text.slice(2)) ?? text : text; + emit_atom(replacement2); + i += text.length; + continue; + } + if (i + 1 >= regex.length) { + out += char; + break; + } + const next = character_at(regex, i + 1); + i += 1 + next.length; + if (next === "G") { + continue; + } + const raw_whitespace = RAW_WHITESPACE_ESCAPES.get(next); + if (raw_whitespace !== void 0) { + emit_atom(raw_whitespace); + continue; + } + const rewrite = ESCAPE_REWRITES.get(next); + let replacement; + if (rewrite !== void 0) { + replacement = rewrite; + } else if (/[A-Za-z0-9]/.test(next)) { + replacement = `\\${next}`; + } else if (JS_SYNTAX_CHARS.includes(next)) { + replacement = `\\${next}`; + } else { + replacement = next; + } + emit_atom(replacement); + continue; + } + switch (char) { + case "[": { + const parsed = parse_character_class(regex, i, ascii_fold); + emit_atom(parsed.atom); + i = parsed.end; + continue; + } + case "]": + emit_atom("\\]"); + ++i; + continue; + case ".": + emit_atom("[^\\n]"); + ++i; + continue; + case "^": + emit_atom(LINE_START_ANCHOR); + ++i; + continue; + case "$": + emit_atom(LINE_END_ANCHOR); + ++i; + continue; + case "(": { + const inline_case_insensitive = regex.startsWith("(?i:", i); + const source_prefix = inline_case_insensitive ? "(?i:" : GROUP_PREFIX_RE.exec(regex.slice(i))?.[0] ?? "("; + const output_prefix = inline_case_insensitive ? "(?:" : source_prefix === "(?>" ? "(?:" : source_prefix; + group_states.push([out.length, ascii_fold]); + if (inline_case_insensitive) ascii_fold = true; + out += output_prefix; + last_was_quantifier = false; + i += source_prefix.length; + continue; + } + case ")": + out += char; + [atom_start, ascii_fold] = group_states.pop() ?? [-1, false]; + last_was_quantifier = false; + ++i; + continue; + case "|": + out += char; + atom_start = -1; + last_was_quantifier = false; + ++i; + continue; + case "{": { + const quant = QUANTIFIER_BRACE_RE.exec(regex.slice(i)); + if (!quant || atom_start < 0) { + emit_atom("\\{"); + ++i; + continue; + } + const body = quant[1].startsWith(",") ? `0${quant[1]}` : quant[1]; + i += quant[0].length; + const following = regex[i]; + if (following === "+" || following === "*") { + out = `${out.slice(0, atom_start)}(?:${out.slice(atom_start)}{${body}})${following}`; + ++i; + } else { + out += `{${body}}`; + } + last_was_quantifier = true; + continue; + } + case "}": + emit_atom("\\}"); + ++i; + continue; + case "+": + if (last_was_quantifier) { + ++i; + continue; + } + out += char; + last_was_quantifier = true; + ++i; + continue; + case "*": + case "?": + out += char; + last_was_quantifier = true; + ++i; + continue; + default: + emit_atom( + ascii_fold && is_ascii_letter(char) ? `[${char.toLowerCase()}${char.toUpperCase()}]` : char + ); + i += char.length; + continue; + } } - type = "If"; + return out; }; -var For = class extends Statement { - constructor(loopvar, iterable, body, defaultBlock) { - super(); - this.loopvar = loopvar; - this.iterable = iterable; - this.body = body; - this.defaultBlock = defaultBlock; +var escape_reg_exp = (string) => string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +var fuse_unk = (arr, tokens_to_ids, unk_token_id) => { + const fused = []; + let i = 0; + while (i < arr.length) { + fused.push(arr[i]); + const token_id = tokens_to_ids.get(arr[i]) ?? unk_token_id; + if (token_id !== unk_token_id) { + ++i; + continue; + } + while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) { + if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) { + fused[fused.length - 1] += arr[i]; + } + } } - type = "For"; -}; -var Break = class extends Statement { - type = "Break"; + return fused; }; -var Continue = class extends Statement { - type = "Continue"; +var is_chinese_char = (cp) => cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103; +var is_integral_number = (x) => Number.isInteger(x) || typeof x === "bigint"; +var len = (s) => { + let length = 0; + for (const c of s) ++length; + return length; }; -var SetStatement = class extends Statement { - constructor(assignee, value, body) { - super(); - this.assignee = assignee; - this.value = value; - this.body = body; +var lowercase_and_remove_accents = (text) => remove_accents(text.toLowerCase()); +var merge_arrays = (...arrs) => Array.prototype.concat.apply([], arrs); +var object_to_map = (obj) => new Map(Object.entries(obj)); +var regex_split = (text, regex) => { + const result = []; + let prev = 0; + for (const match of text.matchAll(regex)) { + const full_match = match[0]; + if (prev < match.index) { + result.push(text.slice(prev, match.index)); + } + if (full_match.length > 0) { + result.push(full_match); + } + prev = match.index + full_match.length; } - type = "Set"; -}; -var Macro = class extends Statement { - constructor(name, args, body) { - super(); - this.name = name; - this.args = args; - this.body = body; + if (prev < text.length) { + result.push(text.slice(prev)); } - type = "Macro"; + return result; }; -var Comment = class extends Statement { - constructor(value) { - super(); - this.value = value; +var remove_accents = (text) => text.replace(/\p{M}/gu, ""); +var validate_object = (obj, name, required_keys = []) => { + if (!obj || Array.isArray(obj) || typeof obj !== "object") { + return `${name} must be a valid object`; } - type = "Comment"; -}; -var Expression = class extends Statement { - type = "Expression"; -}; -var MemberExpression = class extends Expression { - constructor(object, property, computed) { - super(); - this.object = object; - this.property = property; - this.computed = computed; + for (const key of required_keys) { + if (!(key in obj)) { + return `${name} must contain a "${key}" property`; + } } - type = "MemberExpression"; + return null; }; -var CallExpression = class extends Expression { - constructor(callee, args) { - super(); - this.callee = callee; - this.args = args; +var whitespace_split = (text) => text.match(/\S+/g) || []; +var Callable2 = class { + /** + * Creates a new instance of the Callable class. + */ + constructor() { + const closure = function(...args) { + return closure._call(...args); + }; + return Object.setPrototypeOf(closure, new.target.prototype); } - type = "CallExpression"; }; -var Identifier = class extends Expression { +var Callable_default = Callable2; +var Normalizer = class extends Callable_default { /** - * @param {string} value The name of the identifier + * @param config The configuration object for the normalizer. */ - constructor(value) { + constructor(config) { super(); - this.value = value; + this.config = config; + } + /** + * Alias for {@link Normalizer#normalize}. + * @param text The text to normalize. + * @returns The normalized text. + */ + _call(text) { + return this.normalize(text); } - type = "Identifier"; }; -var Literal = class extends Expression { - constructor(value) { - super(); - this.value = value; +var Normalizer_default = Normalizer; +var BertNormalizer = class extends Normalizer_default { + /** + * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text. + * + * @param text The input text to tokenize. + * @returns The tokenized text with whitespace added around CJK characters. + */ + tokenize_chinese_chars(text) { + const output = []; + for (let i = 0; i < text.length; ++i) { + const char = text[i]; + const cp = char.charCodeAt(0); + if (is_chinese_char(cp)) { + output.push(" "); + output.push(char); + output.push(" "); + } else { + output.push(char); + } + } + return output.join(""); + } + /** + * Strips accents from the given text. + * @param text The text to strip accents from. + * @returns The text with accents removed. + */ + strip_accents(text) { + return text.normalize("NFD").replace(/\p{Mn}/gu, ""); + } + /** + * Checks whether `char` is a control character. + * @param char The character to check. + * @returns Whether `char` is a control character. + */ + is_control(char) { + switch (char) { + case " ": + case "\n": + case "\r": + return false; + default: + return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char); + } + } + /** + * Performs invalid character removal and whitespace cleanup on text. + * @param text The text to clean. + * @returns The cleaned text. + */ + clean_text(text) { + const output = []; + for (const char of text) { + const cp = char.charCodeAt(0); + if (cp === 0 || cp === 65533 || this.is_control(char)) { + continue; + } + if (/^\s$/.test(char)) { + output.push(" "); + } else { + output.push(char); + } + } + return output.join(""); + } + /** + * Normalizes the given text based on the configuration. + * @param text The text to normalize. + * @returns The normalized text. + */ + normalize(text) { + if (this.config.clean_text) { + text = this.clean_text(text); + } + if (this.config.handle_chinese_chars) { + text = this.tokenize_chinese_chars(text); + } + if (this.config.lowercase) { + text = text.toLowerCase(); + if (this.config.strip_accents !== false) { + text = this.strip_accents(text); + } + } else if (this.config.strip_accents) { + text = this.strip_accents(text); + } + return text; } - type = "Literal"; }; -var IntegerLiteral = class extends Literal { - type = "IntegerLiteral"; +var BertNormalizer_default = BertNormalizer; +var Precompiled = class extends Normalizer_default { + /** + * Create a new instance of Precompiled normalizer. + * @param config The configuration object. + */ + constructor(config) { + super(config); + this.charsmap = config.precompiled_charsmap ?? null; + } + /** + * Normalizes the given text by applying the precompiled charsmap. + * @param text The text to normalize. + * @returns The normalized text. + */ + normalize(text) { + text = text.replace( + /[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, + "" + ); + text = text.replace( + /[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm, + " " + ); + if (text.includes("\uFF5E")) { + const parts = text.split("\uFF5E"); + text = parts.map((part) => part.normalize("NFKC")).join("\uFF5E"); + } else { + text = text.normalize("NFKC"); + } + return text; + } }; -var FloatLiteral = class extends Literal { - type = "FloatLiteral"; +var Precompiled_default = Precompiled; +var Sequence = class extends Normalizer_default { + /** + * Create a new instance of NormalizerSequence. + * @param config The configuration object. + */ + constructor(config) { + super(config); + this.normalizers = (config.normalizers ?? []).map( + (x) => create_normalizer_default(x) + ); + } + /** + * Apply a sequence of Normalizers to the input text. + * @param text The text to normalize. + * @returns The normalized text. + */ + normalize(text) { + return this.normalizers.reduce((t, normalizer) => { + return normalizer ? normalizer.normalize(t) : t; + }, text); + } }; -var StringLiteral = class extends Literal { - type = "StringLiteral"; +var Sequence_default = Sequence; +var Replace = class extends Normalizer_default { + /** + * @param config The configuration object for the normalizer. + */ + constructor(config) { + super(config); + this.pattern = create_pattern(this.config.pattern ?? {}); + } + /** + * Normalize the input text by replacing the pattern with the content. + * @param text The input text to be normalized. + * @returns The normalized text after replacing the pattern with the content. + */ + normalize(text) { + return this.pattern === null ? text : text.replaceAll(this.pattern, this.config.content ?? ""); + } }; -var ArrayLiteral = class extends Literal { - type = "ArrayLiteral"; +var Replace_default = Replace; +var UnicodeNormalizer = class extends Normalizer_default { + constructor() { + super(...arguments); + this.form = "NFC"; + } + /** + * Normalize the input text by applying Unicode normalization. + * @param text The input text to be normalized. + * @returns The normalized text. + */ + normalize(text) { + text = text.normalize(this.form); + return text; + } }; -var TupleLiteral = class extends Literal { - type = "TupleLiteral"; +var UnicodeNormalizer_default = UnicodeNormalizer; +var NFC = class extends UnicodeNormalizer_default { + constructor() { + super(...arguments); + this.form = "NFC"; + } }; -var ObjectLiteral = class extends Literal { - type = "ObjectLiteral"; +var NFC_default = NFC; +var NFD = class extends UnicodeNormalizer_default { + constructor() { + super(...arguments); + this.form = "NFD"; + } }; -var BinaryExpression = class extends Expression { - constructor(operator, left, right) { - super(); - this.operator = operator; - this.left = left; - this.right = right; +var NFD_default = NFD; +var NFKC = class extends UnicodeNormalizer_default { + constructor() { + super(...arguments); + this.form = "NFKC"; } - type = "BinaryExpression"; }; -var FilterExpression = class extends Expression { - constructor(operand, filter) { - super(); - this.operand = operand; - this.filter = filter; +var NFKC_default = NFKC; +var NFKD = class extends UnicodeNormalizer_default { + constructor() { + super(...arguments); + this.form = "NFKD"; } - type = "FilterExpression"; }; -var FilterStatement = class extends Statement { - constructor(filter, body) { - super(); - this.filter = filter; - this.body = body; +var NFKD_default = NFKD; +var Strip = class extends Normalizer_default { + /** + * Strip leading and/or trailing whitespace from the input text. + * @param text The input text. + * @returns The normalized text. + */ + normalize(text) { + if (this.config.strip_left && this.config.strip_right) { + text = text.trim(); + } else { + if (this.config.strip_left) { + text = text.trimStart(); + } + if (this.config.strip_right) { + text = text.trimEnd(); + } + } + return text; } - type = "FilterStatement"; }; -var SelectExpression = class extends Expression { - constructor(lhs, test) { - super(); - this.lhs = lhs; - this.test = test; +var Strip_default = Strip; +var StripAccents = class extends Normalizer_default { + /** + * Remove all accents from the text. + * @param text The input text. + * @returns The normalized text without accents. + */ + normalize(text) { + return remove_accents(text); } - type = "SelectExpression"; }; -var TestExpression = class extends Expression { - constructor(operand, negate, test) { - super(); - this.operand = operand; - this.negate = negate; - this.test = test; +var StripAccents_default = StripAccents; +var Lowercase = class extends Normalizer_default { + /** + * Lowercases the input string. + * @param {string} text The text to normalize. + * @returns {string} The normalized text. + */ + normalize(text) { + return text.toLowerCase(); } - type = "TestExpression"; }; -var UnaryExpression = class extends Expression { - constructor(operator, argument) { - super(); - this.operator = operator; - this.argument = argument; +var Lowercase_default = Lowercase; +var Prepend = class extends Normalizer_default { + /** + * Prepends the input string. + * @param text The text to normalize. + * @returns The normalized text. + */ + normalize(text) { + text = this.config.prepend + text; + return text; } - type = "UnaryExpression"; }; -var SliceExpression = class extends Expression { - constructor(start = void 0, stop = void 0, step = void 0) { - super(); - this.start = start; - this.stop = stop; - this.step = step; +var Prepend_default = Prepend; +function create_normalizer(config) { + if (config === null) return null; + switch (config.type) { + case "BertNormalizer": + return new BertNormalizer_default(config); + case "Precompiled": + return new Precompiled_default(config); + case "Sequence": + return new Sequence_default(config); + case "Replace": + return new Replace_default(config); + case "NFC": + return new NFC_default(config); + case "NFD": + return new NFD_default(config); + case "NFKC": + return new NFKC_default(config); + case "NFKD": + return new NFKD_default(config); + case "Strip": + return new Strip_default(config); + case "StripAccents": + return new StripAccents_default(config); + case "Lowercase": + return new Lowercase_default(config); + case "Prepend": + return new Prepend_default(config); + default: + throw new Error(`Unknown Normalizer type: ${config.type}`); + } +} +var create_normalizer_default = create_normalizer; +var PreTokenizer = class extends Callable_default { + /** + * Tokenizes the given text into pre-tokens. + * @param text The text or array of texts to pre-tokenize. + * @param options Additional options for the pre-tokenization logic. + * @returns An array of pre-tokens. + */ + pre_tokenize(text, options) { + return (Array.isArray(text) ? text.map((x) => this.pre_tokenize_text(x, options)) : this.pre_tokenize_text(text, options)).flat(); + } + /** + * Alias for {@link PreTokenizer#pre_tokenize}. + * @param text The text or array of texts to pre-tokenize. + * @param options Additional options for the pre-tokenization logic. + * @returns An array of pre-tokens. + */ + _call(text, options) { + return this.pre_tokenize(text, options); } - type = "SliceExpression"; }; -var KeywordArgumentExpression = class extends Expression { - constructor(key, value) { +var PreTokenizer_default = PreTokenizer; +var BYTES_TO_UNICODE = (() => { + const bs2 = [ + ...Array.from( + { length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, + (_, i) => i + "!".charCodeAt(0) + ), + ...Array.from( + { length: "\xAC".charCodeAt(0) - "\xA1".charCodeAt(0) + 1 }, + (_, i) => i + "\xA1".charCodeAt(0) + ), + ...Array.from( + { length: "\xFF".charCodeAt(0) - "\xAE".charCodeAt(0) + 1 }, + (_, i) => i + "\xAE".charCodeAt(0) + ) + ]; + const cs2 = bs2.slice(); + let n = 0; + for (let b = 0; b < 256; ++b) { + if (!bs2.includes(b)) { + bs2.push(b); + cs2.push(256 + n); + n += 1; + } + } + const ccs = cs2.map((n2) => String.fromCharCode(n2)); + return Object.fromEntries(bs2.map((b, i) => [b, ccs[i]])); +})(); +var reverse_dictionary = (data) => Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key])); +var UNICODE_TO_BYTES = reverse_dictionary(BYTES_TO_UNICODE); +var PUNCTUATION_REGEX = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E"; +var ByteLevel = class extends PreTokenizer_default { + /** + * Creates a new instance of the `ByteLevelPreTokenizer` class. + * @param config The configuration object. + */ + constructor(config) { super(); - this.key = key; - this.value = value; + this.config = config; + this.add_prefix_space = this.config.add_prefix_space ?? false; + this.trim_offsets = this.config.trim_offsets ?? false; + this.use_regex = this.config.use_regex ?? true; + this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu; + this.byte_encoder = BYTES_TO_UNICODE; + this.text_encoder = new TextEncoder(); + } + /** + * Tokenizes a single piece of text using byte-level tokenization. + * @param text The text to tokenize. + * @param options Additional options for the pre-tokenization logic. + * @returns An array of tokens. + */ + pre_tokenize_text(text, options) { + if (this.add_prefix_space && !text.startsWith(" ")) { + text = " " + text; + } + const tokens = this.use_regex ? text.match(this.pattern) || [] : [text]; + return tokens.map( + (token) => Array.from( + this.text_encoder.encode(token), + (byte) => this.byte_encoder[byte] + ).join("") + ); } - type = "KeywordArgumentExpression"; }; -var SpreadExpression = class extends Expression { - constructor(argument) { - super(); - this.argument = argument; +var ByteLevel_default = ByteLevel; +var Whitespace = class extends PreTokenizer_default { + /** + * Pre-tokenizes the input text by splitting it on word boundaries. + * @param text The text to be pre-tokenized. + * @param options Additional options for the pre-tokenization logic. + * @returns An array of tokens produced by splitting the input text on whitespace. + */ + pre_tokenize_text(text, options) { + return text.match(/\w+|[^\w\s]+/g) || []; } - type = "SpreadExpression"; }; -var CallStatement = class extends Statement { - constructor(call, callerArgs, body) { +var Whitespace_default = Whitespace; +var Metaspace = class extends PreTokenizer_default { + /** + * @param config The configuration object for the MetaspacePreTokenizer. + */ + constructor(config) { super(); - this.call = call; - this.callerArgs = callerArgs; - this.body = body; + this.replacement = config.replacement ?? "\u2581"; + this.str_rep = config.str_rep || this.replacement; + this.prepend_scheme = config.prepend_scheme ?? "always"; + } + /** + * This method takes a string, replaces spaces with the replacement character, + * adds a prefix space if requested, and returns a new list of tokens. + * @param text The text to pre-tokenize. + * @param options The options for the pre-tokenization. + * @returns A new list of pre-tokenized tokens. + */ + pre_tokenize_text(text, options) { + const { section_index = void 0 } = options ?? {}; + let normalized = text.replaceAll(" ", this.str_rep); + if ( + // We add a prefix space if: + // (1) The normalized token does not already start with the replacement character. + !normalized.startsWith(this.replacement) && // and (2) either: + // (a) prepend_scheme is 'always' + // (b) prepend_scheme is 'first' and this is the first section + (this.prepend_scheme === "always" || this.prepend_scheme === "first" && section_index === 0) + ) { + normalized = this.str_rep + normalized; + } + return [normalized]; } - type = "CallStatement"; }; -var Ternary = class extends Expression { - constructor(condition, trueExpr, falseExpr) { +var Metaspace_default = Metaspace; +var Split = class extends PreTokenizer_default { + /** + * @param config The configuration options for the pre-tokenizer. + */ + constructor(config) { super(); - this.condition = condition; - this.trueExpr = trueExpr; - this.falseExpr = falseExpr; + this.config = config; + this.pattern = create_pattern( + this.config.pattern ?? {}, + this.config.invert ?? true + ); } - type = "Ternary"; -}; - -// src/parser.ts -function parse(tokens) { - const program = new Program([]); - let current = 0; - function expect(type, error) { - const prev = tokens[current++]; - if (!prev || prev.type !== type) { - throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`); + /** + * Tokenizes text by splitting it using the given pattern. + * @param text The text to tokenize. + * @returns An array of tokens. + */ + pre_tokenize_text(text) { + if (this.pattern === null) { + return []; + } + if (this.config.invert) { + return (text.match(this.pattern) || []).filter((x) => x); + } else if (this.config.behavior?.toLowerCase() === "removed") { + return text.split(this.pattern).filter((x) => x); + } else { + return regex_split(text, this.pattern); } - return prev; } - function expectIdentifier(name) { - if (!isIdentifier(name)) { - throw new SyntaxError(`Expected ${name}`); - } - ++current; +}; +var Split_default = Split; +var Punctuation = class extends PreTokenizer_default { + /** + * @param config The configuration options for the pre-tokenizer. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = new RegExp( + `[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, + "gu" + ); } - function parseAny() { - switch (tokens[current].type) { - case TOKEN_TYPES.Comment: - return new Comment(tokens[current++].value); - case TOKEN_TYPES.Text: - return parseText(); - case TOKEN_TYPES.OpenStatement: - return parseJinjaStatement(); - case TOKEN_TYPES.OpenExpression: - return parseJinjaExpression(); - default: - throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`); - } + /** + * Tokenizes text by splitting it using the given pattern. + * @param text The text to tokenize. + * @returns An array of tokens. + */ + pre_tokenize_text(text) { + return text.match(this.pattern) || []; } - function is(...types) { - return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type); +}; +var Punctuation_default = Punctuation; +var Digits = class extends PreTokenizer_default { + /** + * @param config The configuration options for the pre-tokenizer. + */ + constructor(config) { + super(); + this.config = config; + const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? "" : "+"}`; + this.pattern = new RegExp(digit_pattern, "gu"); } - function isStatement(...names) { - return tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.Identifier && names.includes(tokens[current + 1]?.value); + /** + * Tokenizes text by splitting it using the given pattern. + * @param text The text to tokenize. + * @returns An array of tokens. + */ + pre_tokenize_text(text) { + return text.match(this.pattern) || []; } - function isIdentifier(...names) { - return current + names.length <= tokens.length && names.every((name, i) => tokens[current + i].type === "Identifier" && name === tokens[current + i].value); +}; +var Digits_default = Digits; +var BertPreTokenizer = class extends PreTokenizer_default { + /** + * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme + * similar to that used in the original implementation of BERT. + */ + constructor() { + super(); + this.pattern = new RegExp( + `[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, + "gu" + ); } - function parseText() { - return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value); + /** + * Tokenizes a single text using the BERT pre-tokenization scheme. + * + * @param text The text to tokenize. + * @param options Additional options for the pre-tokenization logic. + * @returns An array of tokens. + */ + pre_tokenize_text(text, options) { + return text.trim().match(this.pattern) || []; } - function parseJinjaStatement() { - expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token"); - if (tokens[current].type !== TOKEN_TYPES.Identifier) { - throw new SyntaxError(`Unknown statement, got ${tokens[current].type}`); - } - const name = tokens[current].value; - let result; - switch (name) { - case "set": - ++current; - result = parseSetStatement(); - break; - case "if": - ++current; - result = parseIfStatement(); - expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); - expectIdentifier("endif"); - expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); - break; - case "macro": - ++current; - result = parseMacroStatement(); - expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); - expectIdentifier("endmacro"); - expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); - break; - case "for": - ++current; - result = parseForStatement(); - expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); - expectIdentifier("endfor"); - expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); - break; - case "call": { - ++current; - let callerArgs = null; - if (is(TOKEN_TYPES.OpenParen)) { - callerArgs = parseArgs(); - } - const callee = parsePrimaryExpression(); - if (callee.type !== "Identifier") { - throw new SyntaxError(`Expected identifier following call statement`); - } - const callArgs = parseArgs(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const body = []; - while (!isStatement("endcall")) { - body.push(parseAny()); - } - expect(TOKEN_TYPES.OpenStatement, "Expected '{%'"); - expectIdentifier("endcall"); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const callExpr = new CallExpression(callee, callArgs); - result = new CallStatement(callExpr, callerArgs, body); - break; - } - case "break": - ++current; - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - result = new Break(); - break; - case "continue": - ++current; - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - result = new Continue(); - break; - case "filter": { - ++current; - let filterNode = parsePrimaryExpression(); - if (filterNode instanceof Identifier && is(TOKEN_TYPES.OpenParen)) { - filterNode = parseCallExpression(filterNode); - } - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const filterBody = []; - while (!isStatement("endfilter")) { - filterBody.push(parseAny()); - } - expect(TOKEN_TYPES.OpenStatement, "Expected '{%'"); - expectIdentifier("endfilter"); - expect(TOKEN_TYPES.CloseStatement, "Expected '%}'"); - result = new FilterStatement(filterNode, filterBody); - break; - } - default: - throw new SyntaxError(`Unknown statement type: ${name}`); +}; +var BertPreTokenizer_default = BertPreTokenizer; +var Replace2 = class extends PreTokenizer_default { + /** + * @param config The configuration options for the pre-tokenizer. + */ + constructor(config) { + super(); + this.config = config; + this.pattern = create_pattern(this.config.pattern ?? {}); + this.content = this.config.content ?? ""; + } + /** + * Pre-tokenizes the input text by replacing certain characters. + * @param text The text to be pre-tokenized. + * @returns An array of tokens produced by replacing certain characters. + */ + pre_tokenize_text(text) { + if (this.pattern === null) { + return [text]; } - return result; + return [text.replaceAll(this.pattern, this.config.content ?? "")]; } - function parseJinjaExpression() { - expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token"); - const result = parseExpression(); - expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token"); - return result; +}; +var Replace_default2 = Replace2; +var Sequence2 = class extends PreTokenizer_default { + /** + * Creates an instance of PreTokenizerSequence. + * @param config The configuration object for the pre-tokenizer sequence. + */ + constructor(config) { + super(); + this.tokenizers = (config.pretokenizers ?? []).map( + (x) => create_pre_tokenizer_default(x) + ); } - function parseSetStatement() { - const left = parseExpressionSequence(); - let value = null; - const body = []; - if (is(TOKEN_TYPES.Equals)) { - ++current; - value = parseExpressionSequence(); - } else { - expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); - while (!isStatement("endset")) { - body.push(parseAny()); - } - expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); - expectIdentifier("endset"); - } - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - return new SetStatement(left, value, body); + /** + * Applies each pre-tokenizer in the sequence to the input text in turn. + * @param text The text to pre-tokenize. + * @param options Additional options for the pre-tokenization logic. + * @returns The pre-tokenized text. + */ + pre_tokenize_text(text, options) { + return this.tokenizers.reduce( + (pre_tokenized_text, tokenizer) => { + return tokenizer ? tokenizer.pre_tokenize(pre_tokenized_text, options) : pre_tokenized_text; + }, + [text] + ); } - function parseIfStatement() { - const test = parseExpression(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const body = []; - const alternate = []; - while (!isStatement("elif", "else", "endif")) { - body.push(parseAny()); - } - if (isStatement("elif")) { - ++current; - ++current; - const result = parseIfStatement(); - alternate.push(result); - } else if (isStatement("else")) { - ++current; - ++current; - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - while (!isStatement("endif")) { - alternate.push(parseAny()); - } +}; +var Sequence_default2 = Sequence2; +var WhitespaceSplit = class extends PreTokenizer_default { + /** + * Pre-tokenizes the input text by splitting it on whitespace characters. + * @param text The text to be pre-tokenized. + * @returns An array of tokens produced by splitting the input text on whitespace. + */ + pre_tokenize_text(text) { + return whitespace_split(text); + } +}; +var WhitespaceSplit_default = WhitespaceSplit; +var FixedLength = class extends PreTokenizer_default { + /** + * @param config The configuration options for the pre-tokenizer. + */ + constructor(config) { + super(); + this.config = config; + this._length = config.length; + } + /** + * Pre-tokenizes the input text by splitting it into fixed-length tokens. + * @param text The text to be pre-tokenized. + * @returns An array of tokens produced by splitting the input text into fixed-length tokens. + */ + pre_tokenize_text(text) { + const tokens = []; + for (let i = 0; i < text.length; i += this._length) { + tokens.push(text.slice(i, i + this._length)); } - return new If(test, body, alternate); + return tokens; } - function parseMacroStatement() { - const name = parsePrimaryExpression(); - if (name.type !== "Identifier") { - throw new SyntaxError(`Expected identifier following macro statement`); +}; +var FixedLength_default = FixedLength; +function create_pre_tokenizer(config) { + if (config === null) return null; + switch (config.type) { + case "BertPreTokenizer": + return new BertPreTokenizer_default(); + case "Sequence": + return new Sequence_default2(config); + case "Whitespace": + return new Whitespace_default(); + case "WhitespaceSplit": + return new WhitespaceSplit_default(); + case "Metaspace": + return new Metaspace_default(config); + case "ByteLevel": + return new ByteLevel_default(config); + case "Split": + return new Split_default(config); + case "Punctuation": + return new Punctuation_default(config); + case "Digits": + return new Digits_default(config); + case "Replace": + return new Replace_default2(config); + case "FixedLength": + return new FixedLength_default(config); + default: + throw new Error(`Unknown PreTokenizer type: ${config.type}`); + } +} +var create_pre_tokenizer_default = create_pre_tokenizer; +var TokenizerModel = class extends Callable_default { + /** + * Creates a new instance of TokenizerModel. + * @param config The configuration object for the TokenizerModel. + */ + constructor(config) { + super(); + this.config = config; + this.vocab = []; + this.tokens_to_ids = /* @__PURE__ */ new Map(); + this.unk_token_id = void 0; + this.unk_token = void 0; + this.end_of_word_suffix = void 0; + this.fuse_unk = this.config.fuse_unk ?? false; + } + /** + * Internal function to call the TokenizerModel instance. + * @param tokens The tokens to encode. + * @returns The encoded tokens. + */ + _call(tokens) { + let result = this.encode(tokens); + if (this.fuse_unk) { + result = fuse_unk(result, this.tokens_to_ids, this.unk_token_id); } - const args = parseArgs(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const body = []; - while (!isStatement("endmacro")) { - body.push(parseAny()); + return result; + } +}; +var TokenizerModel_default = TokenizerModel; +var WordPieceTokenizer = class extends TokenizerModel_default { + /** + * @param config The configuration object. + */ + constructor(config) { + super(config); + this.max_input_chars_per_word = 100; + this.tokens_to_ids = object_to_map(config.vocab); + this.unk_token_id = this.tokens_to_ids.get(config.unk_token); + this.unk_token = config.unk_token; + this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100; + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; } - return new Macro(name, args, body); } - function parseExpressionSequence(primary = false) { - const fn = primary ? parsePrimaryExpression : parseExpression; - const expressions = [fn()]; - const isTuple = is(TOKEN_TYPES.Comma); - while (isTuple) { - ++current; - expressions.push(fn()); - if (!is(TOKEN_TYPES.Comma)) { - break; + /** + * Encodes an array of tokens using WordPiece encoding. + * @param tokens The tokens to encode. + * @returns An array of encoded tokens. + */ + encode(tokens) { + const output_tokens = []; + for (const token of tokens) { + const chars = [...token]; + if (chars.length > this.max_input_chars_per_word) { + output_tokens.push(this.unk_token); + continue; + } + let is_unknown = false; + let start = 0; + const sub_tokens = []; + while (start < chars.length) { + let end = chars.length; + let current_substring = null; + while (start < end) { + let substr = chars.slice(start, end).join(""); + if (start > 0) { + substr = this.config.continuing_subword_prefix + substr; + } + if (this.tokens_to_ids.has(substr)) { + current_substring = substr; + break; + } + --end; + } + if (current_substring === null) { + is_unknown = true; + break; + } + sub_tokens.push(current_substring); + start = end; + } + if (is_unknown) { + output_tokens.push(this.unk_token); + } else { + output_tokens.push(...sub_tokens); } } - return isTuple ? new TupleLiteral(expressions) : expressions[0]; + return output_tokens; } - function parseForStatement() { - const loopVariable = parseExpressionSequence(true); - if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) { - throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`); - } - if (!isIdentifier("in")) { - throw new SyntaxError("Expected `in` keyword following loop variable"); - } - ++current; - const iterable = parseExpression(); - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - const body = []; - while (!isStatement("endfor", "else")) { - body.push(parseAny()); +}; +var WordPiece_default = WordPieceTokenizer; +var CharTrieNode = class _CharTrieNode { + /** + * Create a new CharTrieNode. + * @param is_leaf Whether the node is a leaf node or not. + * @param children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. + */ + constructor(is_leaf, children) { + this.is_leaf = is_leaf; + this.children = children; + } + /** + * Returns a new `CharTrieNode` instance with default values. + * @returns A new `CharTrieNode` instance with `is_leaf` set to `false` and an empty `children` map. + */ + static default() { + return new _CharTrieNode(false, /* @__PURE__ */ new Map()); + } +}; +var CharTrie = class { + constructor() { + this.root = CharTrieNode.default(); + } + /** + * Adds one or more `texts` to the trie. + * @param texts The strings to add to the trie. + */ + extend(texts) { + for (const text of texts) { + this.push(text); } - const alternative = []; - if (isStatement("else")) { - ++current; - ++current; - expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); - while (!isStatement("endfor")) { - alternative.push(parseAny()); + } + /** + * Adds text to the trie. + * @param text The string to add to the trie. + */ + push(text) { + let node = this.root; + for (const ch of text) { + let child = node.children.get(ch); + if (child === void 0) { + child = CharTrieNode.default(); + node.children.set(ch, child); } + node = child; } - return new For(loopVariable, iterable, body, alternative); + node.is_leaf = true; } - function parseExpression() { - return parseIfExpression(); - } - function parseIfExpression() { - const a = parseLogicalOrExpression(); - if (isIdentifier("if")) { - ++current; - const test = parseLogicalOrExpression(); - if (isIdentifier("else")) { - ++current; - const falseExpr = parseIfExpression(); - return new Ternary(test, a, falseExpr); - } else { - return new SelectExpression(a, test); + /** + * Searches the trie for stored strings that match `chars` starting at `start`. + * @param chars The input characters to search. + * @param start The index to start searching from. + * @yields Each stored string that is a prefix of `chars` starting at `start`. + */ + *common_prefix_search(chars, start = 0) { + let node = this.root; + if (node === void 0) return; + let prefix = ""; + for (let i = start; i < chars.length; ++i) { + const ch = chars[i]; + prefix += ch; + node = node.children.get(ch); + if (node === void 0) return; + if (node.is_leaf) { + yield prefix; } } - return a; } - function parseLogicalOrExpression() { - let left = parseLogicalAndExpression(); - while (isIdentifier("or")) { - const operator = tokens[current]; - ++current; - const right = parseLogicalAndExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; +}; +var CharTrie_default = CharTrie; +var TokenLatticeNode = class _TokenLatticeNode { + /** + * Represents a node in a token lattice for a given sentence. + * @param token_id The ID of the token associated with this node. + * @param node_id The ID of this node. + * @param pos The starting position of the token in the sentence. + * @param length The length of the token. + * @param score The score associated with the token. + */ + constructor(token_id, node_id, pos, length, score) { + this.token_id = token_id; + this.node_id = node_id; + this.pos = pos; + this.length = length; + this.score = score; + this.prev = null; + this.backtrace_score = 0; } - function parseLogicalAndExpression() { - let left = parseLogicalNegationExpression(); - while (isIdentifier("and")) { - const operator = tokens[current]; - ++current; - const right = parseLogicalNegationExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; + /** + * Returns a clone of this node. + * @returns A clone of this node. + */ + clone() { + const n = new _TokenLatticeNode( + this.token_id, + this.node_id, + this.pos, + this.length, + this.score + ); + n.prev = this.prev; + n.backtrace_score = this.backtrace_score; + return n; } - function parseLogicalNegationExpression() { - let right; - while (isIdentifier("not")) { - const operator = tokens[current]; - ++current; - const arg = parseLogicalNegationExpression(); - right = new UnaryExpression(operator, arg); - } - return right ?? parseComparisonExpression(); +}; +var TokenLattice = class { + /** + * Creates a new TokenLattice instance. + * + * @param sentence The input sentence to be tokenized. + * @param bos_token_id The beginning-of-sequence token ID. + * @param eos_token_id The end-of-sequence token ID. + */ + constructor(sentence, bos_token_id, eos_token_id) { + this.chars = Array.from(sentence); + this.len = this.chars.length; + this.bos_token_id = bos_token_id; + this.eos_token_id = eos_token_id; + this.nodes = []; + this.begin_nodes = Array.from( + { length: this.len + 1 }, + () => [] + ); + this.end_nodes = Array.from({ length: this.len + 1 }, () => []); + const bos = new TokenLatticeNode(this.bos_token_id ?? 0, 0, 0, 0, 0); + const eos = new TokenLatticeNode( + this.eos_token_id ?? 0, + 1, + this.len, + 0, + 0 + ); + this.nodes.push(bos.clone()); + this.nodes.push(eos.clone()); + this.begin_nodes[this.len].push(eos); + this.end_nodes[0].push(bos); } - function parseComparisonExpression() { - let left = parseAdditiveExpression(); - while (true) { - let operator; - if (isIdentifier("not", "in")) { - operator = new Token("not in", TOKEN_TYPES.Identifier); - current += 2; - } else if (isIdentifier("in")) { - operator = tokens[current++]; - } else if (is(TOKEN_TYPES.ComparisonBinaryOperator)) { - operator = tokens[current++]; - } else { - break; + /** + * Inserts a new token node into the token lattice. + * + * @param pos The starting position of the token. + * @param length The length of the token. + * @param score The score of the token. + * @param token_id The token ID of the token. + */ + insert(pos, length, score, token_id) { + const node_id = this.nodes.length; + const node = new TokenLatticeNode(token_id, node_id, pos, length, score); + this.begin_nodes[pos].push(node); + this.end_nodes[pos + length].push(node); + this.nodes.push(node); + } + /** + * Implements the Viterbi algorithm to compute the most likely sequence of tokens. + * + * @returns The most likely sequence of tokens. + */ + viterbi() { + const len2 = this.len; + let pos = 0; + while (pos <= len2) { + if (this.begin_nodes[pos].length == 0) { + return []; } - const right = parseAdditiveExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; + for (let rnode of this.begin_nodes[pos]) { + rnode.prev = null; + let best_score = 0; + let best_node = null; + for (let lnode of this.end_nodes[pos]) { + const score = lnode.backtrace_score + rnode.score; + if (best_node === null || score > best_score) { + best_node = lnode.clone(); + best_score = score; + } + } + if (best_node !== null) { + rnode.prev = best_node; + rnode.backtrace_score = best_score; + } else { + return []; + } + } + ++pos; + } + const results = []; + const root = this.begin_nodes[len2][0]; + const prev = root.prev; + if (prev === null) { + return []; + } + let node = prev.clone(); + while (node.prev !== null) { + results.push(node.clone()); + const n = node.clone(); + node = n.prev.clone(); + } + results.reverse(); + return results; } - function parseAdditiveExpression() { - let left = parseMultiplicativeExpression(); - while (is(TOKEN_TYPES.AdditiveBinaryOperator)) { - const operator = tokens[current]; - ++current; - const right = parseMultiplicativeExpression(); - left = new BinaryExpression(operator, left, right); - } - return left; + /** + * Get the text piece for a given node. + * @param node The node to get the piece for. + * @returns The array of nodes representing the most likely sequence of tokens. + */ + piece(node) { + return this.chars.slice(node.pos, node.pos + node.length).join(""); } - function parseCallMemberExpression() { - const member = parseMemberExpression(parsePrimaryExpression()); - if (is(TOKEN_TYPES.OpenParen)) { - return parseCallExpression(member); - } - return member; + /** + * @returns The most likely sequence of tokens. + */ + tokens() { + const nodes = this.viterbi(); + return nodes.map((x) => this.piece(x)); } - function parseCallExpression(callee) { - let expression = new CallExpression(callee, parseArgs()); - expression = parseMemberExpression(expression); - if (is(TOKEN_TYPES.OpenParen)) { - expression = parseCallExpression(expression); + /** + * @returns The most likely sequence of token ids. + */ + token_ids() { + const nodes = this.viterbi(); + return nodes.map((x) => x.token_id); + } +}; +var TokenLattice_default = TokenLattice; +function min(arr) { + if (arr.length === 0) throw new Error("Array must not be empty"); + let min_value = arr[0]; + let index_of_min = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] < min_value) { + min_value = arr[i]; + index_of_min = i; } - return expression; } - function parseArgs() { - expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list"); - const args = parseArgumentsList(); - expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list"); - return args; + return [min_value, index_of_min]; +} +var Unigram = class extends TokenizerModel_default { + /** + * Create a new Unigram tokenizer model. + * @param config The configuration object for the Unigram model. + * @param eos_token + */ + constructor(config, eos_token) { + super(config); + const vocab_size = config.vocab.length; + this.vocab = new Array(vocab_size); + this.scores = new Array(vocab_size); + for (let i = 0; i < vocab_size; ++i) { + [this.vocab[i], this.scores[i]] = config.vocab[i]; + } + this.unk_token_id = config.unk_id; + this.unk_token = this.vocab[config.unk_id]; + this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i])); + this.bos_token = " "; + this.bos_token_id = this.tokens_to_ids.get(this.bos_token); + this.eos_token = eos_token; + this.eos_token_id = this.tokens_to_ids.get(this.eos_token); + this.unk_token = this.vocab[this.unk_token_id]; + this.min_score = min(this.scores)[0]; + this.unk_score = this.min_score - 10; + this.scores[this.unk_token_id] = this.unk_score; + this.trie = new CharTrie_default(); + this.trie.extend(this.vocab); + this.fuse_unk = true; } - function parseArgumentsList() { - const args = []; - while (!is(TOKEN_TYPES.CloseParen)) { - let argument; - if (tokens[current].type === TOKEN_TYPES.MultiplicativeBinaryOperator && tokens[current].value === "*") { - ++current; - const expr = parseExpression(); - argument = new SpreadExpression(expr); - } else { - argument = parseExpression(); - if (is(TOKEN_TYPES.Equals)) { - ++current; - if (!(argument instanceof Identifier)) { - throw new SyntaxError(`Expected identifier for keyword argument`); - } - const value = parseExpression(); - argument = new KeywordArgumentExpression(argument, value); + /** + * Populates lattice nodes. + * @param lattice The token lattice to populate with nodes. + */ + populate_nodes(lattice) { + const chars = lattice.chars; + const mblen = 1; + let begin_pos = 0; + while (begin_pos < chars.length) { + let has_single_node = false; + const prefixed_tokens = this.trie.common_prefix_search(chars, begin_pos); + for (const token of prefixed_tokens) { + const token_id = this.tokens_to_ids.get(token); + const token_score = this.scores[token_id]; + const n = len(token); + lattice.insert(begin_pos, n, token_score, token_id); + if (!has_single_node && n === mblen) { + has_single_node = true; } } - args.push(argument); - if (is(TOKEN_TYPES.Comma)) { - ++current; + if (!has_single_node) { + lattice.insert(begin_pos, mblen, this.unk_score, this.unk_token_id); } + begin_pos += mblen; } - return args; } - function parseMemberExpressionArgumentsList() { - const slices = []; - let isSlice = false; - while (!is(TOKEN_TYPES.CloseSquareBracket)) { - if (is(TOKEN_TYPES.Colon)) { - slices.push(void 0); - ++current; - isSlice = true; + /** + * Encodes an array of tokens into an array of subtokens using the unigram model. + * + * @param normalized The normalized string. + * @returns An array of subtokens obtained by encoding the input tokens using the unigram model. + */ + tokenize(normalized) { + const lattice = new TokenLattice_default( + normalized, + this.bos_token_id, + this.eos_token_id + ); + this.populate_nodes(lattice); + return lattice.tokens(); + } + /** + * Encodes an array of tokens using Unigram encoding. + * @param tokens The tokens to encode. + * @returns An array of encoded tokens. + */ + encode(tokens) { + const to_return = []; + for (const token of tokens) { + const tokenized = this.tokenize(token); + to_return.push(...tokenized); + } + return to_return; + } +}; +var Unigram_default = Unigram; +var PriorityQueue = class { + /** + * Create a new PriorityQueue. + * @param comparator Comparator function to determine priority. Defaults to a MaxHeap. + * @param max_size Maximum size of the queue. Defaults to Infinity. + */ + constructor(comparator = (a, b) => a > b, max_size = Infinity) { + this._heap = []; + this._comparator = comparator; + this._max_size = max_size; + } + /** + * The size of the queue + */ + get size() { + return this._heap.length; + } + /** + * Check if the queue is empty. + * @returns `true` if the queue is empty, `false` otherwise. + */ + is_empty() { + return this.size === 0; + } + /** + * Return the element with the highest priority in the queue. + * @returns The highest priority element in the queue. + */ + peek() { + return this._heap[0]; + } + /** + * Add one or more elements to the queue. + * @param values The values to push into the queue. + * @returns The new size of the queue. + */ + push(...values) { + return this.extend(values); + } + /** + * Add multiple elements to the queue. + * @param values The values to push into the queue. + * @returns The new size of the queue. + */ + extend(values) { + for (const value of values) { + if (this.size < this._max_size) { + this._heap.push(value); + this._sift_up(); } else { - slices.push(parseExpression()); - if (is(TOKEN_TYPES.Colon)) { - ++current; - isSlice = true; + const smallest = this._smallest(); + if (this._comparator(value, this._heap[smallest])) { + this._heap[smallest] = value; + this._sift_up_from(smallest); } } } - if (slices.length === 0) { - throw new SyntaxError(`Expected at least one argument for member/slice expression`); + return this.size; + } + /** + * Remove and return the element with the highest priority in the queue. + * @returns The element with the highest priority in the queue. + */ + pop() { + const popped_value = this.peek(); + const bottom = this.size - 1; + if (bottom > 0) { + this._swap(0, bottom); + } + this._heap.pop(); + this._sift_down(); + return popped_value; + } + /** + * Replace the element with the highest priority in the queue with a new value. + * @param value The new value. + * @returns The replaced value. + */ + replace(value) { + const replaced_value = this.peek(); + this._heap[0] = value; + this._sift_down(); + return replaced_value; + } + /** + * Compute the index for the parent of the node at index `i`. + * @param i The index of the node to get the parent of. + * @returns The index of the parent node. + * @private + */ + _parent(i) { + return (i + 1 >>> 1) - 1; + } + /** + * Compute the index for the left child of the node at index `i`. + * @param i The index of the node to get the left child of. + * @returns The index of the left child. + * @private + */ + _left(i) { + return (i << 1) + 1; + } + /** + * Compute the index for the right child of the node at index `i`. + * @param i The index of the node to get the right child of. + * @returns The index of the right child. + * @private + */ + _right(i) { + return i + 1 << 1; + } + /** + * Check if the element at index `i` is greater than the element at index `j`. + * @param i The index of the first element to compare. + * @param j The index of the second element to compare. + * @returns `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. + * @private + */ + _greater(i, j2) { + return this._comparator(this._heap[i], this._heap[j2]); + } + /** + * Swap the elements at indices `i` and `j`. + * @param i The index of the first element to swap. + * @param j The index of the second element to swap. + * @private + */ + _swap(i, j2) { + const temp = this._heap[i]; + this._heap[i] = this._heap[j2]; + this._heap[j2] = temp; + } + /** + * Maintain the heap property by updating positions in the heap, + * starting at the last element and moving up the heap. + * @private + */ + _sift_up() { + this._sift_up_from(this.size - 1); + } + /** + * Helper function to sift up from a given node. + * @param node The index of the node to start sifting up from. + */ + _sift_up_from(node) { + while (node > 0 && this._greater(node, this._parent(node))) { + this._swap(node, this._parent(node)); + node = this._parent(node); } - if (isSlice) { - if (slices.length > 3) { - throw new SyntaxError(`Expected 0-3 arguments for slice expression`); - } - return new SliceExpression(...slices); + } + /** + * Maintain the heap property by updating positions in the heap, + * starting at the first element and moving down the heap. + * @private + */ + _sift_down() { + let node = 0; + while (this._left(node) < this.size && this._greater(this._left(node), node) || this._right(node) < this.size && this._greater(this._right(node), node)) { + const max_child = this._right(node) < this.size && this._greater(this._right(node), this._left(node)) ? this._right(node) : this._left(node); + this._swap(node, max_child); + node = max_child; } - return slices[0]; } - function parseMemberExpression(object) { - while (is(TOKEN_TYPES.Dot) || is(TOKEN_TYPES.OpenSquareBracket)) { - const operator = tokens[current]; - ++current; - let property; - const computed = operator.type === TOKEN_TYPES.OpenSquareBracket; - if (computed) { - property = parseMemberExpressionArgumentsList(); - expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket"); - } else { - property = parsePrimaryExpression(); - if (property.type !== "Identifier") { - throw new SyntaxError(`Expected identifier following dot operator`); + /** + * Get the index of the smallest element in the heap. Since we use an array-based heap, + * the index can be computed without needing to traverse the heap. + * @private + */ + _smallest() { + return 2 ** Math.floor(Math.log2(this.size)) - 1; + } +}; +var PriorityQueue_default = PriorityQueue; +var LRUCache = class { + /** + * Creates an LRUCache instance. + * @param capacity The maximum number of items the cache can hold. + */ + constructor(capacity) { + this.capacity = capacity; + this.cache = /* @__PURE__ */ new Map(); + } + /** + * Retrieves the value associated with the given key and marks the key as recently used. + * @param key The key to retrieve. + * @returns The value associated with the key, or undefined if the key does not exist. + */ + get(key) { + if (!this.cache.has(key)) return void 0; + const value = this.cache.get(key); + this.cache.delete(key); + this.cache.set(key, value); + return value; + } + /** + * Inserts or updates the key-value pair in the cache. + * If the key already exists, it is updated and marked as recently used. + * If the cache exceeds its capacity, the least recently used item is evicted. + * @param key The key to add or update. + * @param value The value to associate with the key. + */ + put(key, value) { + if (this.cache.has(key)) { + this.cache.delete(key); + } + this.cache.set(key, value); + if (this.cache.size > this.capacity) { + this.cache.delete(this.cache.keys().next().value); + } + } + /** + * Clears the cache. + */ + clear() { + this.cache.clear(); + } +}; +var LRUCache_default = LRUCache; +var BPE = class extends TokenizerModel_default { + /** + * Create a BPE instance. + * @param config The configuration object for BPE. + */ + constructor(config) { + super(config); + this.tokens_to_ids = object_to_map(config.vocab); + this.unk_token_id = this.tokens_to_ids.get(config.unk_token); + this.unk_token = config.unk_token; + this.vocab = new Array(this.tokens_to_ids.size); + for (const [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; + } + const use_new_merge_format = Array.isArray(config.merges[0]); + this.merges = use_new_merge_format ? config.merges : config.merges.map( + (x) => x.split(" ", 2) + ); + this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i])); + this.end_of_word_suffix = config.end_of_word_suffix; + this.continuing_subword_suffix = config.continuing_subword_suffix ?? null; + this.byte_fallback = this.config.byte_fallback ?? false; + if (this.byte_fallback) { + this.text_encoder = new TextEncoder(); + } + this.ignore_merges = this.config.ignore_merges ?? false; + this.max_length_to_cache = 256; + this.cache_capacity = 1e4; + this.cache = new LRUCache_default(this.cache_capacity); + } + /** + * Clears the cache. + */ + clear_cache() { + this.cache.clear(); + } + /** + * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority + * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js. + * @param token The token to encode. + * @returns The BPE encoded tokens. + */ + bpe(token) { + if (token.length === 0) { + return []; + } + const cached = this.cache.get(token); + if (cached !== void 0) { + return cached; + } + const word = Array.from(token); + if (this.end_of_word_suffix) { + word[word.length - 1] += this.end_of_word_suffix; + } + let result = []; + if (word.length > 1) { + const queue = new PriorityQueue_default((a, b) => a.score < b.score); + let starting_node = { + token: word[0], + bias: 0, + prev: null, + next: null + }; + let previous_node = starting_node; + for (let i = 1; i < word.length; ++i) { + const current_node = { + bias: i / word.length, + // Add fractional component to break ties + token: word[i], + prev: previous_node, + next: null + }; + previous_node.next = current_node; + this.add_node(queue, previous_node); + previous_node = current_node; + } + while (!queue.is_empty()) { + const node = queue.pop(); + if (node.deleted || !node.next || node.next.deleted) continue; + node.deleted = true; + node.next.deleted = true; + if (node.prev) { + const new_previous_node = { ...node.prev }; + node.prev.deleted = true; + node.prev = new_previous_node; + if (new_previous_node.prev) { + new_previous_node.prev.next = new_previous_node; + } else { + starting_node = new_previous_node; + } + } + const merged = { + token: node.token + node.next.token, + bias: node.bias, + prev: node.prev, + next: node.next.next + }; + if (merged.prev) { + merged.prev.next = merged; + this.add_node(queue, merged.prev); + } else { + starting_node = merged; + } + if (merged.next) { + merged.next.prev = merged; + this.add_node(queue, merged); } } - object = new MemberExpression(object, property, computed); + for (let current_node = starting_node; current_node !== null; current_node = current_node.next) { + result.push(current_node.token); + } + } else { + result = word; } - return object; + if (this.continuing_subword_suffix) { + for (let i = 0; i < result.length - 1; ++i) { + result[i] += this.continuing_subword_suffix; + } + } + if (token.length < this.max_length_to_cache) { + this.cache.put(token, result); + } + return result; } - function parseMultiplicativeExpression() { - let left = parseTestExpression(); - while (is(TOKEN_TYPES.MultiplicativeBinaryOperator)) { - const operator = tokens[current++]; - const right = parseTestExpression(); - left = new BinaryExpression(operator, left, right); + /** + * Helper function to add a node to the priority queue. + * @param queue + * @param node + */ + add_node(queue, node) { + const rank = this.bpe_ranks.get( + JSON.stringify([node.token, node.next.token]) + ); + if (rank !== void 0) { + node.score = rank + node.bias; + queue.push(node); } - return left; } - function parseTestExpression() { - let operand = parseFilterExpression(); - while (isIdentifier("is")) { - ++current; - const negate = isIdentifier("not"); - if (negate) { - ++current; + /** + * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens. + * @param tokens The input sequence of tokens to encode. + * @returns The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens. + */ + encode(tokens) { + const output_tokens = []; + for (const token of tokens) { + if (this.ignore_merges && this.tokens_to_ids.has(token)) { + output_tokens.push(token); + continue; } - const filter = parsePrimaryExpression(); - if (!(filter instanceof Identifier)) { - throw new SyntaxError(`Expected identifier for the test`); + const bpe_token_list = this.bpe(token); + for (const t of bpe_token_list) { + if (this.tokens_to_ids.has(t)) { + output_tokens.push(t); + } else if (this.byte_fallback) { + const byte_tokens = Array.from(this.text_encoder.encode(t)).map( + (x) => `<0x${x.toString(16).toUpperCase().padStart(2, "0")}>` + ); + if (byte_tokens.every((x) => this.tokens_to_ids.has(x))) { + output_tokens.push(...byte_tokens); + } else if (this.unk_token != null) { + output_tokens.push(this.unk_token); + } + } else if (this.unk_token != null) { + output_tokens.push(this.unk_token); + } } - operand = new TestExpression(operand, negate, filter); } - return operand; + return output_tokens; } - function parseFilterExpression() { - let operand = parseCallMemberExpression(); - while (is(TOKEN_TYPES.Pipe)) { - ++current; - let filter = parsePrimaryExpression(); - if (!(filter instanceof Identifier)) { - throw new SyntaxError(`Expected identifier for the filter`); - } - if (is(TOKEN_TYPES.OpenParen)) { - filter = parseCallExpression(filter); - } - operand = new FilterExpression(operand, filter); +}; +var BPE_default = BPE; +var Legacy = class extends TokenizerModel_default { + /** + * Create a Legacy tokenizer model instance. + * @param config The configuration object for Legacy tokenizer model. + * @param more_config Additional configuration object for the Legacy tokenizer model. + */ + constructor(config, more_config) { + super(config); + const vocab = config.vocab; + this.tokens_to_ids = object_to_map( + more_config.target_lang ? vocab[more_config.target_lang] : vocab + ); + this.bos_token = more_config.bos_token; + this.bos_token_id = this.tokens_to_ids.get(this.bos_token); + this.eos_token = more_config.eos_token; + this.eos_token_id = this.tokens_to_ids.get(this.eos_token); + this.pad_token = more_config.pad_token; + this.pad_token_id = this.tokens_to_ids.get(this.pad_token); + this.unk_token = more_config.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 [key, value] of this.tokens_to_ids) { + this.vocab[value] = key; } - return operand; } - function parsePrimaryExpression() { - const token = tokens[current++]; - switch (token.type) { - case TOKEN_TYPES.NumericLiteral: { - const num = token.value; - return num.includes(".") ? new FloatLiteral(Number(num)) : new IntegerLiteral(Number(num)); - } - case TOKEN_TYPES.StringLiteral: { - let value = token.value; - while (is(TOKEN_TYPES.StringLiteral)) { - value += tokens[current++].value; - } - return new StringLiteral(value); - } - case TOKEN_TYPES.Identifier: - return new Identifier(token.value); - case TOKEN_TYPES.OpenParen: { - const expression = parseExpressionSequence(); - expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis, got ${tokens[current].type} instead."); - return expression; - } - case TOKEN_TYPES.OpenSquareBracket: { - const values = []; - while (!is(TOKEN_TYPES.CloseSquareBracket)) { - values.push(parseExpression()); - if (is(TOKEN_TYPES.Comma)) { - ++current; + encode(tokens) { + return tokens; + } +}; +var Legacy_default = Legacy; +function create_tokenizer_model(model_config, config) { + switch (model_config.type) { + case "WordPiece": + return new WordPiece_default(model_config); + case "Unigram": + return new Unigram_default(model_config, config.eos_token); + case "BPE": + return new BPE_default(model_config); + default: + if (model_config.vocab) { + if (Array.isArray(model_config.vocab)) { + return new Unigram_default(model_config, config.eos_token); + } else if (Object.hasOwn(model_config, "continuing_subword_prefix") && Object.hasOwn(model_config, "unk_token")) { + if (Object.hasOwn(model_config, "merges")) { + return new BPE_default(model_config); + } else { + return new WordPiece_default(model_config); } + } else { + return new Legacy_default(model_config, { + target_lang: config.target_lang, + bos_token: config.bos_token, + eos_token: config.eos_token, + pad_token: config.pad_token, + unk_token: config.unk_token + }); } - ++current; - return new ArrayLiteral(values); } - case TOKEN_TYPES.OpenCurlyBracket: { - const values = /* @__PURE__ */ new Map(); - while (!is(TOKEN_TYPES.CloseCurlyBracket)) { - const key = parseExpression(); - expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal"); - const value = parseExpression(); - values.set(key, value); - if (is(TOKEN_TYPES.Comma)) { - ++current; - } + throw new Error( + `Unknown TokenizerModel type: ${model_config?.type}` + ); + } +} +var create_tokenizer_model_default = create_tokenizer_model; +var PostProcessor = class extends Callable_default { + /** + * @param config The configuration for the post-processor. + */ + constructor(config) { + super(); + this.config = config; + } + /** + * Alias for {@link PostProcessor#post_process}. + * @param tokens The text or array of texts to post-process. + * @param args Additional arguments required by the post-processing logic. + * @returns The post-processed tokens. + */ + _call(tokens, ...args) { + return this.post_process(tokens, ...args); + } +}; +var PostProcessor_default = PostProcessor; +var TemplateProcessing = class extends PostProcessor_default { + /** + * Replaces special tokens in the template with actual tokens. + * @param tokens The list of tokens for the first sequence. + * @param tokens_pair The list of tokens for the second sequence (optional). + * @param add_special_tokens Whether to add the special tokens to the beginning and end of the input. + * @returns An object containing the list of tokens with the special tokens replaced with actual tokens. + */ + post_process(tokens, tokens_pair = null, add_special_tokens = true) { + const type = tokens_pair === null ? this.config.single : this.config.pair; + let processed_tokens = []; + let types = []; + for (const item of type) { + if ("SpecialToken" in item) { + if (add_special_tokens) { + processed_tokens.push(item.SpecialToken.id); + types.push(item.SpecialToken.type_id); + } + } else if ("Sequence" in item) { + if (item.Sequence.id === "A") { + processed_tokens = merge_arrays(processed_tokens, tokens); + types = merge_arrays( + types, + new Array(tokens.length).fill(item.Sequence.type_id) + ); + } else if (item.Sequence.id === "B") { + processed_tokens = merge_arrays(processed_tokens, tokens_pair); + types = merge_arrays( + types, + new Array(tokens_pair.length).fill(item.Sequence.type_id) + ); } - ++current; - return new ObjectLiteral(values); } - default: - throw new SyntaxError(`Unexpected token: ${token.type}`); } + return { tokens: processed_tokens, token_type_ids: types }; } - while (current < tokens.length) { - program.body.push(parseAny()); +}; +var TemplateProcessing_default = TemplateProcessing; +var ByteLevel2 = class extends PostProcessor_default { + /** + * Post process the given tokens. + * @param tokens The list of tokens for the first sequence. + * @param tokens_pair The list of tokens for the second sequence (optional). + * @returns An object containing the post-processed tokens. + */ + post_process(tokens, tokens_pair = null) { + return { tokens, tokens_pair }; } - return program; -} - -// src/utils.ts -function range(start, stop, step = 1) { - if (stop === void 0) { - stop = start; - start = 0; +}; +var ByteLevel_default2 = ByteLevel2; +var BertProcessing = class extends PostProcessor_default { + /** + * @param config The configuration for the post-processor. + * @param config.cls The special tokens to add to the beginning of the input. + * @param config.sep The special tokens to add to the end of the input. + */ + constructor(config) { + super(config); + this.sep = config.sep; + this.cls = config.cls; } - const result = []; - for (let i = start; i < stop; i += step) { - result.push(i); + /** + * Adds the special tokens to the beginning and end of the input. + * @param tokens The input tokens. + * @param tokens_pair An optional second set of input tokens. + * @param add_special_tokens Whether to add the special tokens to the beginning and end of the input. + * @returns The post-processed tokens with the special tokens added to the beginning and end. + */ + post_process(tokens, tokens_pair = null, add_special_tokens = true) { + if (add_special_tokens) { + tokens = merge_arrays([this.cls[0]], tokens, [this.sep[0]]); + } + let token_type_ids = new Array(tokens.length).fill(0); + if (tokens_pair) { + const middle = []; + const after = add_special_tokens ? [this.sep[0]] : []; + tokens = merge_arrays(tokens, middle, tokens_pair, after); + token_type_ids = merge_arrays( + token_type_ids, + new Array(tokens_pair.length + middle.length + after.length).fill(1) + ); + } + return { tokens, token_type_ids }; } - return result; -} -function slice(array, start, stop, step = 1) { - const direction = Math.sign(step); - if (direction >= 0) { - start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length); - stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length); - } else { - start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1); - stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1); +}; +var BertProcessing_default = BertProcessing; +var RobertaProcessing = class extends PostProcessor_default { + /** + * @param config The configuration for the post-processor. + * @param config.cls The special tokens to add to the beginning of the input. + * @param config.sep The special tokens to add to the end of the input. + */ + constructor(config) { + super(config); + this.sep = config.sep; + this.cls = config.cls; } - const result = []; - for (let i = start; direction * i < direction * stop; i += step) { - result.push(array[i]); + /** + * Adds the special tokens to the beginning and end of the input. + * @param tokens The input tokens. + * @param tokens_pair An optional second set of input tokens. + * @param add_special_tokens Whether to add the special tokens to the beginning and end of the input. + * @returns The post-processed tokens with the special tokens added to the beginning and end. + */ + post_process(tokens, tokens_pair, add_special_tokens = true) { + if (add_special_tokens) { + tokens = merge_arrays([this.cls[0]], tokens, [this.sep[0]]); + } + let token_type_ids = new Array(tokens.length).fill(0); + if (tokens_pair) { + const middle = add_special_tokens ? [this.sep[0]] : []; + const after = add_special_tokens ? [this.sep[0]] : []; + tokens = merge_arrays(tokens, middle, tokens_pair, after); + token_type_ids = merge_arrays( + token_type_ids, + new Array(tokens_pair.length + middle.length + after.length).fill(1) + ); + } + return { tokens, token_type_ids }; } - return result; -} -function titleCase(value) { - return value.replace(/\b\w/g, (c) => c.toUpperCase()); -} -function strftime_now(format2) { - return strftime(/* @__PURE__ */ new Date(), format2); -} -function strftime(date, format2) { - const monthFormatterLong = new Intl.DateTimeFormat(void 0, { month: "long" }); - const monthFormatterShort = new Intl.DateTimeFormat(void 0, { month: "short" }); - const pad2 = (n) => n < 10 ? "0" + n : n.toString(); - return format2.replace(/%[YmdbBHM%]/g, (token) => { - switch (token) { - case "%Y": - return date.getFullYear().toString(); - case "%m": - return pad2(date.getMonth() + 1); - case "%d": - return pad2(date.getDate()); - case "%b": - return monthFormatterShort.format(date); - case "%B": - return monthFormatterLong.format(date); - case "%H": - return pad2(date.getHours()); - case "%M": - return pad2(date.getMinutes()); - case "%%": - return "%"; - default: - return token; +}; +var RobertaProcessing_default = RobertaProcessing; +var Sequence3 = class extends PostProcessor_default { + /** + * Creates a new instance of Sequence post-processor. + * @param config The configuration object. + */ + constructor(config) { + super(config); + this.processors = (config.processors ?? []).map((x) => create_post_processor_default(x)); + } + /** + * Post process the given tokens. + * @param tokens The list of tokens for the first sequence. + * @param tokens_pair The list of tokens for the second sequence (optional). + * @param add_special_tokens Whether to add the special tokens to the beginning and end of the input. + * @returns An object containing the post-processed tokens. + */ + post_process(tokens, tokens_pair = null, add_special_tokens = true) { + let processed_tokens = { tokens, tokens_pair }; + for (const processor of this.processors) { + processed_tokens = processor.post_process( + processed_tokens.tokens, + processed_tokens.tokens_pair, + add_special_tokens + ); } - }); -} -function escapeRegExp(s) { - return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return processed_tokens; + } +}; +var Sequence_default3 = Sequence3; +function create_post_processor(config) { + if (config === null) return null; + switch (config.type) { + case "TemplateProcessing": + return new TemplateProcessing_default(config); + case "ByteLevel": + return new ByteLevel_default2(config); + case "BertProcessing": + return new BertProcessing_default(config); + case "RobertaProcessing": + return new RobertaProcessing_default(config); + case "Sequence": + return new Sequence_default3(config); + default: + throw new Error(`Unknown PostProcessor type: ${config.type}`); + } } -function replace(str, oldvalue, newvalue, count) { - if (count === 0) - return str; - let remaining = count == null || count < 0 ? Infinity : count; - const pattern = oldvalue.length === 0 ? new RegExp("(?=)", "gu") : new RegExp(escapeRegExp(oldvalue), "gu"); - return str.replaceAll(pattern, (match) => { - if (remaining > 0) { - --remaining; - return newvalue; +var create_post_processor_default = create_post_processor; +var Decoder = class extends Callable_default { + /** + * Creates an instance of `Decoder`. + * @param config The configuration object. + **/ + constructor(config) { + super(); + this.config = config; + this.added_tokens = []; + this.end_of_word_suffix = null; + this.trim_offsets = "trim_offsets" in config ? config.trim_offsets : false; + } + /** + * Calls the `decode` method. + * + * @param tokens The list of tokens. + * @returns The decoded string. + */ + _call(tokens) { + return this.decode(tokens); + } + /** + * Decodes a list of tokens. + * @param tokens The list of tokens. + * @returns The decoded string. + */ + decode(tokens) { + return this.decode_chain(tokens).join(""); + } +}; +var Decoder_default = Decoder; +var ByteLevel3 = class extends Decoder_default { + /** + * Create a `ByteLevelDecoder` object. + */ + constructor(config) { + super(config); + this.byte_decoder = UNICODE_TO_BYTES; + this.text_decoder = new TextDecoder("utf-8", { + fatal: false, + // eslint-disable-next-line @typescript-eslint/naming-convention + ignoreBOM: true + }); + this.end_of_word_suffix = null; + } + /** + * Convert an array of tokens to string by decoding each byte. + * @param tokens Array of tokens to be decoded. + * @returns The decoded string. + */ + convert_tokens_to_string(tokens) { + const text = tokens.join(""); + const byte_array = new Uint8Array( + [...text].map((c) => this.byte_decoder[c]) + ); + return this.text_decoder.decode(byte_array); + } + decode_chain(tokens) { + const sub_texts = []; + let current_sub_text = []; + for (const token of tokens) { + if (this.added_tokens.find((x) => x.content === token) !== void 0) { + if (current_sub_text.length > 0) { + sub_texts.push(this.convert_tokens_to_string(current_sub_text)); + current_sub_text = []; + } + sub_texts.push(token); + } else { + current_sub_text.push(token); + } } - return match; - }); -} - -// src/runtime.ts -var BreakControl = class extends Error { + if (current_sub_text.length > 0) { + sub_texts.push(this.convert_tokens_to_string(current_sub_text)); + } + return sub_texts; + } }; -var ContinueControl = class extends Error { +var ByteLevel_default3 = ByteLevel3; +var WordPiece = class extends Decoder_default { + /** + * Creates a new instance of WordPieceDecoder. + * @param config The configuration object. + */ + constructor(config) { + super(config); + this.cleanup = config.cleanup; + } + decode_chain(tokens) { + return tokens.map((token, i) => { + if (i !== 0) { + const prefix = this.config.prefix; + if (prefix && token.startsWith(prefix)) { + token = token.replace(prefix, ""); + } else { + token = " " + token; + } + } + if (this.cleanup) { + token = clean_up_tokenization(token); + } + return token; + }); + } }; -var RuntimeValue = class { - type = "RuntimeValue"; - value; +var WordPiece_default2 = WordPiece; +var Metaspace2 = class extends Decoder_default { /** - * A collection of built-in functions for this type. + * Constructs a new MetaspaceDecoder object. + * @param config The configuration object for the MetaspaceDecoder. */ - builtins = /* @__PURE__ */ new Map(); + constructor(config) { + super(config); + this.replacement = config.replacement ?? "\u2581"; + } + decode_chain(tokens) { + const result = []; + for (let i = 0; i < tokens.length; ++i) { + let normalized = tokens[i].replaceAll(this.replacement, " "); + if (i == 0 && normalized.startsWith(" ")) { + normalized = normalized.substring(1); + } + result.push(normalized); + } + return result; + } +}; +var Metaspace_default2 = Metaspace2; +var BPE2 = class extends Decoder_default { + constructor(config) { + super(config); + this.suffix = config.suffix ?? ""; + } + decode_chain(tokens) { + return tokens.map((token, i) => { + return token.replaceAll(this.suffix, i === tokens.length - 1 ? "" : " "); + }); + } +}; +var BPE_default2 = BPE2; +var CTC = class extends Decoder_default { + constructor(config) { + super(config); + this.pad_token = config.pad_token ?? ""; + this.word_delimiter_token = config.word_delimiter_token ?? ""; + this.cleanup = config.cleanup; + } /** - * Creates a new RuntimeValue. + * Converts a connectionist-temporal-classification (CTC) output tokens into a single string. + * @param tokens Array of tokens to be decoded. + * @returns The decoded string. */ - constructor(value = void 0) { - this.value = value; + convert_tokens_to_string(tokens) { + if (tokens.length === 0) return ""; + const grouped_tokens = [tokens[0]]; + for (let i = 1; i < tokens.length; ++i) { + if (tokens[i] !== grouped_tokens.at(-1)) { + grouped_tokens.push(tokens[i]); + } + } + const filtered_tokens = grouped_tokens.filter( + (token) => token !== this.pad_token + ); + let text = filtered_tokens.join(""); + if (this.cleanup) { + text = clean_up_tokenization(text).replaceAll(this.word_delimiter_token, " ").trim(); + } + return text; + } + decode_chain(tokens) { + return [this.convert_tokens_to_string(tokens)]; } +}; +var CTC_default = CTC; +var Sequence4 = class extends Decoder_default { /** - * Determines truthiness or falsiness of the runtime value. - * This function should be overridden by subclasses if it has custom truthiness criteria. - * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise. + * Creates a new instance of DecoderSequence. + * @param config The configuration object. */ - __bool__() { - return new BooleanValue(!!this.value); + constructor(config) { + super(config); + this.decoders = (config.decoders ?? []).map((x) => create_decoder_default(x)); } - toString() { - return String(this.value); + decode_chain(tokens) { + return this.decoders.reduce((toks, decoder) => { + return decoder.decode_chain(toks); + }, tokens); } }; -var IntegerValue = class extends RuntimeValue { - type = "IntegerValue"; +var Sequence_default4 = Sequence4; +var Replace3 = class extends Decoder_default { + /** + * @param config The configuration object for the decoder. + */ + constructor(config) { + super(config); + this.pattern = create_pattern(this.config.pattern); + } + decode_chain(tokens) { + const content = this.config.content ?? ""; + const pattern = this.pattern; + return pattern === null ? tokens : tokens.map((token) => token.replaceAll(pattern, content)); + } }; -var FloatValue = class extends RuntimeValue { - type = "FloatValue"; - toString() { - return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString(); +var Replace_default3 = Replace3; +var Fuse = class extends Decoder_default { + decode_chain(tokens) { + return [tokens.join("")]; } }; -var StringValue = class extends RuntimeValue { - type = "StringValue"; - builtins = /* @__PURE__ */ new Map([ - [ - "upper", - new FunctionValue(() => { - return new StringValue(this.value.toUpperCase()); - }) - ], - [ - "lower", - new FunctionValue(() => { - return new StringValue(this.value.toLowerCase()); - }) - ], - [ - "strip", - new FunctionValue(() => { - return new StringValue(this.value.trim()); - }) - ], - [ - "title", - new FunctionValue(() => { - return new StringValue(titleCase(this.value)); - }) - ], - [ - "capitalize", - new FunctionValue(() => { - return new StringValue(this.value.charAt(0).toUpperCase() + this.value.slice(1)); - }) - ], - ["length", new IntegerValue(this.value.length)], - [ - "rstrip", - new FunctionValue(() => { - return new StringValue(this.value.trimEnd()); - }) - ], - [ - "lstrip", - new FunctionValue(() => { - return new StringValue(this.value.trimStart()); - }) - ], - [ - "startswith", - new FunctionValue((args) => { - if (args.length === 0) { - throw new Error("startswith() requires at least one argument"); - } - const pattern = args[0]; - if (pattern instanceof StringValue) { - return new BooleanValue(this.value.startsWith(pattern.value)); - } else if (pattern instanceof ArrayValue) { - for (const item of pattern.value) { - if (!(item instanceof StringValue)) { - throw new Error("startswith() tuple elements must be strings"); - } - if (this.value.startsWith(item.value)) { - return new BooleanValue(true); - } - } - return new BooleanValue(false); - } - throw new Error("startswith() argument must be a string or tuple of strings"); - }) - ], - [ - "endswith", - new FunctionValue((args) => { - if (args.length === 0) { - throw new Error("endswith() requires at least one argument"); - } - const pattern = args[0]; - if (pattern instanceof StringValue) { - return new BooleanValue(this.value.endsWith(pattern.value)); - } else if (pattern instanceof ArrayValue) { - for (const item of pattern.value) { - if (!(item instanceof StringValue)) { - throw new Error("endswith() tuple elements must be strings"); - } - if (this.value.endsWith(item.value)) { - return new BooleanValue(true); - } - } - return new BooleanValue(false); - } - throw new Error("endswith() argument must be a string or tuple of strings"); - }) - ], - [ - "split", - // follows Python's `str.split(sep=None, maxsplit=-1)` function behavior - // https://docs.python.org/3.13/library/stdtypes.html#str.split - new FunctionValue((args) => { - const sep = args[0] ?? new NullValue(); - if (!(sep instanceof StringValue || sep instanceof NullValue)) { - throw new Error("sep argument must be a string or null"); - } - const maxsplit = args[1] ?? new IntegerValue(-1); - if (!(maxsplit instanceof IntegerValue)) { - throw new Error("maxsplit argument must be a number"); - } - let result = []; - if (sep instanceof NullValue) { - const text = this.value.trimStart(); - for (const { 0: match, index } of text.matchAll(/\S+/g)) { - if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) { - result.push(match + text.slice(index + match.length)); - break; - } - result.push(match); - } +var Fuse_default = Fuse; +var Strip2 = class extends Decoder_default { + constructor(config) { + super(config); + this.content = config.content ?? ""; + this.start = config.start ?? 0; + this.stop = config.stop ?? 0; + } + decode_chain(tokens) { + return tokens.map((token) => { + let start_cut = 0; + for (let i = 0; i < this.start; ++i) { + if (token[i] === this.content) { + start_cut = i + 1; + continue; } else { - if (sep.value === "") { - throw new Error("empty separator"); - } - result = this.value.split(sep.value); - if (maxsplit.value !== -1 && result.length > maxsplit.value) { - result.push(result.splice(maxsplit.value).join(sep.value)); - } + break; } - return new ArrayValue(result.map((part) => new StringValue(part))); - }) - ], - [ - "replace", - new FunctionValue((args) => { - if (args.length < 2) { - throw new Error("replace() requires at least two arguments"); - } - const oldValue = args[0]; - const newValue = args[1]; - if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) { - throw new Error("replace() arguments must be strings"); - } - let count; - if (args.length > 2) { - if (args[2].type === "KeywordArgumentsValue") { - count = args[2].value.get("count") ?? new NullValue(); - } else { - count = args[2]; - } + } + let stop_cut = token.length; + for (let i = 0; i < this.stop; ++i) { + const index = token.length - i - 1; + if (token[index] === this.content) { + stop_cut = index; + continue; } else { - count = new NullValue(); - } - if (!(count instanceof IntegerValue || count instanceof NullValue)) { - throw new Error("replace() count argument must be a number or null"); + break; } - return new StringValue(replace(this.value, oldValue.value, newValue.value, count.value)); - }) - ] - ]); -}; -var BooleanValue = class extends RuntimeValue { - type = "BooleanValue"; + } + return token.slice(start_cut, stop_cut); + }); + } }; -var ObjectValue = class extends RuntimeValue { - type = "ObjectValue"; - /** - * NOTE: necessary to override since all JavaScript arrays are considered truthy, - * while only non-empty Python arrays are consider truthy. - * - * e.g., - * - JavaScript: {} && 5 -> 5 - * - Python: {} and 5 -> {} - */ - __bool__() { - return new BooleanValue(this.value.size > 0); +var Strip_default2 = Strip2; +var ByteFallback = class extends Decoder_default { + constructor(config) { + super(config); + this.text_decoder = new TextDecoder(); } - builtins = /* @__PURE__ */ new Map([ - [ - "get", - new FunctionValue(([key, defaultValue]) => { - if (!(key instanceof StringValue)) { - throw new Error(`Object key must be a string: got ${key.type}`); + decode_chain(tokens) { + const new_tokens = []; + let previous_byte_tokens = []; + for (const token of tokens) { + let bytes = null; + if (token.length === 6 && token.startsWith("<0x") && token.endsWith(">")) { + const byte = parseInt(token.slice(3, 5), 16); + if (!isNaN(byte)) { + bytes = byte; } - return this.value.get(key.value) ?? defaultValue ?? new NullValue(); - }) - ], - ["items", new FunctionValue(() => this.items())], - ["keys", new FunctionValue(() => this.keys())], - ["values", new FunctionValue(() => this.values())] - ]); - items() { - return new ArrayValue( - Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) - ); + } + if (bytes !== null) { + previous_byte_tokens.push(bytes); + } else { + if (previous_byte_tokens.length > 0) { + const string = this.text_decoder.decode( + Uint8Array.from(previous_byte_tokens) + ); + new_tokens.push(string); + previous_byte_tokens = []; + } + new_tokens.push(token); + } + } + if (previous_byte_tokens.length > 0) { + const string = this.text_decoder.decode( + Uint8Array.from(previous_byte_tokens) + ); + new_tokens.push(string); + previous_byte_tokens = []; + } + return new_tokens; } - keys() { - return new ArrayValue(Array.from(this.value.keys()).map((key) => new StringValue(key))); +}; +var ByteFallback_default = ByteFallback; +function create_decoder(config) { + if (config === null) return null; + switch (config.type) { + case "ByteLevel": + return new ByteLevel_default3(config); + case "WordPiece": + return new WordPiece_default2(config); + case "Metaspace": + return new Metaspace_default2(config); + case "BPEDecoder": + return new BPE_default2(config); + case "CTC": + return new CTC_default(config); + case "Sequence": + return new Sequence_default4(config); + case "Replace": + return new Replace_default3(config); + case "Fuse": + return new Fuse_default(config); + case "Strip": + return new Strip_default2(config); + case "ByteFallback": + return new ByteFallback_default(config); + default: + throw new Error(`Unknown Decoder type: ${config.type}`); } - values() { - return new ArrayValue(Array.from(this.value.values())); +} +var create_decoder_default = create_decoder; +var Tokenizer = class { + constructor(tokenizer, config) { + const tokenizer_error = validate_object(tokenizer, "Tokenizer", [ + "model", + "decoder", + "post_processor", + "pre_tokenizer", + "normalizer" + ]); + if (tokenizer_error) { + throw new Error(tokenizer_error); + } + const config_error = validate_object(config, "Config"); + if (config_error) { + throw new Error(config_error); + } + this.tokenizer = tokenizer; + this.config = config; + this.normalizer = create_normalizer_default(this.tokenizer.normalizer); + this.pre_tokenizer = create_pre_tokenizer_default(this.tokenizer.pre_tokenizer); + this.model = create_tokenizer_model_default(this.tokenizer.model, this.config); + this.post_processor = create_post_processor_default(this.tokenizer.post_processor); + this.decoder = create_decoder_default(this.tokenizer.decoder); + this.special_tokens = []; + this.all_special_ids = []; + this.added_tokens = []; + const unnormalized_contents = []; + const normalized_contents = []; + this.added_tokens_map = /* @__PURE__ */ new Map(); + for (const added_token of this.tokenizer.added_tokens) { + const token = new AddedToken_default(added_token); + this.added_tokens.push(token); + this.model.tokens_to_ids.set(token.content, token.id); + this.model.vocab[token.id] = token.content; + if (token.special) { + this.special_tokens.push(token.content); + this.all_special_ids.push(token.id); + } + this.added_tokens_map.set(token.content, token); + if (token.normalized && this.normalizer !== null) { + const normalized_content = this.normalizer(token.content); + normalized_contents.push(normalized_content); + this.added_tokens_map.set(normalized_content, token); + } else { + unnormalized_contents.push(token.content); + } + } + (this.config.additional_special_tokens ?? []).forEach((token) => { + if (!this.special_tokens.includes(token)) this.special_tokens.push(token); + }); + if (this.decoder) { + this.decoder.added_tokens = this.added_tokens; + this.decoder.end_of_word_suffix = this.model.end_of_word_suffix; + } + this.splitter_unnormalized = new DictionarySplitter_default(unnormalized_contents); + this.splitter_normalized = new DictionarySplitter_default(normalized_contents); + this.remove_space = this.config.remove_space; + this.clean_up_tokenization_spaces = this.config.clean_up_tokenization_spaces ?? true; + this.do_lowercase_and_remove_accent = this.config.do_lowercase_and_remove_accent ?? false; } -}; -var KeywordArgumentsValue = class extends ObjectValue { - type = "KeywordArgumentsValue"; -}; -var ArrayValue = class extends RuntimeValue { - type = "ArrayValue"; - builtins = /* @__PURE__ */ new Map([["length", new IntegerValue(this.value.length)]]); - /** - * NOTE: necessary to override since all JavaScript arrays are considered truthy, - * while only non-empty Python arrays are consider truthy. - * - * e.g., - * - JavaScript: [] && 5 -> 5 - * - Python: [] and 5 -> [] - */ - __bool__() { - return new BooleanValue(this.value.length > 0); + // Implementation + encode(text, { + text_pair = null, + add_special_tokens = true, + return_token_type_ids = null + } = {}) { + const { tokens, token_type_ids } = this.tokenize_helper(text, { + text_pair, + add_special_tokens + }); + const input_ids = tokens.map( + (t) => this.added_tokens_map.get(t)?.id ?? this.model.tokens_to_ids.get(t) ?? this.model.unk_token_id + ); + const result = { + ids: input_ids, + tokens, + attention_mask: new Array(input_ids.length).fill(1) + }; + if (return_token_type_ids && token_type_ids) { + result.token_type_ids = token_type_ids; + } + return result; } -}; -var TupleValue = class extends ArrayValue { - type = "TupleValue"; -}; -var FunctionValue = class extends RuntimeValue { - type = "FunctionValue"; -}; -var NullValue = class extends RuntimeValue { - type = "NullValue"; -}; -var UndefinedValue = class extends RuntimeValue { - type = "UndefinedValue"; -}; -var Environment = class { - constructor(parent) { - this.parent = parent; + decode(token_ids, options = {}) { + if (!Array.isArray(token_ids) || token_ids.length === 0 || !is_integral_number(token_ids[0])) { + throw Error("token_ids must be a non-empty array of integers."); + } + let tokens = token_ids.map( + (i) => this.model.vocab[Number(i)] ?? this.model.unk_token + ); + if (options.skip_special_tokens) { + tokens = tokens.filter((x) => !this.special_tokens.includes(x)); + } + let decoded = this.decoder ? this.decoder(tokens) : tokens.join(" "); + if (this.decoder && this.decoder.end_of_word_suffix) { + decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, " "); + if (options.skip_special_tokens) { + decoded = decoded.trim(); + } + } + if (options.clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) { + decoded = clean_up_tokenization(decoded); + } + return decoded; } /** - * The variables declared in this environment. + * Converts a string into a sequence of tokens. + * @param text The sequence to be encoded. + * @param options An optional object containing the following properties: + * @returns The list of tokens. */ - variables = /* @__PURE__ */ new Map([ - [ - "namespace", - new FunctionValue((args) => { - if (args.length === 0) { - return new ObjectValue(/* @__PURE__ */ new Map()); - } - if (args.length !== 1 || !(args[0] instanceof ObjectValue)) { - throw new Error("`namespace` expects either zero arguments or a single object argument"); + tokenize(text, { text_pair = null, add_special_tokens = false } = {}) { + return this.tokenize_helper(text, { text_pair, add_special_tokens }).tokens; + } + encode_text(text) { + if (text === null) { + return null; + } + const sections = this.splitter_unnormalized.split(text); + sections.forEach((section, i) => { + const added_token = this.added_tokens_map.get(section); + if (added_token) { + if (added_token.lstrip && i > 0) { + sections[i - 1] = sections[i - 1].trimEnd(); } - return args[0]; - }) - ] - ]); - /** - * The tests available in this environment. - */ - tests = /* @__PURE__ */ new Map([ - ["boolean", (operand) => operand.type === "BooleanValue"], - ["callable", (operand) => operand instanceof FunctionValue], - [ - "odd", - (operand) => { - if (!(operand instanceof IntegerValue)) { - throw new Error(`cannot odd on ${operand.type}`); + if (added_token.rstrip && i < sections.length - 1) { + sections[i + 1] = sections[i + 1].trimStart(); } - return operand.value % 2 !== 0; } - ], - [ - "even", - (operand) => { - if (!(operand instanceof IntegerValue)) { - throw new Error(`cannot even on ${operand.type}`); - } - return operand.value % 2 === 0; + }); + return sections.flatMap((processed_text, section_index) => { + if (processed_text.length === 0) { + return []; } - ], - ["false", (operand) => operand.type === "BooleanValue" && !operand.value], - ["true", (operand) => operand.type === "BooleanValue" && operand.value], - ["none", (operand) => operand.type === "NullValue"], - ["string", (operand) => operand.type === "StringValue"], - ["number", (operand) => operand instanceof IntegerValue || operand instanceof FloatValue], - ["integer", (operand) => operand instanceof IntegerValue], - ["iterable", (operand) => operand.type === "ArrayValue" || operand.type === "StringValue"], - ["mapping", (operand) => operand.type === "ObjectValue"], - [ - "lower", - (operand) => { - const str = operand.value; - return operand.type === "StringValue" && str === str.toLowerCase(); + if (this.added_tokens_map.has(processed_text)) { + return [processed_text]; } - ], - [ - "upper", - (operand) => { - const str = operand.value; - return operand.type === "StringValue" && str === str.toUpperCase(); + if (this.remove_space === true) { + processed_text = processed_text.trim().split(/\s+/).join(" "); } - ], - ["none", (operand) => operand.type === "NullValue"], - ["defined", (operand) => operand.type !== "UndefinedValue"], - ["undefined", (operand) => operand.type === "UndefinedValue"], - ["equalto", (a, b) => a.value === b.value], - ["eq", (a, b) => a.value === b.value] - ]); - /** - * Set the value of a variable in the current environment. - */ - set(name, value) { - return this.declareVariable(name, convertToRuntimeValues(value)); + if (this.do_lowercase_and_remove_accent) { + processed_text = lowercase_and_remove_accents(processed_text); + } + if (this.normalizer !== null) { + processed_text = this.normalizer(processed_text); + } + if (processed_text.length === 0) { + return []; + } + const subsections = this.splitter_normalized.split(processed_text); + subsections.forEach((subsection, j2) => { + const added_token = this.added_tokens_map.get(subsection); + if (added_token) { + if (added_token.lstrip && j2 > 0) { + subsections[j2 - 1] = subsections[j2 - 1].trimEnd(); + } + if (added_token.rstrip && j2 < subsections.length - 1) { + subsections[j2 + 1] = subsections[j2 + 1].trimStart(); + } + } + }); + return subsections.flatMap((subsection) => { + if (subsection.length === 0) { + return []; + } + if (this.added_tokens_map.has(subsection)) { + return [subsection]; + } + const section_tokens = this.pre_tokenizer !== null ? this.pre_tokenizer(subsection, { + section_index + }) : [subsection]; + return this.model(section_tokens); + }); + }); } - declareVariable(name, value) { - if (this.variables.has(name)) { - throw new SyntaxError(`Variable already declared: ${name}`); - } - this.variables.set(name, value); - return value; + tokenize_helper(text, { text_pair = null, add_special_tokens = true }) { + const tokens1 = this.encode_text(text); + const tokens2 = this.encode_text(text_pair || null); + return this.post_processor ? this.post_processor(tokens1, tokens2, add_special_tokens) : { tokens: merge_arrays(tokens1 ?? [], tokens2 ?? []) }; } - // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue { - // const env = this.resolve(name); - // env.variables.set(name, value); - // return value; - // } /** - * Set variable in the current scope. - * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information. + * Converts a token string to its corresponding token ID. + * @param token The token string to convert. + * @returns The token ID, or undefined if the token is not in the vocabulary. */ - setVariable(name, value) { - this.variables.set(name, value); - return value; + token_to_id(token) { + return this.model.tokens_to_ids.get(token); } /** - * Resolve the environment in which the variable is declared. - * @param {string} name The name of the variable. - * @returns {Environment} The environment in which the variable is declared. + * Converts a token ID to its corresponding token string. + * @param id The token ID to convert. + * @returns The token string, or undefined if the ID is not in the vocabulary. */ - resolve(name) { - if (this.variables.has(name)) { - return this; - } - if (this.parent) { - return this.parent.resolve(name); - } - throw new Error(`Unknown variable: ${name}`); - } - lookupVariable(name) { - try { - return this.resolve(name).variables.get(name) ?? new UndefinedValue(); - } catch { - return new UndefinedValue(); - } - } -}; -function setupGlobals(env) { - env.set("false", false); - env.set("true", true); - env.set("none", null); - env.set("raise_exception", (args) => { - throw new Error(args); - }); - env.set("range", range); - env.set("strftime_now", strftime_now); - env.set("True", true); - env.set("False", false); - env.set("None", null); -} -var Interpreter = class { - global; - constructor(env) { - this.global = env ?? new Environment(); + id_to_token(id) { + return this.model.vocab[id]; } /** - * Run the program. + * Returns a mapping of token IDs to AddedToken objects for all added tokens. + * @returns A Map where keys are token IDs and values are AddedToken objects. */ - run(program) { - return this.evaluate(program, this.global); + get_added_tokens_decoder() { + const decoder = /* @__PURE__ */ new Map(); + for (const token of this.added_tokens) { + decoder.set(token.id, token); + } + return decoder; } /** - * Evaluates expressions following the binary operation type. + * Get the underlying vocabulary + * @param with_added_tokens Whether to include the added tokens + * @returns The vocabulary */ - evaluateBinaryExpression(node, environment) { - const left = this.evaluate(node.left, environment); - switch (node.operator.value) { - case "and": - return left.__bool__().value ? this.evaluate(node.right, environment) : left; - case "or": - return left.__bool__().value ? left : this.evaluate(node.right, environment); - } - const right = this.evaluate(node.right, environment); - switch (node.operator.value) { - case "==": - return new BooleanValue(left.value == right.value); - case "!=": - return new BooleanValue(left.value != right.value); - } - if (left instanceof UndefinedValue || right instanceof UndefinedValue) { - if (right instanceof UndefinedValue && ["in", "not in"].includes(node.operator.value)) { - return new BooleanValue(node.operator.value === "not in"); + get_vocab(with_added_tokens = true) { + const vocab = /* @__PURE__ */ new Map(); + for (let i = 0; i < this.model.vocab.length; ++i) { + const token = this.model.vocab[i]; + if (with_added_tokens || !this.added_tokens_map.has(token)) { + vocab.set(token, i); } - throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`); - } else if (left instanceof NullValue || right instanceof NullValue) { - throw new Error("Cannot perform operation on null values"); - } else if (node.operator.value === "~") { - return new StringValue(left.value.toString() + right.value.toString()); - } else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) { - const a = left.value, b = right.value; - switch (node.operator.value) { - case "+": - case "-": - case "*": { - const res = node.operator.value === "+" ? a + b : node.operator.value === "-" ? a - b : a * b; - const isFloat = left instanceof FloatValue || right instanceof FloatValue; - return isFloat ? new FloatValue(res) : new IntegerValue(res); + } + return vocab; + } +}; +var Tokenizer_default = Tokenizer; + +// ../../node_modules/.pnpm/@huggingface+jinja@0.5.10/node_modules/@huggingface/jinja/dist/index.js +var __defProp2 = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; +var TOKEN_TYPES = Object.freeze({ + Text: "Text", + // The text between Jinja statements or expressions + NumericLiteral: "NumericLiteral", + // e.g., 123, 1.0 + StringLiteral: "StringLiteral", + // 'string' + Identifier: "Identifier", + // Variables, functions, statements, booleans, etc. + 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", + // * / // % + ExponentiationBinaryOperator: "ExponentiationBinaryOperator", + // ** + ComparisonBinaryOperator: "ComparisonBinaryOperator", + // < > <= >= == != + UnaryOperator: "UnaryOperator", + // ! - + + Comment: "Comment" + // {# ... #} +}); +var Token = class { + /** + * Constructs a new Token. + * @param {string} value The raw value as seen inside the source code. + * @param {TokenType} type The type of token. + */ + constructor(value, type) { + this.value = value; + this.type = type; + } +}; +function isWord(char) { + return /\w/.test(char); +} +function isInteger(char) { + return /[0-9]/.test(char); +} +function isWhitespace(char) { + return /\s/.test(char); +} +var ORDERED_MAPPING_TABLE = [ + // Control sequences + ["{%", TOKEN_TYPES.OpenStatement], + ["%}", TOKEN_TYPES.CloseStatement], + ["{{", TOKEN_TYPES.OpenExpression], + ["}}", TOKEN_TYPES.CloseExpression], + // Single character tokens + ["(", TOKEN_TYPES.OpenParen], + [")", TOKEN_TYPES.CloseParen], + ["{", TOKEN_TYPES.OpenCurlyBracket], + ["}", TOKEN_TYPES.CloseCurlyBracket], + ["[", TOKEN_TYPES.OpenSquareBracket], + ["]", TOKEN_TYPES.CloseSquareBracket], + [",", TOKEN_TYPES.Comma], + [".", TOKEN_TYPES.Dot], + [":", TOKEN_TYPES.Colon], + ["|", TOKEN_TYPES.Pipe], + // Comparison operators + ["<=", TOKEN_TYPES.ComparisonBinaryOperator], + [">=", TOKEN_TYPES.ComparisonBinaryOperator], + ["==", TOKEN_TYPES.ComparisonBinaryOperator], + ["!=", TOKEN_TYPES.ComparisonBinaryOperator], + ["<", TOKEN_TYPES.ComparisonBinaryOperator], + [">", TOKEN_TYPES.ComparisonBinaryOperator], + // Arithmetic operators + ["+", TOKEN_TYPES.AdditiveBinaryOperator], + ["-", TOKEN_TYPES.AdditiveBinaryOperator], + ["~", TOKEN_TYPES.AdditiveBinaryOperator], + ["**", TOKEN_TYPES.ExponentiationBinaryOperator], + // NOTE: must come before "*" so that "**" is matched first + ["*", TOKEN_TYPES.MultiplicativeBinaryOperator], + ["//", TOKEN_TYPES.MultiplicativeBinaryOperator], + // NOTE: must come before "/" so that "//" is matched first + ["/", TOKEN_TYPES.MultiplicativeBinaryOperator], + ["%", TOKEN_TYPES.MultiplicativeBinaryOperator], + // Assignment operator + ["=", TOKEN_TYPES.Equals] +]; +var ESCAPE_CHARACTERS = /* @__PURE__ */ new Map([ + ["n", "\n"], + // New line + ["t", " "], + // Horizontal tab + ["r", "\r"], + // Carriage return + ["b", "\b"], + // Backspace + ["f", "\f"], + // Form feed + ["v", "\v"], + // Vertical tab + ["'", "'"], + // Single quote + ['"', '"'], + // Double quote + ["\\", "\\"] + // Backslash +]); +function preprocess(template, options = {}) { + if (template.endsWith("\n")) { + template = template.slice(0, -1); + } + if (options.lstrip_blocks) { + template = template.replace(/^[ \t]*({[#%-])/gm, "$1"); + } + if (options.trim_blocks) { + template = template.replace(/([#%-]})\n/g, "$1"); + } + return template.replace( + /(\s*){%(-?)\s*(?:end)?generation\s*(-?)%}(\s*)/gs, + (_, before, lstrip, rstrip, after) => (lstrip ? "" : before) + (rstrip ? "" : after) + ); +} +function tokenize(source, options = {}) { + const tokens = []; + const src = preprocess(source, options); + let cursorPosition = 0; + let curlyBracketDepth = 0; + const consumeWhile = (predicate) => { + let str = ""; + while (predicate(src[cursorPosition])) { + if (src[cursorPosition] === "\\") { + ++cursorPosition; + if (cursorPosition >= src.length) { + throw new SyntaxError("Unexpected end of input"); } - case "/": - return new FloatValue(a / b); - case "%": { - const rem = a % b; - const isFloat = left instanceof FloatValue || right instanceof FloatValue; - return isFloat ? new FloatValue(rem) : new IntegerValue(rem); + const escaped = src[cursorPosition++]; + const unescaped = ESCAPE_CHARACTERS.get(escaped); + if (unescaped === void 0) { + throw new SyntaxError(`Unexpected escaped character: ${escaped}`); } - case "<": - return new BooleanValue(a < b); - case ">": - return new BooleanValue(a > b); - case ">=": - return new BooleanValue(a >= b); - case "<=": - return new BooleanValue(a <= b); - } - } else if (left instanceof ArrayValue && right instanceof ArrayValue) { - switch (node.operator.value) { - case "+": - return new ArrayValue(left.value.concat(right.value)); + str += unescaped; + continue; } - } else if (right instanceof ArrayValue) { - const member = right.value.find((x) => x.value === left.value) !== void 0; - switch (node.operator.value) { - case "in": - return new BooleanValue(member); - case "not in": - return new BooleanValue(!member); + str += src[cursorPosition++]; + if (cursorPosition >= src.length) { + throw new SyntaxError("Unexpected end of input"); } } - if (left instanceof StringValue || right instanceof StringValue) { - switch (node.operator.value) { - case "+": - return new StringValue(left.value.toString() + right.value.toString()); + return str; + }; + const stripTrailingWhitespace = () => { + const lastToken = tokens.at(-1); + if (lastToken && lastToken.type === TOKEN_TYPES.Text) { + lastToken.value = lastToken.value.trimEnd(); + if (lastToken.value === "") { + tokens.pop(); } } - if (left instanceof StringValue && right instanceof StringValue) { - switch (node.operator.value) { - case "in": - return new BooleanValue(right.value.includes(left.value)); - case "not in": - return new BooleanValue(!right.value.includes(left.value)); - } + }; + const skipLeadingWhitespace = () => { + while (cursorPosition < src.length && isWhitespace(src[cursorPosition])) { + ++cursorPosition; } - if (left instanceof StringValue && right instanceof ObjectValue) { - switch (node.operator.value) { - case "in": - return new BooleanValue(right.value.has(left.value)); - case "not in": - return new BooleanValue(!right.value.has(left.value)); + }; + main: + while (cursorPosition < src.length) { + const lastTokenType = tokens.at(-1)?.type; + if (lastTokenType === void 0 || lastTokenType === TOKEN_TYPES.CloseStatement || lastTokenType === TOKEN_TYPES.CloseExpression || lastTokenType === TOKEN_TYPES.Comment) { + let text = ""; + while (cursorPosition < src.length && // Keep going until we hit the next Jinja statement or expression + !(src[cursorPosition] === "{" && (src[cursorPosition + 1] === "%" || src[cursorPosition + 1] === "{" || src[cursorPosition + 1] === "#"))) { + text += src[cursorPosition++]; + } + if (text.length > 0) { + tokens.push(new Token(text, TOKEN_TYPES.Text)); + continue; + } } - } - throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`); - } - evaluateArguments(args, environment) { - const positionalArguments = []; - const keywordArguments = /* @__PURE__ */ new Map(); - for (const argument of args) { - if (argument.type === "SpreadExpression") { - const spreadNode = argument; - const val = this.evaluate(spreadNode.argument, environment); - if (!(val instanceof ArrayValue)) { - throw new Error(`Cannot unpack non-iterable type: ${val.type}`); + if (src[cursorPosition] === "{" && src[cursorPosition + 1] === "#") { + cursorPosition += 2; + const stripBefore = src[cursorPosition] === "-"; + if (stripBefore) { + ++cursorPosition; } - for (const item of val.value) { - positionalArguments.push(item); + let comment = ""; + while (src[cursorPosition] !== "#" || src[cursorPosition + 1] !== "}") { + if (cursorPosition + 2 >= src.length) { + throw new SyntaxError("Missing end of comment tag"); + } + comment += src[cursorPosition++]; } - } else if (argument.type === "KeywordArgumentExpression") { - const kwarg = argument; - keywordArguments.set(kwarg.key.value, this.evaluate(kwarg.value, environment)); - } else { - if (keywordArguments.size > 0) { - throw new Error("Positional arguments must come before keyword arguments"); + const stripAfter = comment.endsWith("-"); + if (stripAfter) { + comment = comment.slice(0, -1); } - positionalArguments.push(this.evaluate(argument, environment)); + if (stripBefore) { + stripTrailingWhitespace(); + } + tokens.push(new Token(comment, TOKEN_TYPES.Comment)); + cursorPosition += 2; + if (stripAfter) { + skipLeadingWhitespace(); + } + continue; } - } - return [positionalArguments, keywordArguments]; - } - applyFilter(operand, filterNode, environment) { - if (filterNode.type === "Identifier") { - const filter = filterNode; - if (filter.value === "tojson") { - return new StringValue(toJSON(operand)); + if (src.slice(cursorPosition, cursorPosition + 3) === "{%-") { + stripTrailingWhitespace(); + tokens.push(new Token("{%", TOKEN_TYPES.OpenStatement)); + cursorPosition += 3; + continue; } - if (operand instanceof ArrayValue) { - switch (filter.value) { - case "list": - return operand; - case "first": - return operand.value[0]; - case "last": - return operand.value[operand.value.length - 1]; - case "length": - return new IntegerValue(operand.value.length); - case "reverse": - return new ArrayValue(operand.value.reverse()); - case "sort": - return new ArrayValue( - operand.value.sort((a, b) => { - if (a.type !== b.type) { - throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`); - } - switch (a.type) { - case "IntegerValue": - case "FloatValue": - return a.value - b.value; - case "StringValue": - return a.value.localeCompare(b.value); - default: - throw new Error(`Cannot compare type: ${a.type}`); - } - }) - ); - case "join": - return new StringValue(operand.value.map((x) => x.value).join("")); - case "string": - return new StringValue(toJSON(operand)); - case "unique": { - const seen = /* @__PURE__ */ new Set(); - const output = []; - for (const item of operand.value) { - if (!seen.has(item.value)) { - seen.add(item.value); - output.push(item); - } - } - return new ArrayValue(output); - } - default: - throw new Error(`Unknown ArrayValue filter: ${filter.value}`); + if (src.slice(cursorPosition, cursorPosition + 3) === "{{-") { + stripTrailingWhitespace(); + tokens.push(new Token("{{", TOKEN_TYPES.OpenExpression)); + curlyBracketDepth = 0; + cursorPosition += 3; + continue; + } + consumeWhile(isWhitespace); + if (src.slice(cursorPosition, cursorPosition + 3) === "-%}") { + tokens.push(new Token("%}", TOKEN_TYPES.CloseStatement)); + cursorPosition += 3; + skipLeadingWhitespace(); + continue; + } + if (src.slice(cursorPosition, cursorPosition + 3) === "-}}") { + tokens.push(new Token("}}", TOKEN_TYPES.CloseExpression)); + cursorPosition += 3; + skipLeadingWhitespace(); + continue; + } + const char = src[cursorPosition]; + if (char === "-" || char === "+") { + const lastTokenType2 = tokens.at(-1)?.type; + if (lastTokenType2 === TOKEN_TYPES.Text || lastTokenType2 === void 0) { + throw new SyntaxError(`Unexpected character: ${char}`); } - } else if (operand instanceof StringValue) { - switch (filter.value) { - case "length": - case "upper": - case "lower": - case "title": - case "capitalize": { - const builtin = operand.builtins.get(filter.value); - if (builtin instanceof FunctionValue) { - return builtin.value( - /* no arguments */ - [], - environment - ); - } else if (builtin instanceof IntegerValue) { - return builtin; - } else { - throw new Error(`Unknown StringValue filter: ${filter.value}`); + switch (lastTokenType2) { + case TOKEN_TYPES.Identifier: + case TOKEN_TYPES.NumericLiteral: + case TOKEN_TYPES.StringLiteral: + case TOKEN_TYPES.CloseParen: + case TOKEN_TYPES.CloseSquareBracket: + break; + default: { + ++cursorPosition; + let num = consumeWhile(isInteger); + if (num.length > 0 && src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) { + ++cursorPosition; + const frac = consumeWhile(isInteger); + num = `${num}.${frac}`; } - } - case "trim": - return new StringValue(operand.value.trim()); - case "indent": - return new StringValue( - operand.value.split("\n").map( - (x, i) => ( - // By default, don't indent the first line or empty lines - i === 0 || x.length === 0 ? x : " " + x - ) - ).join("\n") + tokens.push( + new Token(`${char}${num}`, num.length > 0 ? TOKEN_TYPES.NumericLiteral : TOKEN_TYPES.UnaryOperator) ); - case "join": - case "string": - return operand; - case "int": { - const val = parseInt(operand.value, 10); - return new IntegerValue(isNaN(val) ? 0 : val); - } - case "float": { - const val = parseFloat(operand.value); - return new FloatValue(isNaN(val) ? 0 : val); + continue; } - default: - throw new Error(`Unknown StringValue filter: ${filter.value}`); - } - } else if (operand instanceof IntegerValue || operand instanceof FloatValue) { - switch (filter.value) { - case "abs": - return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value)); - case "int": - return new IntegerValue(Math.floor(operand.value)); - case "float": - return new FloatValue(operand.value); - default: - throw new Error(`Unknown NumericValue filter: ${filter.value}`); } - } else if (operand instanceof ObjectValue) { - switch (filter.value) { - case "items": - return new ArrayValue( - Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) - ); - case "length": - return new IntegerValue(operand.value.size); - default: - throw new Error(`Unknown ObjectValue filter: ${filter.value}`); + } + for (const [seq, type] of ORDERED_MAPPING_TABLE) { + if (seq === "}}" && curlyBracketDepth > 0) { + continue; } - } else if (operand instanceof BooleanValue) { - switch (filter.value) { - case "bool": - return new BooleanValue(operand.value); - case "int": - return new IntegerValue(operand.value ? 1 : 0); - case "float": - return new FloatValue(operand.value ? 1 : 0); - case "string": - return new StringValue(operand.value ? "true" : "false"); - default: - throw new Error(`Unknown BooleanValue filter: ${filter.value}`); + const slice22 = src.slice(cursorPosition, cursorPosition + seq.length); + if (slice22 === seq) { + tokens.push(new Token(seq, type)); + if (type === TOKEN_TYPES.OpenExpression) { + curlyBracketDepth = 0; + } else if (type === TOKEN_TYPES.OpenCurlyBracket) { + ++curlyBracketDepth; + } else if (type === TOKEN_TYPES.CloseCurlyBracket) { + --curlyBracketDepth; + } + cursorPosition += seq.length; + continue main; } } - throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`); - } else if (filterNode.type === "CallExpression") { - const filter = filterNode; - if (filter.callee.type !== "Identifier") { - throw new Error(`Unknown filter: ${filter.callee.type}`); + if (char === "'" || char === '"') { + ++cursorPosition; + const str = consumeWhile((c) => c !== char); + tokens.push(new Token(str, TOKEN_TYPES.StringLiteral)); + ++cursorPosition; + continue; } - const filterName = filter.callee.value; - if (filterName === "tojson") { - const [, kwargs] = this.evaluateArguments(filter.args, environment); - const indent = kwargs.get("indent") ?? new NullValue(); - if (!(indent instanceof IntegerValue || indent instanceof NullValue)) { - throw new Error("If set, indent must be a number"); - } - return new StringValue(toJSON(operand, indent.value)); - } else if (filterName === "join") { - let value; - if (operand instanceof StringValue) { - value = Array.from(operand.value); - } else if (operand instanceof ArrayValue) { - value = operand.value.map((x) => x.value); - } else { - throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); - } - const [args, kwargs] = this.evaluateArguments(filter.args, environment); - const separator = args.at(0) ?? kwargs.get("separator") ?? new StringValue(""); - if (!(separator instanceof StringValue)) { - throw new Error("separator must be a string"); - } - return new StringValue(value.join(separator.value)); - } else if (filterName === "int" || filterName === "float") { - const [args, kwargs] = this.evaluateArguments(filter.args, environment); - const defaultValue = args.at(0) ?? kwargs.get("default") ?? (filterName === "int" ? new IntegerValue(0) : new FloatValue(0)); - if (operand instanceof StringValue) { - const val = filterName === "int" ? parseInt(operand.value, 10) : parseFloat(operand.value); - return isNaN(val) ? defaultValue : filterName === "int" ? new IntegerValue(val) : new FloatValue(val); - } else if (operand instanceof IntegerValue || operand instanceof FloatValue) { - return operand; - } else if (operand instanceof BooleanValue) { - return filterName === "int" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0); - } else { - throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); - } - } else if (filterName === "default") { - const [args, kwargs] = this.evaluateArguments(filter.args, environment); - const defaultValue = args[0] ?? new StringValue(""); - const booleanValue = args[1] ?? kwargs.get("boolean") ?? new BooleanValue(false); - if (!(booleanValue instanceof BooleanValue)) { - throw new Error("`default` filter flag must be a boolean"); - } - if (operand instanceof UndefinedValue || booleanValue.value && !operand.__bool__().value) { - return defaultValue; + if (isInteger(char)) { + let num = consumeWhile(isInteger); + if (tokens.at(-1)?.type !== TOKEN_TYPES.Dot && src[cursorPosition] === "." && isInteger(src[cursorPosition + 1])) { + ++cursorPosition; + const frac = consumeWhile(isInteger); + num = `${num}.${frac}`; } - return operand; + tokens.push(new Token(num, TOKEN_TYPES.NumericLiteral)); + continue; } - if (operand instanceof ArrayValue) { - switch (filterName) { - case "selectattr": - case "rejectattr": { - const select = filterName === "selectattr"; - if (operand.value.some((x) => !(x instanceof ObjectValue))) { - throw new Error(`\`${filterName}\` can only be applied to array of objects`); - } - if (filter.args.some((x) => x.type !== "StringLiteral")) { - throw new Error(`arguments of \`${filterName}\` must be strings`); - } - const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment)); - let testFunction; - if (testName) { - const test = environment.tests.get(testName.value); - if (!test) { - throw new Error(`Unknown test: ${testName.value}`); - } - testFunction = test; - } else { - testFunction = (...x) => x[0].__bool__().value; - } - const filtered = operand.value.filter((item) => { - const a = item.value.get(attr.value); - const result = a ? testFunction(a, value) : false; - return select ? result : !result; - }); - return new ArrayValue(filtered); - } - case "map": { - const [, kwargs] = this.evaluateArguments(filter.args, environment); - if (kwargs.has("attribute")) { - const attr = kwargs.get("attribute"); - if (!(attr instanceof StringValue)) { - throw new Error("attribute must be a string"); - } - const defaultValue = kwargs.get("default"); - const mapped = operand.value.map((item) => { - if (!(item instanceof ObjectValue)) { - throw new Error("items in map must be an object"); - } - return item.value.get(attr.value) ?? defaultValue ?? new UndefinedValue(); - }); - return new ArrayValue(mapped); - } else { - throw new Error("`map` expressions without `attribute` set are not currently supported."); - } - } - } - throw new Error(`Unknown ArrayValue filter: ${filterName}`); - } else if (operand instanceof StringValue) { - switch (filterName) { - case "indent": { - const [args, kwargs] = this.evaluateArguments(filter.args, environment); - const width = args.at(0) ?? kwargs.get("width") ?? new IntegerValue(4); - if (!(width instanceof IntegerValue)) { - throw new Error("width must be a number"); - } - const first = args.at(1) ?? kwargs.get("first") ?? new BooleanValue(false); - const blank = args.at(2) ?? kwargs.get("blank") ?? new BooleanValue(false); - const lines = operand.value.split("\n"); - const indent = " ".repeat(width.value); - const indented = lines.map( - (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x - ); - return new StringValue(indented.join("\n")); - } - case "replace": { - const replaceFn = operand.builtins.get("replace"); - if (!(replaceFn instanceof FunctionValue)) { - throw new Error("replace filter not available"); - } - const [args, kwargs] = this.evaluateArguments(filter.args, environment); - return replaceFn.value([...args, new KeywordArgumentsValue(kwargs)], environment); - } - } - throw new Error(`Unknown StringValue filter: ${filterName}`); - } else { - throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); + if (isWord(char)) { + const word = consumeWhile(isWord); + tokens.push(new Token(word, TOKEN_TYPES.Identifier)); + continue; } + throw new SyntaxError(`Unexpected character: ${char}`); } - throw new Error(`Unknown filter: ${filterNode.type}`); + return tokens; +} +var Statement = class { + type = "Statement"; +}; +var Program = class extends Statement { + constructor(body) { + super(); + this.body = body; } - /** - * Evaluates expressions following the filter operation type. - */ - evaluateFilterExpression(node, environment) { - const operand = this.evaluate(node.operand, environment); - return this.applyFilter(operand, node.filter, environment); + type = "Program"; +}; +var If = class extends Statement { + constructor(test, body, alternate) { + super(); + this.test = test; + this.body = body; + this.alternate = alternate; } - /** - * Evaluates expressions following the test operation type. - */ - evaluateTestExpression(node, environment) { - const operand = this.evaluate(node.operand, environment); - const test = environment.tests.get(node.test.value); - if (!test) { - throw new Error(`Unknown test: ${node.test.value}`); - } - const result = test(operand); - return new BooleanValue(node.negate ? !result : result); + type = "If"; +}; +var For = class extends Statement { + constructor(loopvar, iterable, body, defaultBlock) { + super(); + this.loopvar = loopvar; + this.iterable = iterable; + this.body = body; + this.defaultBlock = defaultBlock; } - /** - * Evaluates expressions following the select operation type. - */ - evaluateSelectExpression(node, environment) { - const predicate = this.evaluate(node.test, environment); - if (!predicate.__bool__().value) { - return new UndefinedValue(); - } - return this.evaluate(node.lhs, environment); + type = "For"; +}; +var Break = class extends Statement { + type = "Break"; +}; +var Continue = class extends Statement { + type = "Continue"; +}; +var SetStatement = class extends Statement { + constructor(assignee, value, body) { + super(); + this.assignee = assignee; + this.value = value; + this.body = body; + } + type = "Set"; +}; +var Macro = class extends Statement { + constructor(name, args, body) { + super(); + this.name = name; + this.args = args; + this.body = body; + } + type = "Macro"; +}; +var Comment = class extends Statement { + constructor(value) { + super(); + this.value = value; + } + type = "Comment"; +}; +var Expression = class extends Statement { + type = "Expression"; +}; +var MemberExpression = class extends Expression { + constructor(object, property, computed) { + super(); + this.object = object; + this.property = property; + this.computed = computed; + } + type = "MemberExpression"; +}; +var CallExpression = class extends Expression { + constructor(callee, args) { + super(); + this.callee = callee; + this.args = args; } + type = "CallExpression"; +}; +var Identifier = class extends Expression { /** - * Evaluates expressions following the unary operation type. + * @param {string} value The name of the identifier */ - evaluateUnaryExpression(node, environment) { - const argument = this.evaluate(node.argument, environment); - switch (node.operator.value) { - case "not": - return new BooleanValue(!argument.value); - default: - throw new SyntaxError(`Unknown operator: ${node.operator.value}`); - } - } - evaluateTernaryExpression(node, environment) { - const cond = this.evaluate(node.condition, environment); - return cond.__bool__().value ? this.evaluate(node.trueExpr, environment) : this.evaluate(node.falseExpr, environment); + constructor(value) { + super(); + this.value = value; } - evalProgram(program, environment) { - return this.evaluateBlock(program.body, environment); + type = "Identifier"; +}; +var Literal = class extends Expression { + constructor(value) { + super(); + this.value = value; } - evaluateBlock(statements, environment) { - let result = ""; - for (const statement of statements) { - const lastEvaluated = this.evaluate(statement, environment); - if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") { - result += lastEvaluated.toString(); - } - } - return new StringValue(result); + type = "Literal"; +}; +var IntegerLiteral = class extends Literal { + type = "IntegerLiteral"; +}; +var FloatLiteral = class extends Literal { + type = "FloatLiteral"; +}; +var StringLiteral = class extends Literal { + type = "StringLiteral"; +}; +var ArrayLiteral = class extends Literal { + type = "ArrayLiteral"; +}; +var TupleLiteral = class extends Literal { + type = "TupleLiteral"; +}; +var ObjectLiteral = class extends Literal { + type = "ObjectLiteral"; +}; +var BinaryExpression = class extends Expression { + constructor(operator, left, right) { + super(); + this.operator = operator; + this.left = left; + this.right = right; } - evaluateIdentifier(node, environment) { - return environment.lookupVariable(node.value); + type = "BinaryExpression"; +}; +var FilterExpression = class extends Expression { + constructor(operand, filter) { + super(); + this.operand = operand; + this.filter = filter; } - evaluateCallExpression(expr, environment) { - const [args, kwargs] = this.evaluateArguments(expr.args, environment); - if (kwargs.size > 0) { - args.push(new KeywordArgumentsValue(kwargs)); - } - const fn = this.evaluate(expr.callee, environment); - if (fn.type !== "FunctionValue") { - throw new Error(`Cannot call something that is not a function: got ${fn.type}`); - } - return fn.value(args, environment); + type = "FilterExpression"; +}; +var FilterStatement = class extends Statement { + constructor(filter, body) { + super(); + this.filter = filter; + this.body = body; } - evaluateSliceExpression(object, expr, environment) { - if (!(object instanceof ArrayValue || object instanceof StringValue)) { - throw new Error("Slice object must be an array or string"); - } - const start = this.evaluate(expr.start, environment); - const stop = this.evaluate(expr.stop, environment); - const step = this.evaluate(expr.step, environment); - if (!(start instanceof IntegerValue || start instanceof UndefinedValue)) { - throw new Error("Slice start must be numeric or undefined"); - } - if (!(stop instanceof IntegerValue || stop instanceof UndefinedValue)) { - throw new Error("Slice stop must be numeric or undefined"); - } - if (!(step instanceof IntegerValue || step instanceof UndefinedValue)) { - throw new Error("Slice step must be numeric or undefined"); - } - if (object instanceof ArrayValue) { - return new ArrayValue(slice(object.value, start.value, stop.value, step.value)); - } else { - return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join("")); - } + type = "FilterStatement"; +}; +var SelectExpression = class extends Expression { + constructor(lhs, test) { + super(); + this.lhs = lhs; + this.test = test; } - evaluateMemberExpression(expr, environment) { - const object = this.evaluate(expr.object, environment); - let property; - if (expr.computed) { - if (expr.property.type === "SliceExpression") { - return this.evaluateSliceExpression(object, expr.property, environment); - } else { - property = this.evaluate(expr.property, environment); - } - } else { - property = new StringValue(expr.property.value); + type = "SelectExpression"; +}; +var TestExpression = class extends Expression { + constructor(operand, negate, test) { + super(); + this.operand = operand; + this.negate = negate; + this.test = test; + } + type = "TestExpression"; +}; +var UnaryExpression = class extends Expression { + constructor(operator, argument) { + super(); + this.operator = operator; + this.argument = argument; + } + type = "UnaryExpression"; +}; +var SliceExpression = class extends Expression { + constructor(start = void 0, stop = void 0, step = void 0) { + super(); + this.start = start; + this.stop = stop; + this.step = step; + } + type = "SliceExpression"; +}; +var KeywordArgumentExpression = class extends Expression { + constructor(key, value) { + super(); + this.key = key; + this.value = value; + } + type = "KeywordArgumentExpression"; +}; +var SpreadExpression = class extends Expression { + constructor(argument) { + super(); + this.argument = argument; + } + type = "SpreadExpression"; +}; +var KeywordSpreadExpression = class extends Expression { + constructor(argument) { + super(); + this.argument = argument; + } + type = "KeywordSpreadExpression"; +}; +var CallStatement = class extends Statement { + constructor(call, callerArgs, body) { + super(); + this.call = call; + this.callerArgs = callerArgs; + this.body = body; + } + type = "CallStatement"; +}; +var Ternary = class extends Expression { + constructor(condition, trueExpr, falseExpr) { + super(); + this.condition = condition; + this.trueExpr = trueExpr; + this.falseExpr = falseExpr; + } + type = "Ternary"; +}; +function parse(tokens) { + const program = new Program([]); + let current = 0; + function expect(type, error) { + const prev = tokens[current++]; + if (!prev || prev.type !== type) { + throw new Error(`Parser Error: ${error}. ${prev.type} !== ${type}.`); } - let value; - if (object instanceof ObjectValue) { - if (!(property instanceof StringValue)) { - throw new Error(`Cannot access property with non-string: got ${property.type}`); - } - value = object.value.get(property.value) ?? object.builtins.get(property.value); - } else if (object instanceof ArrayValue || object instanceof StringValue) { - if (property instanceof IntegerValue) { - value = object.value.at(property.value); - if (object instanceof StringValue) { - value = new StringValue(object.value.at(property.value)); - } - } else if (property instanceof StringValue) { - value = object.builtins.get(property.value); - } else { - throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`); - } - } else { - if (!(property instanceof StringValue)) { - throw new Error(`Cannot access property with non-string: got ${property.type}`); - } - value = object.builtins.get(property.value); + return prev; + } + function expectIdentifier(name) { + if (!isIdentifier(name)) { + throw new SyntaxError(`Expected ${name}`); } - return value instanceof RuntimeValue ? value : new UndefinedValue(); + ++current; } - evaluateSet(node, environment) { - const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment); - if (node.assignee.type === "Identifier") { - const variableName = node.assignee.value; - environment.setVariable(variableName, rhs); - } else if (node.assignee.type === "TupleLiteral") { - const tuple = node.assignee; - if (!(rhs instanceof ArrayValue)) { - throw new Error(`Cannot unpack non-iterable type in set: ${rhs.type}`); - } - const arr = rhs.value; - if (arr.length !== tuple.value.length) { - throw new Error(`Too ${tuple.value.length > arr.length ? "few" : "many"} items to unpack in set`); - } - for (let i = 0; i < tuple.value.length; ++i) { - const elem = tuple.value[i]; - if (elem.type !== "Identifier") { - throw new Error(`Cannot unpack to non-identifier in set: ${elem.type}`); - } - environment.setVariable(elem.value, arr[i]); - } - } else if (node.assignee.type === "MemberExpression") { - const member = node.assignee; - const object = this.evaluate(member.object, environment); - if (!(object instanceof ObjectValue)) { - throw new Error("Cannot assign to member of non-object"); - } - if (member.property.type !== "Identifier") { - throw new Error("Cannot assign to member with non-identifier property"); - } - object.value.set(member.property.value, rhs); - } else { - throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`); + function parseAny() { + switch (tokens[current].type) { + case TOKEN_TYPES.Comment: + return new Comment(tokens[current++].value); + case TOKEN_TYPES.Text: + return parseText(); + case TOKEN_TYPES.OpenStatement: + return parseJinjaStatement(); + case TOKEN_TYPES.OpenExpression: + return parseJinjaExpression(); + default: + throw new SyntaxError(`Unexpected token type: ${tokens[current].type}`); } - return new NullValue(); } - evaluateIf(node, environment) { - const test = this.evaluate(node.test, environment); - return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment); + function is2(...types) { + return current + types.length <= tokens.length && types.every((type, i) => type === tokens[current + i].type); } - evaluateFor(node, environment) { - const scope = new Environment(environment); - let test, iterable; - if (node.iterable.type === "SelectExpression") { - const select = node.iterable; - iterable = this.evaluate(select.lhs, scope); - test = select.test; - } else { - iterable = this.evaluate(node.iterable, scope); - } - if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) { - throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`); - } - if (iterable instanceof ObjectValue) { - iterable = iterable.keys(); + function isStatement(...names) { + return tokens[current]?.type === TOKEN_TYPES.OpenStatement && tokens[current + 1]?.type === TOKEN_TYPES.Identifier && names.includes(tokens[current + 1]?.value); + } + function isIdentifier(...names) { + return current + names.length <= tokens.length && names.every((name, i) => tokens[current + i].type === "Identifier" && name === tokens[current + i].value); + } + function parseText() { + return new StringLiteral(expect(TOKEN_TYPES.Text, "Expected text token").value); + } + function parseJinjaStatement() { + expect(TOKEN_TYPES.OpenStatement, "Expected opening statement token"); + if (tokens[current].type !== TOKEN_TYPES.Identifier) { + throw new SyntaxError(`Unknown statement, got ${tokens[current].type}`); } - const items = []; - const scopeUpdateFunctions = []; - for (let i = 0; i < iterable.value.length; ++i) { - const loopScope = new Environment(scope); - const current = iterable.value[i]; - let scopeUpdateFunction; - if (node.loopvar.type === "Identifier") { - scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current); - } else if (node.loopvar.type === "TupleLiteral") { - const loopvar = node.loopvar; - if (current.type !== "ArrayValue") { - throw new Error(`Cannot unpack non-iterable type: ${current.type}`); + const name = tokens[current].value; + let result; + switch (name) { + case "set": + ++current; + result = parseSetStatement(); + break; + case "if": + ++current; + result = parseIfStatement(); + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endif"); + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + break; + case "macro": + ++current; + result = parseMacroStatement(); + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endmacro"); + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + break; + case "for": + ++current; + result = parseForStatement(); + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endfor"); + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + break; + case "call": { + ++current; + let callerArgs = null; + if (is2(TOKEN_TYPES.OpenParen)) { + callerArgs = parseArgs("parameters"); } - const c = current; - if (loopvar.value.length !== c.value.length) { - throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`); + const callee = parsePrimaryExpression(); + if (callee.type !== "Identifier") { + throw new SyntaxError(`Expected identifier following call statement`); } - scopeUpdateFunction = (scope2) => { - for (let j = 0; j < loopvar.value.length; ++j) { - if (loopvar.value[j].type !== "Identifier") { - throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j].type}`); - } - scope2.setVariable(loopvar.value[j].value, c.value[j]); - } - }; - } else { - throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`); - } - if (test) { - scopeUpdateFunction(loopScope); - const testValue = this.evaluate(test, loopScope); - if (!testValue.__bool__().value) { - continue; + const callArgs = parseArgs("call"); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + while (!isStatement("endcall")) { + body.push(parseAny()); } + expect(TOKEN_TYPES.OpenStatement, "Expected '{%'"); + expectIdentifier("endcall"); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const callExpr = new CallExpression(callee, callArgs); + result = new CallStatement(callExpr, callerArgs, body); + break; } - items.push(current); - scopeUpdateFunctions.push(scopeUpdateFunction); - } - let result = ""; - let noIteration = true; - for (let i = 0; i < items.length; ++i) { - const loop = /* @__PURE__ */ new Map([ - ["index", new IntegerValue(i + 1)], - ["index0", new IntegerValue(i)], - ["revindex", new IntegerValue(items.length - i)], - ["revindex0", new IntegerValue(items.length - i - 1)], - ["first", new BooleanValue(i === 0)], - ["last", new BooleanValue(i === items.length - 1)], - ["length", new IntegerValue(items.length)], - ["previtem", i > 0 ? items[i - 1] : new UndefinedValue()], - ["nextitem", i < items.length - 1 ? items[i + 1] : new UndefinedValue()] - ]); - scope.setVariable("loop", new ObjectValue(loop)); - scopeUpdateFunctions[i](scope); - try { - const evaluated = this.evaluateBlock(node.body, scope); - result += evaluated.value; - } catch (err) { - if (err instanceof ContinueControl) { - continue; - } - if (err instanceof BreakControl) { - break; - } - throw err; - } - noIteration = false; - } - if (noIteration) { - const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope); - result += defaultEvaluated.value; - } - return new StringValue(result); - } - /** - * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information. - */ - evaluateMacro(node, environment) { - environment.setVariable( - node.name.value, - new FunctionValue((args, scope) => { - const macroScope = new Environment(scope); - args = args.slice(); - let kwargs; - if (args.at(-1)?.type === "KeywordArgumentsValue") { - kwargs = args.pop(); - } - for (let i = 0; i < node.args.length; ++i) { - const nodeArg = node.args[i]; - const passedArg = args[i]; - if (nodeArg.type === "Identifier") { - const identifier = nodeArg; - if (!passedArg) { - throw new Error(`Missing positional argument: ${identifier.value}`); - } - macroScope.setVariable(identifier.value, passedArg); - } else if (nodeArg.type === "KeywordArgumentExpression") { - const kwarg = nodeArg; - const value = passedArg ?? // Try positional arguments first - kwargs?.value.get(kwarg.key.value) ?? // Look in user-passed kwargs - this.evaluate(kwarg.value, macroScope); - macroScope.setVariable(kwarg.key.value, value); - } else { - throw new Error(`Unknown argument type: ${nodeArg.type}`); - } - } - return this.evaluateBlock(node.body, macroScope); - }) - ); - return new NullValue(); - } - evaluateCallStatement(node, environment) { - const callerFn = new FunctionValue((callerArgs, callerEnv) => { - const callBlockEnv = new Environment(callerEnv); - if (node.callerArgs) { - for (let i = 0; i < node.callerArgs.length; ++i) { - const param = node.callerArgs[i]; - if (param.type !== "Identifier") { - throw new Error(`Caller parameter must be an identifier, got ${param.type}`); - } - callBlockEnv.setVariable(param.value, callerArgs[i] ?? new UndefinedValue()); - } - } - return this.evaluateBlock(node.body, callBlockEnv); - }); - const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment); - macroArgs.push(new KeywordArgumentsValue(macroKwargs)); - const fn = this.evaluate(node.call.callee, environment); - if (fn.type !== "FunctionValue") { - throw new Error(`Cannot call something that is not a function: got ${fn.type}`); - } - const newEnv = new Environment(environment); - newEnv.setVariable("caller", callerFn); - return fn.value(macroArgs, newEnv); - } - evaluateFilterStatement(node, environment) { - const rendered = this.evaluateBlock(node.body, environment); - return this.applyFilter(rendered, node.filter, environment); - } - evaluate(statement, environment) { - if (!statement) - return new UndefinedValue(); - switch (statement.type) { - case "Program": - return this.evalProgram(statement, environment); - case "Set": - return this.evaluateSet(statement, environment); - case "If": - return this.evaluateIf(statement, environment); - case "For": - return this.evaluateFor(statement, environment); - case "Macro": - return this.evaluateMacro(statement, environment); - case "CallStatement": - return this.evaluateCallStatement(statement, environment); - case "Break": - throw new BreakControl(); - case "Continue": - throw new ContinueControl(); - case "IntegerLiteral": - return new IntegerValue(statement.value); - case "FloatLiteral": - return new FloatValue(statement.value); - case "StringLiteral": - return new StringValue(statement.value); - case "ArrayLiteral": - return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment))); - case "TupleLiteral": - return new TupleValue(statement.value.map((x) => this.evaluate(x, environment))); - case "ObjectLiteral": { - const mapping = /* @__PURE__ */ new Map(); - for (const [key, value] of statement.value) { - const evaluatedKey = this.evaluate(key, environment); - if (!(evaluatedKey instanceof StringValue)) { - throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`); - } - mapping.set(evaluatedKey.value, this.evaluate(value, environment)); - } - return new ObjectValue(mapping); - } - case "Identifier": - return this.evaluateIdentifier(statement, environment); - case "CallExpression": - return this.evaluateCallExpression(statement, environment); - case "MemberExpression": - return this.evaluateMemberExpression(statement, environment); - case "UnaryExpression": - return this.evaluateUnaryExpression(statement, environment); - case "BinaryExpression": - return this.evaluateBinaryExpression(statement, environment); - case "FilterExpression": - return this.evaluateFilterExpression(statement, environment); - case "FilterStatement": - return this.evaluateFilterStatement(statement, environment); - case "TestExpression": - return this.evaluateTestExpression(statement, environment); - case "SelectExpression": - return this.evaluateSelectExpression(statement, environment); - case "Ternary": - return this.evaluateTernaryExpression(statement, environment); - case "Comment": - return new NullValue(); - default: - throw new SyntaxError(`Unknown node type: ${statement.type}`); - } - } -}; -function convertToRuntimeValues(input) { - switch (typeof input) { - case "number": - return Number.isInteger(input) ? new IntegerValue(input) : new FloatValue(input); - case "string": - return new StringValue(input); - case "boolean": - return new BooleanValue(input); - case "undefined": - return new UndefinedValue(); - case "object": - if (input === null) { - return new NullValue(); - } else if (Array.isArray(input)) { - return new ArrayValue(input.map(convertToRuntimeValues)); - } else { - return new ObjectValue( - new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)])) - ); - } - case "function": - return new FunctionValue((args, _scope) => { - const result = input(...args.map((x) => x.value)) ?? null; - return convertToRuntimeValues(result); - }); - default: - throw new Error(`Cannot convert to runtime value: ${input}`); - } -} -function toJSON(input, indent, depth) { - const currentDepth = depth ?? 0; - switch (input.type) { - case "NullValue": - case "UndefinedValue": - return "null"; - case "IntegerValue": - case "FloatValue": - case "StringValue": - case "BooleanValue": - return JSON.stringify(input.value); - case "ArrayValue": - case "ObjectValue": { - const indentValue = indent ? " ".repeat(indent) : ""; - const basePadding = "\n" + indentValue.repeat(currentDepth); - const childrenPadding = basePadding + indentValue; - if (input.type === "ArrayValue") { - const core = input.value.map((x) => toJSON(x, indent, currentDepth + 1)); - return indent ? `[${childrenPadding}${core.join(`,${childrenPadding}`)}${basePadding}]` : `[${core.join(", ")}]`; - } else { - const core = Array.from(input.value.entries()).map(([key, value]) => { - const v = `"${key}": ${toJSON(value, indent, currentDepth + 1)}`; - return indent ? `${childrenPadding}${v}` : v; - }); - return indent ? `{${core.join(",")}${basePadding}}` : `{${core.join(", ")}}`; - } - } - default: - throw new Error(`Cannot convert to JSON: ${input.type}`); - } -} - -// src/format.ts -var NEWLINE = "\n"; -var OPEN_STATEMENT = "{%- "; -var CLOSE_STATEMENT = " -%}"; -function getBinaryOperatorPrecedence(expr) { - switch (expr.operator.type) { - case "MultiplicativeBinaryOperator": - return 4; - case "AdditiveBinaryOperator": - return 3; - case "ComparisonBinaryOperator": - return 2; - case "Identifier": - if (expr.operator.value === "and") - return 1; - if (expr.operator.value === "in" || expr.operator.value === "not in") - return 2; - return 0; - } - return 0; -} -function format(program, indent = " ") { - const indentStr = typeof indent === "number" ? " ".repeat(indent) : indent; - const body = formatStatements(program.body, 0, indentStr); - return body.replace(/\n$/, ""); -} -function createStatement(...text) { - return OPEN_STATEMENT + text.join(" ") + CLOSE_STATEMENT; -} -function formatStatements(stmts, depth, indentStr) { - return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE); -} -function formatStatement(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - switch (node.type) { - case "Program": - return formatStatements(node.body, depth, indentStr); - case "If": - return formatIf(node, depth, indentStr); - case "For": - return formatFor(node, depth, indentStr); - case "Set": - return formatSet(node, depth, indentStr); - case "Macro": - return formatMacro(node, depth, indentStr); - case "Break": - return pad + createStatement("break"); - case "Continue": - return pad + createStatement("continue"); - case "CallStatement": - return formatCallStatement(node, depth, indentStr); - case "FilterStatement": - return formatFilterStatement(node, depth, indentStr); - case "Comment": - return pad + "{# " + node.value + " #}"; - default: - return pad + "{{- " + formatExpression(node) + " -}}"; - } -} -function formatIf(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - const clauses = []; - let current = node; - while (current) { - clauses.push({ test: current.test, body: current.body }); - if (current.alternate.length === 1 && current.alternate[0].type === "If") { - current = current.alternate[0]; - } else { - break; - } - } - let out = pad + createStatement("if", formatExpression(clauses[0].test)) + NEWLINE + formatStatements(clauses[0].body, depth + 1, indentStr); - for (let i = 1; i < clauses.length; ++i) { - out += NEWLINE + pad + createStatement("elif", formatExpression(clauses[i].test)) + NEWLINE + formatStatements(clauses[i].body, depth + 1, indentStr); - } - if (current && current.alternate.length > 0) { - out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(current.alternate, depth + 1, indentStr); - } - out += NEWLINE + pad + createStatement("endif"); - return out; -} -function formatFor(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - let formattedIterable = ""; - if (node.iterable.type === "SelectExpression") { - const n = node.iterable; - formattedIterable = `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`; - } else { - formattedIterable = formatExpression(node.iterable); - } - let out = pad + createStatement("for", formatExpression(node.loopvar), "in", formattedIterable) + NEWLINE + formatStatements(node.body, depth + 1, indentStr); - if (node.defaultBlock.length > 0) { - out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(node.defaultBlock, depth + 1, indentStr); - } - out += NEWLINE + pad + createStatement("endfor"); - return out; -} -function formatSet(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - const left = formatExpression(node.assignee); - const right = node.value ? formatExpression(node.value) : ""; - const value = pad + createStatement("set", `${left}${node.value ? " = " + right : ""}`); - if (node.body.length === 0) { - return value; - } - return value + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endset"); -} -function formatMacro(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - const args = node.args.map(formatExpression).join(", "); - return pad + createStatement("macro", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endmacro"); -} -function formatCallStatement(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - const params = node.callerArgs && node.callerArgs.length > 0 ? `(${node.callerArgs.map(formatExpression).join(", ")})` : ""; - const callExpr = formatExpression(node.call); - let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE; - out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE; - out += pad + createStatement("endcall"); - return out; -} -function formatFilterStatement(node, depth, indentStr) { - const pad = indentStr.repeat(depth); - const spec = node.filter.type === "Identifier" ? node.filter.value : formatExpression(node.filter); - let out = pad + createStatement("filter", spec) + NEWLINE; - out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE; - out += pad + createStatement("endfilter"); - return out; -} -function formatExpression(node, parentPrec = -1) { - switch (node.type) { - case "SpreadExpression": { - const n = node; - return `*${formatExpression(n.argument)}`; - } - case "Identifier": - return node.value; - case "IntegerLiteral": - return `${node.value}`; - case "FloatLiteral": - return `${node.value}`; - case "StringLiteral": - return JSON.stringify(node.value); - case "BinaryExpression": { - const n = node; - const thisPrecedence = getBinaryOperatorPrecedence(n); - const left = formatExpression(n.left, thisPrecedence); - const right = formatExpression(n.right, thisPrecedence + 1); - const expr = `${left} ${n.operator.value} ${right}`; - return thisPrecedence < parentPrec ? `(${expr})` : expr; - } - case "UnaryExpression": { - const n = node; - const val = n.operator.value + (n.operator.value === "not" ? " " : "") + formatExpression(n.argument, Infinity); - return val; - } - case "CallExpression": { - const n = node; - const args = n.args.map(formatExpression).join(", "); - return `${formatExpression(n.callee)}(${args})`; - } - case "MemberExpression": { - const n = node; - let obj = formatExpression(n.object); - if (![ - "Identifier", - "MemberExpression", - "CallExpression", - "StringLiteral", - "IntegerLiteral", - "FloatLiteral", - "ArrayLiteral", - "TupleLiteral", - "ObjectLiteral" - ].includes(n.object.type)) { - obj = `(${obj})`; - } - let prop = formatExpression(n.property); - if (!n.computed && n.property.type !== "Identifier") { - prop = `(${prop})`; - } - return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`; - } - case "FilterExpression": { - const n = node; - const operand = formatExpression(n.operand, Infinity); - if (n.filter.type === "CallExpression") { - return `${operand} | ${formatExpression(n.filter)}`; - } - return `${operand} | ${n.filter.value}`; - } - case "SelectExpression": { - const n = node; - return `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`; - } - case "TestExpression": { - const n = node; - return `${formatExpression(n.operand)} is${n.negate ? " not" : ""} ${n.test.value}`; - } - case "ArrayLiteral": - case "TupleLiteral": { - const elems = node.value.map(formatExpression); - const brackets = node.type === "ArrayLiteral" ? "[]" : "()"; - return `${brackets[0]}${elems.join(", ")}${brackets[1]}`; - } - case "ObjectLiteral": { - const entries = Array.from(node.value.entries()).map( - ([k, v]) => `${formatExpression(k)}: ${formatExpression(v)}` - ); - return `{${entries.join(", ")}}`; - } - case "SliceExpression": { - const n = node; - const s = n.start ? formatExpression(n.start) : ""; - const t = n.stop ? formatExpression(n.stop) : ""; - const st = n.step ? `:${formatExpression(n.step)}` : ""; - return `${s}:${t}${st}`; - } - case "KeywordArgumentExpression": { - const n = node; - return `${n.key.value}=${formatExpression(n.value)}`; - } - case "Ternary": { - const n = node; - const expr = `${formatExpression(n.trueExpr)} if ${formatExpression(n.condition, 0)} else ${formatExpression( - n.falseExpr - )}`; - return parentPrec > -1 ? `(${expr})` : expr; - } - default: - throw new Error(`Unknown expression type: ${node.type}`); - } -} - -// src/index.ts -var Template = class { - parsed; - /** - * @param {string} template The template string - */ - constructor(template) { - const tokens = tokenize(template, { - lstrip_blocks: true, - trim_blocks: true - }); - this.parsed = parse(tokens); - } - render(items) { - const env = new Environment(); - setupGlobals(env); - if (items) { - for (const [key, value] of Object.entries(items)) { - env.set(key, value); - } - } - const interpreter = new Interpreter(env); - const result = interpreter.run(this.parsed); - return result.value; - } - format(options) { - return format(this.parsed, options?.indent || " "); - } -}; - - - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js": -/*!******************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/backend-impl.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ registerBackend: () => (/* binding */ registerBackend), -/* harmony export */ resolveBackendAndExecutionProviders: () => (/* binding */ resolveBackendAndExecutionProviders) -/* harmony export */ }); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -const backends = new Map(); -const backendsSortedByPriority = []; -/** - * Register a backend. - * - * @param name - the name as a key to lookup as an execution provider. - * @param backend - the backend object. - * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority - * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default. - * - * @ignore - */ -const registerBackend = (name, backend, priority) => { - if (backend && typeof backend.init === 'function' && typeof backend.createInferenceSessionHandler === 'function') { - const currentBackend = backends.get(name); - if (currentBackend === undefined) { - backends.set(name, { backend, priority }); - } - else if (currentBackend.priority > priority) { - // same name is already registered with a higher priority. skip registeration. - return; - } - else if (currentBackend.priority === priority) { - if (currentBackend.backend !== backend) { - throw new Error(`cannot register backend "${name}" using priority ${priority}`); - } - } - if (priority >= 0) { - const i = backendsSortedByPriority.indexOf(name); - if (i !== -1) { - backendsSortedByPriority.splice(i, 1); - } - for (let i = 0; i < backendsSortedByPriority.length; i++) { - if (backends.get(backendsSortedByPriority[i]).priority <= priority) { - backendsSortedByPriority.splice(i, 0, name); - return; - } - } - backendsSortedByPriority.push(name); - } - return; - } - throw new TypeError('not a valid backend'); -}; -/** - * Try to resolve and initialize a backend. - * - * @param backendName - the name of the backend. - * @returns the backend instance if resolved and initialized successfully, or an error message if failed. - */ -const tryResolveAndInitializeBackend = async (backendName) => { - const backendInfo = backends.get(backendName); - if (!backendInfo) { - return 'backend not found.'; - } - if (backendInfo.initialized) { - return backendInfo.backend; - } - else if (backendInfo.aborted) { - return backendInfo.error; - } - else { - const isInitializing = !!backendInfo.initPromise; - try { - if (!isInitializing) { - backendInfo.initPromise = backendInfo.backend.init(backendName); - } - await backendInfo.initPromise; - backendInfo.initialized = true; - return backendInfo.backend; - } - catch (e) { - if (!isInitializing) { - backendInfo.error = `${e}`; - backendInfo.aborted = true; - } - return backendInfo.error; - } - finally { - delete backendInfo.initPromise; - } - } -}; -/** - * Resolve execution providers from the specific session options. - * - * @param options - the session options object. - * @returns a promise that resolves to a tuple of an initialized backend instance and a session options object with - * filtered EP list. - * - * @ignore - */ -const resolveBackendAndExecutionProviders = async (options) => { - // extract backend hints from session options - const eps = options.executionProviders || []; - const backendHints = eps.map((i) => (typeof i === 'string' ? i : i.name)); - const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints; - // try to resolve and initialize all requested backends - let backend; - const errors = []; - const availableBackendNames = new Set(); - for (const backendName of backendNames) { - const resolveResult = await tryResolveAndInitializeBackend(backendName); - if (typeof resolveResult === 'string') { - errors.push({ name: backendName, err: resolveResult }); - } - else { - if (!backend) { - backend = resolveResult; - } - if (backend === resolveResult) { - availableBackendNames.add(backendName); - } - } - } - // if no backend is available, throw error. - if (!backend) { - throw new Error(`no available backend found. ERR: ${errors.map((e) => `[${e.name}] ${e.err}`).join(', ')}`); - } - // for each explicitly requested backend, if it's not available, output warning message. - for (const { name, err } of errors) { - if (backendHints.includes(name)) { - // eslint-disable-next-line no-console - console.warn(`removing requested execution provider "${name}" from session options because it is not available: ${err}`); - } - } - const filteredEps = eps.filter((i) => availableBackendNames.has(typeof i === 'string' ? i : i.name)); - return [ - backend, - new Proxy(options, { - get: (target, prop) => { - if (prop === 'executionProviders') { - return filteredEps; - } - return Reflect.get(target, prop); - }, - }), - ]; -}; -//# sourceMappingURL=backend-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/backend.js": -/*!*************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/backend.js ***! - \*************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ registerBackend: () => (/* reexport safe */ _backend_impl_js__WEBPACK_IMPORTED_MODULE_0__.registerBackend) -/* harmony export */ }); -/* harmony import */ var _backend_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl.js */ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//# sourceMappingURL=backend.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/env-impl.js": -/*!**************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/env-impl.js ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ env: () => (/* binding */ env) -/* harmony export */ }); -/* harmony import */ var _version_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./version.js */ "./node_modules/onnxruntime-common/dist/esm/version.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -let logLevelValue = 'warning'; -const env = { - wasm: {}, - webgl: {}, - webgpu: {}, - versions: { common: _version_js__WEBPACK_IMPORTED_MODULE_0__.version }, - set logLevel(value) { - if (value === undefined) { - return; - } - if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) { - throw new Error(`Unsupported logging level: ${value}`); - } - logLevelValue = value; - }, - get logLevel() { - return logLevelValue; - }, -}; -// set property 'logLevel' so that they can be correctly transferred to worker by `postMessage()`. -Object.defineProperty(env, 'logLevel', { enumerable: true }); -//# sourceMappingURL=env-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/env.js": -/*!*********************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/env.js ***! - \*********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ env: () => (/* binding */ env) -/* harmony export */ }); -/* harmony import */ var _env_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env-impl.js */ "./node_modules/onnxruntime-common/dist/esm/env-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Represent a set of flags as a global singleton. - */ -const env = _env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env; -//# sourceMappingURL=env.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/index.js": -/*!***********************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/index.js ***! - \***********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ InferenceSession: () => (/* reexport safe */ _inference_session_js__WEBPACK_IMPORTED_MODULE_2__.InferenceSession), -/* harmony export */ TRACE: () => (/* reexport safe */ _trace_js__WEBPACK_IMPORTED_MODULE_6__.TRACE), -/* harmony export */ TRACE_FUNC_BEGIN: () => (/* reexport safe */ _trace_js__WEBPACK_IMPORTED_MODULE_6__.TRACE_FUNC_BEGIN), -/* harmony export */ TRACE_FUNC_END: () => (/* reexport safe */ _trace_js__WEBPACK_IMPORTED_MODULE_6__.TRACE_FUNC_END), -/* harmony export */ Tensor: () => (/* reexport safe */ _tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor), -/* harmony export */ env: () => (/* reexport safe */ _env_js__WEBPACK_IMPORTED_MODULE_1__.env), -/* harmony export */ registerBackend: () => (/* reexport safe */ _backend_js__WEBPACK_IMPORTED_MODULE_0__.registerBackend) -/* harmony export */ }); -/* harmony import */ var _backend_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend.js */ "./node_modules/onnxruntime-common/dist/esm/backend.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./env.js */ "./node_modules/onnxruntime-common/dist/esm/env.js"); -/* harmony import */ var _inference_session_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./inference-session.js */ "./node_modules/onnxruntime-common/dist/esm/inference-session.js"); -/* harmony import */ var _tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor.js */ "./node_modules/onnxruntime-common/dist/esm/tensor.js"); -/* harmony import */ var _tensor_conversion_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./tensor-conversion.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js"); -/* harmony import */ var _tensor_factory_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./tensor-factory.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-factory.js"); -/* harmony import */ var _trace_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./trace.js */ "./node_modules/onnxruntime-common/dist/esm/trace.js"); -/* harmony import */ var _onnx_model_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./onnx-model.js */ "./node_modules/onnxruntime-common/dist/esm/onnx-model.js"); -/* harmony import */ var _onnx_value_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./onnx-value.js */ "./node_modules/onnxruntime-common/dist/esm/onnx-value.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * # ONNX Runtime JavaScript API - * - * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages: - * - * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node) - * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web) - * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native) - * - * See also: - * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript/) - * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js) - * - * @packageDocumentation - */ - - - - - - - - - -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js": -/*!****************************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js ***! - \****************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ InferenceSession: () => (/* binding */ InferenceSession) -/* harmony export */ }); -/* harmony import */ var _backend_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl.js */ "./node_modules/onnxruntime-common/dist/esm/backend-impl.js"); -/* harmony import */ var _tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tensor.js */ "./node_modules/onnxruntime-common/dist/esm/tensor.js"); -/* harmony import */ var _trace_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./trace.js */ "./node_modules/onnxruntime-common/dist/esm/trace.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - - - -class InferenceSession { - constructor(handler) { - this.handler = handler; - } - async run(feeds, arg1, arg2) { - (0,_trace_js__WEBPACK_IMPORTED_MODULE_2__.TRACE_FUNC_BEGIN)(); - const fetches = {}; - let options = {}; - // check inputs - if (typeof feeds !== 'object' || feeds === null || feeds instanceof _tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor || Array.isArray(feeds)) { - throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); - } - let isFetchesEmpty = true; - // determine which override is being used - if (typeof arg1 === 'object') { - if (arg1 === null) { - throw new TypeError('Unexpected argument[1]: cannot be null.'); - } - if (arg1 instanceof _tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor) { - throw new TypeError("'fetches' cannot be a Tensor"); - } - if (Array.isArray(arg1)) { - if (arg1.length === 0) { - throw new TypeError("'fetches' cannot be an empty array."); - } - isFetchesEmpty = false; - // output names - for (const name of arg1) { - if (typeof name !== 'string') { - throw new TypeError("'fetches' must be a string array or an object."); - } - if (this.outputNames.indexOf(name) === -1) { - throw new RangeError(`'fetches' contains invalid output name: ${name}.`); - } - fetches[name] = null; - } - if (typeof arg2 === 'object' && arg2 !== null) { - options = arg2; - } - else if (typeof arg2 !== 'undefined') { - throw new TypeError("'options' must be an object."); - } - } - else { - // decide whether arg1 is fetches or options - // if any output name is present and its value is valid OnnxValue, we consider it fetches - let isFetches = false; - const arg1Keys = Object.getOwnPropertyNames(arg1); - for (const name of this.outputNames) { - if (arg1Keys.indexOf(name) !== -1) { - const v = arg1[name]; - if (v === null || v instanceof _tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor) { - isFetches = true; - isFetchesEmpty = false; - fetches[name] = v; - } - } - } - if (isFetches) { - if (typeof arg2 === 'object' && arg2 !== null) { - options = arg2; - } - else if (typeof arg2 !== 'undefined') { - throw new TypeError("'options' must be an object."); - } - } - else { - options = arg1; - } - } - } - else if (typeof arg1 !== 'undefined') { - throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); - } - // check if all inputs are in feed - for (const name of this.inputNames) { - if (typeof feeds[name] === 'undefined') { - throw new Error(`input '${name}' is missing in 'feeds'.`); - } - } - // if no fetches is specified, we use the full output names list - if (isFetchesEmpty) { - for (const name of this.outputNames) { - fetches[name] = null; - } - } - // feeds, fetches and options are prepared - const results = await this.handler.run(feeds, fetches, options); - const returnValue = {}; - for (const key in results) { - if (Object.hasOwnProperty.call(results, key)) { - const result = results[key]; - if (result instanceof _tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor) { - returnValue[key] = result; - } - else { - returnValue[key] = new _tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(result.type, result.data, result.dims); - } - } - } - (0,_trace_js__WEBPACK_IMPORTED_MODULE_2__.TRACE_FUNC_END)(); - return returnValue; - } - async release() { - return this.handler.dispose(); - } - static async create(arg0, arg1, arg2, arg3) { - (0,_trace_js__WEBPACK_IMPORTED_MODULE_2__.TRACE_FUNC_BEGIN)(); - // either load from a file or buffer - let filePathOrUint8Array; - let options = {}; - if (typeof arg0 === 'string') { - filePathOrUint8Array = arg0; - if (typeof arg1 === 'object' && arg1 !== null) { - options = arg1; - } - else if (typeof arg1 !== 'undefined') { - throw new TypeError("'options' must be an object."); - } - } - else if (arg0 instanceof Uint8Array) { - filePathOrUint8Array = arg0; - if (typeof arg1 === 'object' && arg1 !== null) { - options = arg1; - } - else if (typeof arg1 !== 'undefined') { - throw new TypeError("'options' must be an object."); - } - } - else if (arg0 instanceof ArrayBuffer || - (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) { - const buffer = arg0; - let byteOffset = 0; - let byteLength = arg0.byteLength; - if (typeof arg1 === 'object' && arg1 !== null) { - options = arg1; - } - else if (typeof arg1 === 'number') { - byteOffset = arg1; - if (!Number.isSafeInteger(byteOffset)) { - throw new RangeError("'byteOffset' must be an integer."); - } - if (byteOffset < 0 || byteOffset >= buffer.byteLength) { - throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`); - } - byteLength = arg0.byteLength - byteOffset; - if (typeof arg2 === 'number') { - byteLength = arg2; - if (!Number.isSafeInteger(byteLength)) { - throw new RangeError("'byteLength' must be an integer."); - } - if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) { - throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`); - } - if (typeof arg3 === 'object' && arg3 !== null) { - options = arg3; - } - else if (typeof arg3 !== 'undefined') { - throw new TypeError("'options' must be an object."); - } - } - else if (typeof arg2 !== 'undefined') { - throw new TypeError("'byteLength' must be a number."); - } - } - else if (typeof arg1 !== 'undefined') { - throw new TypeError("'options' must be an object."); - } - filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength); - } - else { - throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); - } - // resolve backend, update session options with validated EPs, and create session handler - const [backend, optionsWithValidatedEPs] = await (0,_backend_impl_js__WEBPACK_IMPORTED_MODULE_0__.resolveBackendAndExecutionProviders)(options); - const handler = await backend.createInferenceSessionHandler(filePathOrUint8Array, optionsWithValidatedEPs); - (0,_trace_js__WEBPACK_IMPORTED_MODULE_2__.TRACE_FUNC_END)(); - return new InferenceSession(handler); - } - startProfiling() { - this.handler.startProfiling(); - } - endProfiling() { - this.handler.endProfiling(); - } - get inputNames() { - return this.handler.inputNames; - } - get outputNames() { - return this.handler.outputNames; - } -} -//# sourceMappingURL=inference-session-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/inference-session.js": -/*!***********************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/inference-session.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ InferenceSession: () => (/* binding */ InferenceSession) -/* harmony export */ }); -/* harmony import */ var _inference_session_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./inference-session-impl.js */ "./node_modules/onnxruntime-common/dist/esm/inference-session-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// eslint-disable-next-line @typescript-eslint/naming-convention -const InferenceSession = _inference_session_impl_js__WEBPACK_IMPORTED_MODULE_0__.InferenceSession; -//# sourceMappingURL=inference-session.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/onnx-model.js": -/*!****************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/onnx-model.js ***! - \****************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//# sourceMappingURL=onnx-model.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/onnx-value.js": -/*!****************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/onnx-value.js ***! - \****************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//# sourceMappingURL=onnx-value.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js": -/*!****************************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js ***! - \****************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ tensorToDataURL: () => (/* binding */ tensorToDataURL), -/* harmony export */ tensorToImageData: () => (/* binding */ tensorToImageData) -/* harmony export */ }); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * implementation of Tensor.toDataURL() - */ -const tensorToDataURL = (tensor, options) => { - const canvas = typeof document !== 'undefined' ? document.createElement('canvas') : new OffscreenCanvas(1, 1); - canvas.width = tensor.dims[3]; - canvas.height = tensor.dims[2]; - const pixels2DContext = canvas.getContext('2d'); - if (pixels2DContext != null) { - // Default values for height and width & format - let width; - let height; - if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') { - width = tensor.dims[2]; - height = tensor.dims[3]; - } - else { - // Default layout is NCWH - width = tensor.dims[3]; - height = tensor.dims[2]; - } - const inputformat = options?.format !== undefined ? options.format : 'RGB'; - const norm = options?.norm; - let normMean; - let normBias; - if (norm === undefined || norm.mean === undefined) { - normMean = [255, 255, 255, 255]; - } - else { - if (typeof norm.mean === 'number') { - normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; - } - else { - normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0]; - if (norm.mean[3] !== undefined) { - normMean[3] = norm.mean[3]; - } - } - } - if (norm === undefined || norm.bias === undefined) { - normBias = [0, 0, 0, 0]; - } - else { - if (typeof norm.bias === 'number') { - normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; - } - else { - normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0]; - if (norm.bias[3] !== undefined) { - normBias[3] = norm.bias[3]; - } - } - } - const stride = height * width; - // Default pointer assignments - let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; - // Updating the pointer assignments based on the input image format - if (inputformat === 'RGBA') { - rTensorPointer = 0; - gTensorPointer = stride; - bTensorPointer = stride * 2; - aTensorPointer = stride * 3; - } - else if (inputformat === 'RGB') { - rTensorPointer = 0; - gTensorPointer = stride; - bTensorPointer = stride * 2; - } - else if (inputformat === 'RBG') { - rTensorPointer = 0; - bTensorPointer = stride; - gTensorPointer = stride * 2; - } - for (let i = 0; i < height; i++) { - for (let j = 0; j < width; j++) { - const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value - const G = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value - const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value - const A = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value - // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - pixels2DContext.fillStyle = 'rgba(' + R + ',' + G + ',' + B + ',' + A + ')'; - pixels2DContext.fillRect(j, i, 1, 1); - } - } - if ('toDataURL' in canvas) { - return canvas.toDataURL(); - } - else { - throw new Error('toDataURL is not supported'); - } - } - else { - throw new Error('Can not access image data'); - } -}; -/** - * implementation of Tensor.toImageData() - */ -const tensorToImageData = (tensor, options) => { - const pixels2DContext = typeof document !== 'undefined' - ? document.createElement('canvas').getContext('2d') - : new OffscreenCanvas(1, 1).getContext('2d'); - let image; - if (pixels2DContext != null) { - // Default values for height and width & format - let width; - let height; - let channels; - if (options?.tensorLayout !== undefined && options.tensorLayout === 'NHWC') { - width = tensor.dims[2]; - height = tensor.dims[1]; - channels = tensor.dims[3]; - } - else { - // Default layout is NCWH - width = tensor.dims[3]; - height = tensor.dims[2]; - channels = tensor.dims[1]; - } - const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB'; - const norm = options?.norm; - let normMean; - let normBias; - if (norm === undefined || norm.mean === undefined) { - normMean = [255, 255, 255, 255]; - } - else { - if (typeof norm.mean === 'number') { - normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; - } - else { - normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255]; - if (norm.mean[3] !== undefined) { - normMean[3] = norm.mean[3]; - } - } - } - if (norm === undefined || norm.bias === undefined) { - normBias = [0, 0, 0, 0]; - } - else { - if (typeof norm.bias === 'number') { - normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; - } - else { - normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0]; - if (norm.bias[3] !== undefined) { - normBias[3] = norm.bias[3]; - } - } - } - const stride = height * width; - if (options !== undefined) { - if ((options.format !== undefined && channels === 4 && options.format !== 'RGBA') || - (channels === 3 && options.format !== 'RGB' && options.format !== 'BGR')) { - throw new Error("Tensor format doesn't match input tensor dims"); - } - } - // Default pointer assignments - const step = 4; - let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; - let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; - // Updating the pointer assignments based on the input image format - if (inputformat === 'RGBA') { - rTensorPointer = 0; - gTensorPointer = stride; - bTensorPointer = stride * 2; - aTensorPointer = stride * 3; - } - else if (inputformat === 'RGB') { - rTensorPointer = 0; - gTensorPointer = stride; - bTensorPointer = stride * 2; - } - else if (inputformat === 'RBG') { - rTensorPointer = 0; - bTensorPointer = stride; - gTensorPointer = stride * 2; - } - image = pixels2DContext.createImageData(width, height); - for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) { - image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; // R value - image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; // G value - image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; // B value - image.data[aImagePointer] = - aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; // A value - } - } - else { - throw new Error('Can not access image data'); - } - return image; -}; -//# sourceMappingURL=tensor-conversion-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js": -/*!***********************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-conversion.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//# sourceMappingURL=tensor-conversion.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js": -/*!*************************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js ***! - \*************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ bufferToTensor: () => (/* binding */ bufferToTensor), -/* harmony export */ tensorFromGpuBuffer: () => (/* binding */ tensorFromGpuBuffer), -/* harmony export */ tensorFromImage: () => (/* binding */ tensorFromImage), -/* harmony export */ tensorFromMLTensor: () => (/* binding */ tensorFromMLTensor), -/* harmony export */ tensorFromPinnedBuffer: () => (/* binding */ tensorFromPinnedBuffer), -/* harmony export */ tensorFromTexture: () => (/* binding */ tensorFromTexture) -/* harmony export */ }); -/* harmony import */ var _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * Create a new tensor object from image object - * - * @param buffer - Extracted image buffer data - assuming RGBA format - * @param imageFormat - input image configuration - required configurations height, width, format - * @param tensorFormat - output tensor configuration - Default is RGB format - */ -const bufferToTensor = (buffer, options) => { - if (buffer === undefined) { - throw new Error('Image buffer must be defined'); - } - if (options.height === undefined || options.width === undefined) { - throw new Error('Image height and width must be defined'); - } - if (options.tensorLayout === 'NHWC') { - throw new Error('NHWC Tensor layout is not supported yet'); - } - const { height, width } = options; - const norm = options.norm ?? { mean: 255, bias: 0 }; - let normMean; - let normBias; - if (typeof norm.mean === 'number') { - normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; - } - else { - normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255]; - } - if (typeof norm.bias === 'number') { - normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; - } - else { - normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0]; - } - const inputformat = options.format !== undefined ? options.format : 'RGBA'; - // default value is RGBA since imagedata and HTMLImageElement uses it - const outputformat = options.tensorFormat !== undefined ? (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : 'RGB'; - const stride = height * width; - const float32Data = outputformat === 'RGBA' ? new Float32Array(stride * 4) : new Float32Array(stride * 3); - // Default pointer assignments - let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; - let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; - // Updating the pointer assignments based on the input image format - if (inputformat === 'RGB') { - step = 3; - rImagePointer = 0; - gImagePointer = 1; - bImagePointer = 2; - aImagePointer = -1; - } - // Updating the pointer assignments based on the output tensor format - if (outputformat === 'RGBA') { - aTensorPointer = stride * 3; - } - else if (outputformat === 'RBG') { - rTensorPointer = 0; - bTensorPointer = stride; - gTensorPointer = stride * 2; - } - else if (outputformat === 'BGR') { - bTensorPointer = 0; - gTensorPointer = stride; - rTensorPointer = stride * 2; - } - for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) { - float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0]; - float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1]; - float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2]; - if (aTensorPointer !== -1 && aImagePointer !== -1) { - float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3]; - } - } - // Float32Array -> ort.Tensor - const outputTensor = outputformat === 'RGBA' - ? new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor('float32', float32Data, [1, 4, height, width]) - : new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor('float32', float32Data, [1, 3, height, width]); - return outputTensor; -}; -/** - * implementation of Tensor.fromImage(). - */ -const tensorFromImage = async (image, options) => { - // checking the type of image object - const isHTMLImageEle = typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement; - const isImageDataEle = typeof ImageData !== 'undefined' && image instanceof ImageData; - const isImageBitmap = typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap; - const isString = typeof image === 'string'; - let data; - let bufferToTensorOptions = options ?? {}; - const createCanvas = () => { - if (typeof document !== 'undefined') { - return document.createElement('canvas'); - } - else if (typeof OffscreenCanvas !== 'undefined') { - return new OffscreenCanvas(1, 1); - } - else { - throw new Error('Canvas is not supported'); - } - }; - const createCanvasContext = (canvas) => { - if (typeof HTMLCanvasElement !== 'undefined' && canvas instanceof HTMLCanvasElement) { - return canvas.getContext('2d'); - } - else if (canvas instanceof OffscreenCanvas) { - return canvas.getContext('2d'); - } - else { - return null; - } - }; - // filling and checking image configuration options - if (isHTMLImageEle) { - // HTMLImageElement - image object - format is RGBA by default - const canvas = createCanvas(); - canvas.width = image.width; - canvas.height = image.height; - const pixels2DContext = createCanvasContext(canvas); - if (pixels2DContext != null) { - let height = image.height; - let width = image.width; - if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) { - height = options.resizedHeight; - width = options.resizedWidth; - } - if (options !== undefined) { - bufferToTensorOptions = options; - if (options.tensorFormat !== undefined) { - throw new Error('Image input config format must be RGBA for HTMLImageElement'); - } - else { - bufferToTensorOptions.tensorFormat = 'RGBA'; - } - bufferToTensorOptions.height = height; - bufferToTensorOptions.width = width; - } - else { - bufferToTensorOptions.tensorFormat = 'RGBA'; - bufferToTensorOptions.height = height; - bufferToTensorOptions.width = width; - } - pixels2DContext.drawImage(image, 0, 0); - data = pixels2DContext.getImageData(0, 0, width, height).data; - } - else { - throw new Error('Can not access image data'); - } - } - else if (isImageDataEle) { - let height; - let width; - if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) { - height = options.resizedHeight; - width = options.resizedWidth; - } - else { - height = image.height; - width = image.width; - } - if (options !== undefined) { - bufferToTensorOptions = options; - } - bufferToTensorOptions.format = 'RGBA'; - bufferToTensorOptions.height = height; - bufferToTensorOptions.width = width; - if (options !== undefined) { - const tempCanvas = createCanvas(); - tempCanvas.width = width; - tempCanvas.height = height; - const pixels2DContext = createCanvasContext(tempCanvas); - if (pixels2DContext != null) { - pixels2DContext.putImageData(image, 0, 0); - data = pixels2DContext.getImageData(0, 0, width, height).data; - } - else { - throw new Error('Can not access image data'); - } - } - else { - data = image.data; - } - } - else if (isImageBitmap) { - // ImageBitmap - image object - format must be provided by user - if (options === undefined) { - throw new Error('Please provide image config with format for Imagebitmap'); - } - const canvas = createCanvas(); - canvas.width = image.width; - canvas.height = image.height; - const pixels2DContext = createCanvasContext(canvas); - if (pixels2DContext != null) { - const height = image.height; - const width = image.width; - pixels2DContext.drawImage(image, 0, 0, width, height); - data = pixels2DContext.getImageData(0, 0, width, height).data; - bufferToTensorOptions.height = height; - bufferToTensorOptions.width = width; - return bufferToTensor(data, bufferToTensorOptions); - } - else { - throw new Error('Can not access image data'); - } - } - else if (isString) { - return new Promise((resolve, reject) => { - const canvas = createCanvas(); - const context = createCanvasContext(canvas); - if (!image || !context) { - return reject(); - } - const newImage = new Image(); - newImage.crossOrigin = 'Anonymous'; - newImage.src = image; - newImage.onload = () => { - canvas.width = newImage.width; - canvas.height = newImage.height; - context.drawImage(newImage, 0, 0, canvas.width, canvas.height); - const img = context.getImageData(0, 0, canvas.width, canvas.height); - bufferToTensorOptions.height = canvas.height; - bufferToTensorOptions.width = canvas.width; - resolve(bufferToTensor(img.data, bufferToTensorOptions)); - }; - }); - } - else { - throw new Error('Input data provided is not supported - aborted tensor creation'); - } - if (data !== undefined) { - return bufferToTensor(data, bufferToTensorOptions); - } - else { - throw new Error('Input data provided is not supported - aborted tensor creation'); - } -}; -/** - * implementation of Tensor.fromTexture(). - */ -const tensorFromTexture = (texture, options) => { - const { width, height, download, dispose } = options; - // Always assume RGBAF32. TODO: support different texture format - const dims = [1, height, width, 4]; - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ location: 'texture', type: 'float32', texture, dims, download, dispose }); -}; -/** - * implementation of Tensor.fromGpuBuffer(). - */ -const tensorFromGpuBuffer = (gpuBuffer, options) => { - const { dataType, dims, download, dispose } = options; - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ location: 'gpu-buffer', type: dataType ?? 'float32', gpuBuffer, dims, download, dispose }); -}; -/** - * implementation of Tensor.fromMLTensor(). - */ -const tensorFromMLTensor = (mlTensor, options) => { - const { dataType, dims, download, dispose } = options; - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ location: 'ml-tensor', type: dataType ?? 'float32', mlTensor, dims, download, dispose }); -}; -/** - * implementation of Tensor.fromPinnedBuffer(). - */ -const tensorFromPinnedBuffer = (type, buffer, dims) => new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ location: 'cpu-pinned', type, data: buffer, dims: dims ?? [buffer.length] }); -//# sourceMappingURL=tensor-factory-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-factory.js": -/*!********************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-factory.js ***! - \********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -//# sourceMappingURL=tensor-factory.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js": -/*!******************************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP: () => (/* binding */ NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP), -/* harmony export */ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP: () => (/* binding */ NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP), -/* harmony export */ checkTypedArray: () => (/* binding */ checkTypedArray) -/* harmony export */ }); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap. -const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([ - ['float32', Float32Array], - ['uint8', Uint8Array], - ['int8', Int8Array], - ['uint16', Uint16Array], - ['int16', Int16Array], - ['int32', Int32Array], - ['bool', Uint8Array], - ['float64', Float64Array], - ['uint32', Uint32Array], - ['int4', Uint8Array], - ['uint4', Uint8Array], -]); -// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap. -const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([ - [Float32Array, 'float32'], - [Uint8Array, 'uint8'], - [Int8Array, 'int8'], - [Uint16Array, 'uint16'], - [Int16Array, 'int16'], - [Int32Array, 'int32'], - [Float64Array, 'float64'], - [Uint32Array, 'uint32'], -]); -// the following code allows delaying execution of BigInt/Float16Array checking. This allows lazy initialization for -// NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP and NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP, which allows BigInt/Float16Array -// polyfill if available. -let isTypedArrayChecked = false; -const checkTypedArray = () => { - if (!isTypedArrayChecked) { - isTypedArrayChecked = true; - const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && BigInt64Array.from; - const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && BigUint64Array.from; - // eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any - const Float16Array = globalThis.Float16Array; - const isFloat16ArrayAvailable = typeof Float16Array !== 'undefined' && Float16Array.from; - if (isBigInt64ArrayAvailable) { - NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array); - NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64'); - } - if (isBigUint64ArrayAvailable) { - NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array); - NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64'); - } - if (isFloat16ArrayAvailable) { - NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Float16Array); - NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array, 'float16'); - } - else { - // if Float16Array is not available, use 'Uint16Array' to store the data. - NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('float16', Uint16Array); - } - } -}; -//# sourceMappingURL=tensor-impl-type-mapping.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js": -/*!*****************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-impl.js ***! - \*****************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Tensor: () => (/* binding */ Tensor) -/* harmony export */ }); -/* harmony import */ var _tensor_conversion_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-conversion-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js"); -/* harmony import */ var _tensor_factory_impl_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tensor-factory-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js"); -/* harmony import */ var _tensor_impl_type_mapping_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./tensor-impl-type-mapping.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js"); -/* harmony import */ var _tensor_utils_impl_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor-utils-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - - - - -/** - * the implementation of Tensor interface. - * - * @ignore - */ -class Tensor { - /** - * implementation. - */ - constructor(arg0, arg1, arg2) { - // perform one-time check for BigInt/Float16Array support - (0,_tensor_impl_type_mapping_js__WEBPACK_IMPORTED_MODULE_2__.checkTypedArray)(); - let type; - let dims; - if (typeof arg0 === 'object' && 'location' in arg0) { - // - // constructing tensor from specific location - // - this.dataLocation = arg0.location; - type = arg0.type; - dims = arg0.dims; - switch (arg0.location) { - case 'cpu-pinned': { - const expectedTypedArrayConstructor = _tensor_impl_type_mapping_js__WEBPACK_IMPORTED_MODULE_2__.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type); - if (!expectedTypedArrayConstructor) { - throw new TypeError(`unsupported type "${type}" to create tensor from pinned buffer`); - } - if (!(arg0.data instanceof expectedTypedArrayConstructor)) { - throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`); - } - this.cpuData = arg0.data; - break; - } - case 'texture': { - if (type !== 'float32') { - throw new TypeError(`unsupported type "${type}" to create tensor from texture`); - } - this.gpuTextureData = arg0.texture; - this.downloader = arg0.download; - this.disposer = arg0.dispose; - break; - } - case 'gpu-buffer': { - if (type !== 'float32' && - type !== 'float16' && - type !== 'int32' && - type !== 'int64' && - type !== 'uint32' && - type !== 'uint8' && - type !== 'bool' && - type !== 'uint4' && - type !== 'int4') { - throw new TypeError(`unsupported type "${type}" to create tensor from gpu buffer`); - } - this.gpuBufferData = arg0.gpuBuffer; - this.downloader = arg0.download; - this.disposer = arg0.dispose; - break; - } - case 'ml-tensor': { - if (type !== 'float32' && - type !== 'float16' && - type !== 'int32' && - type !== 'int64' && - type !== 'uint32' && - type !== 'uint64' && - type !== 'int8' && - type !== 'uint8' && - type !== 'bool' && - type !== 'uint4' && - type !== 'int4') { - throw new TypeError(`unsupported type "${type}" to create tensor from MLTensor`); - } - this.mlTensorData = arg0.mlTensor; - this.downloader = arg0.download; - this.disposer = arg0.dispose; - break; - } - default: - throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); - } - } - else { - // - // constructing tensor of location 'cpu' - // - let data; - let maybeDims; - // check whether arg0 is type or data - if (typeof arg0 === 'string') { - // - // Override: constructor(type, data, ...) - // - type = arg0; - maybeDims = arg2; - if (arg0 === 'string') { - // string tensor - if (!Array.isArray(arg1)) { - throw new TypeError("A string tensor's data must be a string array."); - } - // we don't check whether every element in the array is string; this is too slow. we assume it's correct and - // error will be populated at inference - data = arg1; - } - else { - // numeric tensor - const typedArrayConstructor = _tensor_impl_type_mapping_js__WEBPACK_IMPORTED_MODULE_2__.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0); - if (typedArrayConstructor === undefined) { - throw new TypeError(`Unsupported tensor type: ${arg0}.`); - } - if (Array.isArray(arg1)) { - if ((arg0 === 'float16' && typedArrayConstructor === Uint16Array) || arg0 === 'uint4' || arg0 === 'int4') { - // - 'float16': - // When no Float16Array polyfill is used, we cannot create 'float16' tensor from number array. - // - // Throw error here because when user try to use number array as data, - // e.g. new Tensor('float16', [1, 2, 3, 4], dims)), it will actually call - // Uint16Array.from(arg1) which generates wrong data. - // - // - 'uint4' and 'int4': - // Uint8Array.from(arg1) will generate wrong data for 'uint4' and 'int4' tensor. - // - throw new TypeError(`Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`); - } - else if (arg0 === 'uint64' || arg0 === 'int64') { - // use 'as any' here because: - // 1. TypeScript's check on type of 'Array.isArray()' does not work with readonly arrays. - // see https://github.com/microsoft/TypeScript/issues/17002 - // 2. TypeScript's check on union type of '(BigInt64ArrayConstructor|BigUint64ArrayConstructor).from()' - // does not accept parameter mapFn. - // 3. parameters of 'SupportedTypedArrayConstructors.from()' does not match the requirement of the union - // type. - // assume 'arg1' is of type "readonly number[]|readonly bigint[]" here. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data = typedArrayConstructor.from(arg1, BigInt); - } - else { - // assume 'arg1' is of type "readonly number[]" here. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data = typedArrayConstructor.from(arg1); - } - } - else if (arg1 instanceof typedArrayConstructor) { - data = arg1; - } - else if (arg1 instanceof Uint8ClampedArray) { - if (arg0 === 'uint8') { - data = Uint8Array.from(arg1); - } - else { - throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`); - } - } - else if (arg0 === 'float16' && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) { - // when Float16Array is available and data is of type Uint16Array. - // We allow Uint16Array to be passed in as data for 'float16' tensor until Float16Array is generally - // supported in JavaScript environment. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data = new globalThis.Float16Array(arg1.buffer, arg1.byteOffset, arg1.length); - } - else { - throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`); - } - } - } - else { - // - // Override: constructor(data, ...) - // - maybeDims = arg1; - if (Array.isArray(arg0)) { - // only boolean[] and string[] is supported - if (arg0.length === 0) { - throw new TypeError('Tensor type cannot be inferred from an empty array.'); - } - const firstElementType = typeof arg0[0]; - if (firstElementType === 'string') { - type = 'string'; - data = arg0; - } - else if (firstElementType === 'boolean') { - type = 'bool'; - // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is - // wrong type. We use 'as any' to make it happy. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - data = Uint8Array.from(arg0); - } - else { - throw new TypeError(`Invalid element type of data array: ${firstElementType}.`); - } - } - else if (arg0 instanceof Uint8ClampedArray) { - type = 'uint8'; - data = Uint8Array.from(arg0); - } - else { - // get tensor type from TypedArray - const mappedType = _tensor_impl_type_mapping_js__WEBPACK_IMPORTED_MODULE_2__.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor); - if (mappedType === undefined) { - throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`); - } - type = mappedType; - data = arg0; - } - } - // type and data is processed, now processing dims - if (maybeDims === undefined) { - // assume 1-D tensor if dims omitted - maybeDims = [data.length]; - } - else if (!Array.isArray(maybeDims)) { - throw new TypeError("A tensor's dims must be a number array"); - } - dims = maybeDims; - this.cpuData = data; - this.dataLocation = 'cpu'; - } - // perform check on dims - const size = (0,_tensor_utils_impl_js__WEBPACK_IMPORTED_MODULE_3__.calculateSize)(dims); - // if data is on CPU, check whether data length matches tensor size - if (this.cpuData && size !== this.cpuData.length) { - if ((type === 'uint4' || type === 'int4') && Math.ceil(size / 2) === this.cpuData.length) { - // for (u)int4, the data length is half of the tensor size. So we check this special case when size is odd. - } - else { - throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`); - } - } - this.type = type; - this.dims = dims; - this.size = size; - } - // #endregion - // #region factory - static async fromImage(image, options) { - return (0,_tensor_factory_impl_js__WEBPACK_IMPORTED_MODULE_1__.tensorFromImage)(image, options); - } - static fromTexture(texture, options) { - return (0,_tensor_factory_impl_js__WEBPACK_IMPORTED_MODULE_1__.tensorFromTexture)(texture, options); - } - static fromGpuBuffer(gpuBuffer, options) { - return (0,_tensor_factory_impl_js__WEBPACK_IMPORTED_MODULE_1__.tensorFromGpuBuffer)(gpuBuffer, options); - } - static fromMLTensor(mlTensor, options) { - return (0,_tensor_factory_impl_js__WEBPACK_IMPORTED_MODULE_1__.tensorFromMLTensor)(mlTensor, options); - } - static fromPinnedBuffer(type, buffer, dims) { - return (0,_tensor_factory_impl_js__WEBPACK_IMPORTED_MODULE_1__.tensorFromPinnedBuffer)(type, buffer, dims); - } - // #endregion - // #region conversions - toDataURL(options) { - return (0,_tensor_conversion_impl_js__WEBPACK_IMPORTED_MODULE_0__.tensorToDataURL)(this, options); - } - toImageData(options) { - return (0,_tensor_conversion_impl_js__WEBPACK_IMPORTED_MODULE_0__.tensorToImageData)(this, options); - } - // #endregion - // #region properties - get data() { - this.ensureValid(); - if (!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() { - this.ensureValid(); - if (!this.gpuTextureData) { - throw new Error('The data is not stored as a WebGL texture.'); - } - return this.gpuTextureData; - } - get gpuBuffer() { - this.ensureValid(); - if (!this.gpuBufferData) { - throw new Error('The data is not stored as a WebGPU buffer.'); - } - return this.gpuBufferData; - } - get mlTensor() { - this.ensureValid(); - if (!this.mlTensorData) { - throw new Error('The data is not stored as a WebNN MLTensor.'); - } - return this.mlTensorData; - } - // #endregion - // #region methods - async getData(releaseData) { - this.ensureValid(); - switch (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 = true; - const data = await this.downloader(); - this.downloader = undefined; - this.dataLocation = 'cpu'; - this.cpuData = data; - if (releaseData && this.disposer) { - this.disposer(); - this.disposer = undefined; - } - return data; - } - finally { - this.isDownloading = false; - } - } - default: - throw new Error(`cannot get data from location: ${this.dataLocation}`); - } - } - dispose() { - if (this.isDownloading) { - throw new Error('The current tensor is being downloaded.'); - } - if (this.disposer) { - this.disposer(); - this.disposer = undefined; - } - this.cpuData = undefined; - this.gpuTextureData = undefined; - this.gpuBufferData = undefined; - this.mlTensorData = undefined; - this.downloader = undefined; - this.isDownloading = undefined; - this.dataLocation = 'none'; - } - // #endregion - // #region tensor utilities - ensureValid() { - if (this.dataLocation === 'none') { - throw new Error('The tensor is disposed.'); - } - } - reshape(dims) { - this.ensureValid(); - if (this.downloader || this.disposer) { - throw new Error('Cannot reshape a tensor that owns GPU resource.'); - } - return (0,_tensor_utils_impl_js__WEBPACK_IMPORTED_MODULE_3__.tensorReshape)(this, dims); - } -} -//# sourceMappingURL=tensor-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js": -/*!***********************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ calculateSize: () => (/* binding */ calculateSize), -/* harmony export */ tensorReshape: () => (/* binding */ tensorReshape) -/* harmony export */ }); -/* harmony import */ var _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * calculate size from dims. - * - * @param dims the dims array. May be an illegal input. - */ -const calculateSize = (dims) => { - let size = 1; - for (let i = 0; i < dims.length; i++) { - const dim = dims[i]; - if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) { - throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`); - } - if (dim < 0) { - throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`); - } - size *= dim; - } - return size; -}; -/** - * implementation of Tensor.reshape() - */ -const tensorReshape = (tensor, dims) => { - switch (tensor.location) { - case 'cpu': - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor(tensor.type, tensor.data, dims); - case 'cpu-pinned': - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ - location: 'cpu-pinned', - data: tensor.data, - type: tensor.type, - dims, - }); - case 'texture': - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ - location: 'texture', - texture: tensor.texture, - type: tensor.type, - dims, - }); - case 'gpu-buffer': - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ - location: 'gpu-buffer', - gpuBuffer: tensor.gpuBuffer, - type: tensor.type, - dims, - }); - case 'ml-tensor': - return new _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor({ - location: 'ml-tensor', - mlTensor: tensor.mlTensor, - type: tensor.type, - dims, - }); - default: - throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`); - } -}; -//# sourceMappingURL=tensor-utils-impl.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/tensor.js": -/*!************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/tensor.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Tensor: () => (/* binding */ Tensor) -/* harmony export */ }); -/* harmony import */ var _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl.js */ "./node_modules/onnxruntime-common/dist/esm/tensor-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// eslint-disable-next-line @typescript-eslint/naming-convention -const Tensor = _tensor_impl_js__WEBPACK_IMPORTED_MODULE_0__.Tensor; -//# sourceMappingURL=tensor.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/trace.js": -/*!***********************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/trace.js ***! - \***********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ TRACE: () => (/* binding */ TRACE), -/* harmony export */ TRACE_FUNC_BEGIN: () => (/* binding */ TRACE_FUNC_BEGIN), -/* harmony export */ TRACE_FUNC_END: () => (/* binding */ TRACE_FUNC_END) -/* harmony export */ }); -/* harmony import */ var _env_impl_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env-impl.js */ "./node_modules/onnxruntime-common/dist/esm/env-impl.js"); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -/** - * @ignore - */ -const TRACE = (deviceType, label) => { - if (typeof _env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.trace === 'undefined' ? !_env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.wasm.trace : !_env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.trace) { - return; - } - // eslint-disable-next-line no-console - console.timeStamp(`${deviceType}::ORT::${label}`); -}; -const TRACE_FUNC = (msg, extraMsg) => { - const stack = new Error().stack?.split(/\r\n|\r|\n/g) || []; - let hasTraceFunc = false; - for (let i = 0; i < stack.length; i++) { - if (hasTraceFunc && !stack[i].includes('TRACE_FUNC')) { - let label = `FUNC_${msg}::${stack[i].trim().split(' ')[1]}`; - if (extraMsg) { - label += `::${extraMsg}`; - } - TRACE('CPU', label); - return; - } - if (stack[i].includes('TRACE_FUNC')) { - hasTraceFunc = true; - } - } -}; -/** - * @ignore - */ -const TRACE_FUNC_BEGIN = (extraMsg) => { - if (typeof _env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.trace === 'undefined' ? !_env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.wasm.trace : !_env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.trace) { - return; - } - TRACE_FUNC('BEGIN', extraMsg); -}; -/** - * @ignore - */ -const TRACE_FUNC_END = (extraMsg) => { - if (typeof _env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.trace === 'undefined' ? !_env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.wasm.trace : !_env_impl_js__WEBPACK_IMPORTED_MODULE_0__.env.trace) { - return; - } - TRACE_FUNC('END', extraMsg); -}; -//# sourceMappingURL=trace.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-common/dist/esm/version.js": -/*!*************************************************************!*\ - !*** ./node_modules/onnxruntime-common/dist/esm/version.js ***! - \*************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ version: () => (/* binding */ version) -/* harmony export */ }); -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -// This file is generated by /js/scripts/update-version.ts -// Do not modify file content manually. -const version = '1.21.0'; -//# sourceMappingURL=version.js.map - -/***/ }), - -/***/ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96": -/*!**************************************************************!*\ - !*** ./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ InferenceSession: () => (/* binding */ Gp), -/* harmony export */ TRACE: () => (/* binding */ gr), -/* harmony export */ TRACE_FUNC_BEGIN: () => (/* binding */ Re), -/* harmony export */ TRACE_FUNC_END: () => (/* binding */ Oe), -/* harmony export */ Tensor: () => (/* binding */ Ge), -/* harmony export */ "default": () => (/* binding */ IS), -/* harmony export */ env: () => (/* binding */ ge), -/* harmony export */ registerBackend: () => (/* binding */ $t) -/* harmony export */ }); -/*! - * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -var zn=Object.defineProperty;var Up=Object.getOwnPropertyDescriptor;var Np=Object.getOwnPropertyNames;var Vp=Object.prototype.hasOwnProperty;var On=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var U=(e,t)=>()=>(e&&(t=e(e=0)),t);var Dt=(e,t)=>{for(var r in t)zn(e,r,{get:t[r],enumerable:!0})},Wp=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Np(t))!Vp.call(e,o)&&o!==r&&zn(e,o,{get:()=>t[o],enumerable:!(n=Up(t,o))||n.enumerable});return e};var Ft=e=>Wp(zn({},"__esModule",{value:!0}),e);var fr,vt,$t,Lp,Fi,Bn=U(()=>{"use strict";fr=new Map,vt=[],$t=(e,t,r)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=fr.get(e);if(n===void 0)fr.set(e,{backend:t,priority:r});else{if(n.priority>r)return;if(n.priority===r&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${r}`)}if(r>=0){let o=vt.indexOf(e);o!==-1&&vt.splice(o,1);for(let i=0;i{let t=fr.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let r=!!t.initPromise;try{return r||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return r||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},Fi=async e=>{let t=e.executionProviders||[],r=t.map(d=>typeof d=="string"?d:d.name),n=r.length===0?vt:r,o,i=[],a=new Set;for(let d of n){let c=await Lp(d);typeof c=="string"?i.push({name:d,err:c}):(o||(o=c),o===c&&a.add(d))}if(!o)throw new Error(`no available backend found. ERR: ${i.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:c}of i)r.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${c}`);let u=t.filter(d=>a.has(typeof d=="string"?d:d.name));return[o,new Proxy(e,{get:(d,c)=>c==="executionProviders"?u:Reflect.get(d,c)})]}});var qi=U(()=>{"use strict";Bn()});var ji,Ki=U(()=>{"use strict";ji="1.22.0-dev.20250409-89f8206ba4"});var Zi,Me,Dn=U(()=>{"use strict";Ki();Zi="warning",Me={wasm:{},webgl:{},webgpu:{},versions:{common:ji},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}`);Zi=e}},get logLevel(){return Zi}};Object.defineProperty(Me,"logLevel",{enumerable:!0})});var ge,Qi=U(()=>{"use strict";Dn();ge=Me});var Yi,Xi,Ji=U(()=>{"use strict";Yi=(e,t)=>{let r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=e.dims[3],r.height=e.dims[2];let n=r.getContext("2d");if(n!=null){let o,i;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[3]):(o=e.dims[3],i=e.dims[2]);let a=t?.format!==void 0?t.format:"RGB",u=t?.norm,d,c;u===void 0||u.mean===void 0?d=[255,255,255,255]:typeof u.mean=="number"?d=[u.mean,u.mean,u.mean,u.mean]:(d=[u.mean[0],u.mean[1],u.mean[2],0],u.mean[3]!==void 0&&(d[3]=u.mean[3])),u===void 0||u.bias===void 0?c=[0,0,0,0]:typeof u.bias=="number"?c=[u.bias,u.bias,u.bias,u.bias]:(c=[u.bias[0],u.bias[1],u.bias[2],0],u.bias[3]!==void 0&&(c[3]=u.bias[3]));let p=i*o,m=0,f=p,b=p*2,g=-1;a==="RGBA"?(m=0,f=p,b=p*2,g=p*3):a==="RGB"?(m=0,f=p,b=p*2):a==="RBG"&&(m=0,b=p,f=p*2);for(let _=0;_{let r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(r!=null){let o,i,a;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(o=e.dims[2],i=e.dims[1],a=e.dims[3]):(o=e.dims[3],i=e.dims[2],a=e.dims[1]);let u=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t?.norm,c,p;d===void 0||d.mean===void 0?c=[255,255,255,255]:typeof d.mean=="number"?c=[d.mean,d.mean,d.mean,d.mean]:(c=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(c[3]=d.mean[3])),d===void 0||d.bias===void 0?p=[0,0,0,0]:typeof d.bias=="number"?p=[d.bias,d.bias,d.bias,d.bias]:(p=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(p[3]=d.bias[3]));let m=i*o;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let f=4,b=0,g=1,_=2,S=3,$=0,v=m,x=m*2,T=-1;u==="RGBA"?($=0,v=m,x=m*2,T=m*3):u==="RGB"?($=0,v=m,x=m*2):u==="RBG"&&($=0,x=m,v=m*2),n=r.createImageData(o,i);for(let E=0;E{"use strict";hr();Mn=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:r,width:n}=t,o=t.norm??{mean:255,bias:0},i,a;typeof o.mean=="number"?i=[o.mean,o.mean,o.mean,o.mean]:i=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?a=[o.bias,o.bias,o.bias,o.bias]:a=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let u=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",c=r*n,p=d==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),m=4,f=0,b=1,g=2,_=3,S=0,$=c,v=c*2,x=-1;u==="RGB"&&(m=3,f=0,b=1,g=2,_=-1),d==="RGBA"?x=c*3:d==="RBG"?(S=0,v=c,$=c*2):d==="BGR"&&(v=0,$=c,S=c*2);for(let E=0;E{let r=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,i=typeof e=="string",a,u=t??{},d=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(r){let p=d();p.width=e.width,p.height=e.height;let m=c(p);if(m!=null){let f=e.height,b=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(f=t.resizedHeight,b=t.resizedWidth),t!==void 0){if(u=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");u.tensorFormat="RGBA",u.height=f,u.width=b}else u.tensorFormat="RGBA",u.height=f,u.width=b;m.drawImage(e,0,0),a=m.getImageData(0,0,b,f).data}else throw new Error("Can not access image data")}else if(n){let p,m;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(p=t.resizedHeight,m=t.resizedWidth):(p=e.height,m=e.width),t!==void 0&&(u=t),u.format="RGBA",u.height=p,u.width=m,t!==void 0){let f=d();f.width=m,f.height=p;let b=c(f);if(b!=null)b.putImageData(e,0,0),a=b.getImageData(0,0,m,p).data;else throw new Error("Can not access image data")}else a=e.data}else if(o){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=d();p.width=e.width,p.height=e.height;let m=c(p);if(m!=null){let f=e.height,b=e.width;return m.drawImage(e,0,0,b,f),a=m.getImageData(0,0,b,f).data,u.height=f,u.width=b,Mn(a,u)}else throw new Error("Can not access image data")}else{if(i)return new Promise((p,m)=>{let f=d(),b=c(f);if(!e||!b)return m();let g=new Image;g.crossOrigin="Anonymous",g.src=e,g.onload=()=>{f.width=g.width,f.height=g.height,b.drawImage(g,0,0,f.width,f.height);let _=b.getImageData(0,0,f.width,f.height);u.height=f.height,u.width=f.width,p(Mn(_.data,u))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Mn(a,u);throw new Error("Input data provided is not supported - aborted tensor creation")},ta=(e,t)=>{let{width:r,height:n,download:o,dispose:i}=t,a=[1,n,r,4];return new Pe({location:"texture",type:"float32",texture:e,dims:a,download:o,dispose:i})},ra=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Pe({location:"gpu-buffer",type:r??"float32",gpuBuffer:e,dims:n,download:o,dispose:i})},na=(e,t)=>{let{dataType:r,dims:n,download:o,dispose:i}=t;return new Pe({location:"ml-tensor",type:r??"float32",mlTensor:e,dims:n,download:o,dispose:i})},oa=(e,t,r)=>new Pe({location:"cpu-pinned",type:e,data:t,dims:r??[t.length]})});var xt,qt,aa,sa,ua=U(()=>{"use strict";xt=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),qt=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),aa=!1,sa=()=>{if(!aa){aa=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,n=typeof r<"u"&&r.from;e&&(xt.set("int64",BigInt64Array),qt.set(BigInt64Array,"int64")),t&&(xt.set("uint64",BigUint64Array),qt.set(BigUint64Array,"uint64")),n?(xt.set("float16",r),qt.set(r,"float16")):xt.set("float16",Uint16Array)}}});var da,la,ca=U(()=>{"use strict";hr();da=e=>{let t=1;for(let r=0;r{switch(e.location){case"cpu":return new Pe(e.type,e.data,t);case"cpu-pinned":return new Pe({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Pe({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Pe({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Pe({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}});var Pe,hr=U(()=>{"use strict";Ji();ia();ua();ca();Pe=class{constructor(t,r,n){sa();let o,i;if(typeof t=="object"&&"location"in t)switch(this.dataLocation=t.location,o=t.type,i=t.dims,t.location){case"cpu-pinned":{let u=xt.get(o);if(!u)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(t.data instanceof u))throw new TypeError(`buffer should be of type ${u.name}`);this.cpuData=t.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=t.texture,this.downloader=t.download,this.disposer=t.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=t.gpuBuffer,this.downloader=t.download,this.disposer=t.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=t.mlTensor,this.downloader=t.download,this.disposer=t.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let u,d;if(typeof t=="string")if(o=t,d=n,t==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");u=r}else{let c=xt.get(t);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${t}.`);if(Array.isArray(r)){if(t==="float16"&&c===Uint16Array||t==="uint4"||t==="int4")throw new TypeError(`Creating a ${t} tensor from number array is not supported. Please use ${c.name} as data.`);t==="uint64"||t==="int64"?u=c.from(r,BigInt):u=c.from(r)}else if(r instanceof c)u=r;else if(r instanceof Uint8ClampedArray)if(t==="uint8")u=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(t==="float16"&&r instanceof Uint16Array&&c!==Uint16Array)u=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(d=r,Array.isArray(t)){if(t.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let c=typeof t[0];if(c==="string")o="string",u=t;else if(c==="boolean")o="bool",u=Uint8Array.from(t);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(t instanceof Uint8ClampedArray)o="uint8",u=Uint8Array.from(t);else{let c=qt.get(t.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${t.constructor}.`);o=c,u=t}if(d===void 0)d=[u.length];else if(!Array.isArray(d))throw new TypeError("A tensor's dims must be a number array");i=d,this.cpuData=u,this.dataLocation="cpu"}let a=da(i);if(this.cpuData&&a!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=i,this.size=a}static async fromImage(t,r){return ea(t,r)}static fromTexture(t,r){return ta(t,r)}static fromGpuBuffer(t,r){return ra(t,r)}static fromMLTensor(t,r){return na(t,r)}static fromPinnedBuffer(t,r,n){return oa(t,r,n)}toDataURL(t){return Yi(this,t)}toImageData(t){return Xi(this,t)}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(t){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,t&&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(t){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return la(this,t)}}});var Ge,Rn=U(()=>{"use strict";hr();Ge=Pe});var gr,pa,Re,Oe,Un=U(()=>{"use strict";Dn();gr=(e,t)=>{(typeof Me.trace>"u"?!Me.wasm.trace:!Me.trace)||console.timeStamp(`${e}::ORT::${t}`)},pa=(e,t)=>{let r=new Error().stack?.split(/\r\n|\r|\n/g)||[],n=!1;for(let o=0;o{(typeof Me.trace>"u"?!Me.wasm.trace:!Me.trace)||pa("BEGIN",e)},Oe=e=>{(typeof Me.trace>"u"?!Me.wasm.trace:!Me.trace)||pa("END",e)}});var br,ma=U(()=>{"use strict";Bn();Rn();Un();br=class e{constructor(t){this.handler=t}async run(t,r,n){Re();let o={},i={};if(typeof t!="object"||t===null||t instanceof Ge||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof Ge)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let c of r){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(r);for(let m of this.outputNames)if(p.indexOf(m)!==-1){let f=r[m];(f===null||f instanceof Ge)&&(c=!0,a=!1,o[m]=f)}if(c){if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else i=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof t[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(a)for(let c of this.outputNames)o[c]=null;let u=await this.handler.run(t,o,i),d={};for(let c in u)if(Object.hasOwnProperty.call(u,c)){let p=u[c];p instanceof Ge?d[c]=p:d[c]=new Ge(p.type,p.data,p.dims)}return Oe(),d}async release(){return this.handler.dispose()}static async create(t,r,n,o){Re();let i,a={};if(typeof t=="string"){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(i=t,typeof r=="object"&&r!==null)a=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let p=t,m=0,f=t.byteLength;if(typeof r=="object"&&r!==null)a=r;else if(typeof r=="number"){if(m=r,!Number.isSafeInteger(m))throw new RangeError("'byteOffset' must be an integer.");if(m<0||m>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(f=t.byteLength-m,typeof n=="number"){if(f=n,!Number.isSafeInteger(f))throw new RangeError("'byteLength' must be an integer.");if(f<=0||m+f>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-m}].`);if(typeof o=="object"&&o!==null)a=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(p,m,f)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[u,d]=await Fi(a),c=await u.createInferenceSessionHandler(i,d);return Oe(),new e(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}});var Gp,fa=U(()=>{"use strict";ma();Gp=br});var ha=U(()=>{"use strict"});var ga=U(()=>{"use strict"});var ba=U(()=>{"use strict"});var ya=U(()=>{"use strict"});var Nn={};Dt(Nn,{InferenceSession:()=>Gp,TRACE:()=>gr,TRACE_FUNC_BEGIN:()=>Re,TRACE_FUNC_END:()=>Oe,Tensor:()=>Ge,env:()=>ge,registerBackend:()=>$t});var We=U(()=>{"use strict";qi();Qi();fa();Rn();ha();ga();Un();ba();ya()});var yr=U(()=>{"use strict"});var $a={};Dt($a,{default:()=>Hp});var wa,va,Hp,xa=U(()=>{"use strict";Vn();ht();_r();wa="ort-wasm-proxy-worker",va=globalThis.self?.name===wa;va&&(self.onmessage=e=>{let{type:t,in:r}=e.data;try{switch(t){case"init-wasm":wr(r.wasm).then(()=>{vr(r).then(()=>{postMessage({type:t})},n=>{postMessage({type:t,err:n})})},n=>{postMessage({type:t,err:n})});break;case"init-ep":{let{epName:n,env:o}=r;$r(o,n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:n}=r,o=jt(n);postMessage({type:t,out:o});break}case"create":{let{model:n,options:o}=r;xr(n,o).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":Sr(r),postMessage({type:t});break;case"run":{let{sessionId:n,inputIndices:o,inputs:i,outputIndices:a,options:u}=r;Tr(n,o,i,a,new Array(a.length).fill(null),u).then(d=>{d.some(c=>c[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},Cr([...i,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":Ir(r),postMessage({type:t});break;default:}}catch(n){postMessage({type:t,err:n})}});Hp=va?null:e=>new Worker(e??Ue,{type:"module",name:wa})});var Ta={};Dt(Ta,{default:()=>Fp});var Wn,Sa,Fp,qp,Ia=U(()=>{"use strict";Sa=(Wn=import.meta.url,async function(e={}){var t,r,n=e,o=new Promise((s,l)=>{t=s,r=l}),i=typeof window=="object",a=typeof WorkerGlobalScope<"u",u=a&&self.name?.startsWith("em-pthread");n.mountExternalData=(s,l)=>{s.startsWith("./")&&(s=s.substring(2)),(n.Eb||(n.Eb=new Map)).set(s,l)},n.unmountExternalData=()=>{delete n.Eb};var d=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=s=>async(...l)=>{try{if(n.Fb)throw Error("Session already started");let h=n.Fb={dc:l[0],errors:[]},y=await s(...l);if(n.Fb!==h)throw Error("Session mismatch");n.Jb?.flush();let w=h.errors;if(0B),0{if(s==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=l;let h=n.Jb;n.jsepRegisterBuffer=(y,w,A,B)=>h.registerBuffer(y,w,A,B),n.jsepGetBuffer=y=>h.getBuffer(y),n.jsepCreateDownloader=(y,w,A)=>h.createDownloader(y,w,A),n.jsepOnCreateSession=y=>{h.onCreateSession(y)},n.jsepOnReleaseSession=y=>{h.onReleaseSession(y)},n.jsepOnRunStart=y=>h.onRunStart(y),n.bc=(y,w)=>{h.upload(y,w)}}else if(s==="webnn"){let h=l[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=l.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=y=>h.onRunStart(y),n.webnnOnRunEnd=h.onRunEnd.bind(h),n.webnnRegisterMLContext=(y,w)=>{h.registerMLContext(y,w)},n.webnnOnReleaseSession=y=>{h.onReleaseSession(y)},n.webnnCreateMLTensorDownloader=(y,w)=>h.createMLTensorDownloader(y,w),n.webnnRegisterMLTensor=(y,w,A,B)=>h.registerMLTensor(y,w,A,B),n.webnnCreateMLContext=y=>h.createMLContext(y),n.webnnRegisterMLConstant=(y,w,A,B,R,G)=>h.registerMLConstant(y,w,A,B,R,n.Eb,G),n.webnnRegisterGraphInput=h.registerGraphInput.bind(h),n.webnnIsGraphInput=h.isGraphInput.bind(h),n.webnnCreateTemporaryTensor=h.createTemporaryTensor.bind(h),n.webnnIsInt64Supported=h.isInt64Supported.bind(h)}};let p=()=>{let s=(l,h,y)=>(...w)=>{let A=Ze,B=h?.();w=l(...w);let R=h?.();return B!==R&&(l=R,y(B),h=y=null),Ze!=A?new Promise((G,K)=>{Sn={resolve:G,reject:K}}):w};(()=>{for(let l of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[l]=s(n[l],()=>n[l],h=>n[l]=h)})(),c!==void 0&&(n._OrtRun=c(n._OrtRun),n._OrtRunWithBinding=c(n._OrtRunWithBinding)),p=void 0};n.asyncInit=()=>{p?.()};var m,f,b=Object.assign({},n),g=(s,l)=>{throw l},_="";(i||a)&&(a?_=self.location.href:typeof document<"u"&&document.currentScript&&(_=document.currentScript.src),Wn&&(_=Wn),_=_.startsWith("blob:")?"":_.slice(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1),a&&(f=s=>{var l=new XMLHttpRequest;return l.open("GET",s,!1),l.responseType="arraybuffer",l.send(null),new Uint8Array(l.response)}),m=async s=>{if(X(s))return new Promise((h,y)=>{var w=new XMLHttpRequest;w.open("GET",s,!0),w.responseType="arraybuffer",w.onload=()=>{w.status==200||w.status==0&&w.response?h(w.response):y(w.status)},w.onerror=y,w.send(null)});var l=await fetch(s,{credentials:"same-origin"});if(l.ok)return l.arrayBuffer();throw Error(l.status+" : "+l.url)});var S=console.log.bind(console),$=console.error.bind(console),v=S,x=$;Object.assign(n,b),b=null;var T,E,I,z,O,D,L,q,Q,W,Z,we,H,j=n.wasmBinary,te=!1,X=s=>s.startsWith("file://");function ue(){return T.buffer!=z.buffer&&Ce(),z}function he(){return T.buffer!=z.buffer&&Ce(),O}function ye(){return T.buffer!=z.buffer&&Ce(),D}function re(){return T.buffer!=z.buffer&&Ce(),L}function C(){return T.buffer!=z.buffer&&Ce(),q}function V(){return T.buffer!=z.buffer&&Ce(),Q}function de(){return T.buffer!=z.buffer&&Ce(),W}function ze(){return T.buffer!=z.buffer&&Ce(),H}if(u){let s=function(l){try{var h=l.data,y=h.Bb;if(y==="load"){let w=[];self.onmessage=A=>w.push(A),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let A of w)s(A);self.onmessage=s};for(let A of h.Rb)n[A]&&!n[A].proxy||(n[A]=(...B)=>{postMessage({Bb:"callHandler",Qb:A,args:B})},A=="print"&&(v=n[A]),A=="printErr"&&(x=n[A]));T=h.kc,Ce(),ve(h.lc)}else if(y==="run"){_c(h.Ab),An(h.Ab,0,0,1,0,0),No(),$n(h.Ab),$e||(Oi(),$e=!0);try{wc(h.fc,h.Hb)}catch(w){if(w!="unwind")throw w}}else h.target!=="setimmediate"&&(y==="checkMailbox"?$e&&nr():y&&(x(`worker: received unknown command ${y}`),x(h)))}catch(w){throw Bi(),w}};var wg=s,ve,$e=!1;x=function(...l){l=l.join(" "),console.error(l)},self.alert=function(...l){postMessage({Bb:"alert",text:l.join(" "),ic:cr()})},self.onunhandledrejection=l=>{throw l.reason||l},self.onmessage=s}function Ce(){var s=T.buffer;n.HEAP8=z=new Int8Array(s),n.HEAP16=D=new Int16Array(s),n.HEAPU8=O=new Uint8Array(s),n.HEAPU16=L=new Uint16Array(s),n.HEAP32=q=new Int32Array(s),n.HEAPU32=Q=new Uint32Array(s),n.HEAPF32=W=new Float32Array(s),n.HEAPF64=H=new Float64Array(s),n.HEAP64=Z=new BigInt64Array(s),n.HEAPU64=we=new BigUint64Array(s)}function _t(){u?startWorker(n):Y.Ca()}u||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Ce());var kt,Pt=0,Lt=null;function zo(){if(--Pt==0&&Lt){var s=Lt;Lt=null,s()}}function dt(s){throw x(s="Aborted("+s+")"),te=!0,s=new WebAssembly.RuntimeError(s+". Build with -sASSERTIONS for more info."),r(s),s}function Oo(){return{a:{L:yc,Aa:bc,b:$c,$:Go,A:qo,pa:jo,X:Zo,Z:Qo,qa:Yo,na:Xo,ga:Jo,ma:ei,J:ti,Y:ri,V:ni,oa:oi,W:ii,va:xc,E:Tc,Q:Ic,O:Ac,D:kc,u:Pc,r:zc,P:Oc,z:Vc,R:Wc,ja:Lc,T:Gc,aa:Hc,M:Fc,F:qc,ia:$n,sa:jc,t:Kc,Ba:Zc,w:Xc,o:Jc,l:tp,c:_n,n:rp,j:ip,v:ap,p:sp,f:up,s:dp,m:lp,e:cp,k:pp,i:mp,g:fp,d:hp,da:gp,ea:bp,fa:yp,ba:_i,ca:wi,N:vi,xa:wp,ua:xp,h:Sp,C:Tp,G:Ip,ta:vp,x:Cp,ra:Ap,U:Ep,q:_p,y:kp,K:Pp,S:zp,za:Op,ya:Bp,ka:Ti,la:Ii,_:hn,B:Ci,I:Ai,ha:Ei,H:ki,a:T,wa:fn}}}var cn={829644:(s,l,h,y,w)=>{if(n===void 0||!n.Eb)return 1;if((s=Te(Number(s>>>0))).startsWith("./")&&(s=s.substring(2)),!(s=n.Eb.get(s)))return 2;if(l=Number(l>>>0),h=Number(h>>>0),y=Number(y>>>0),l+h>s.byteLength)return 3;try{let A=s.subarray(l,l+h);switch(w){case 0:he().set(A,y>>>0);break;case 1:n.mc?n.mc(y,A):n.bc(y,A);break;default:return 4}return 0}catch{return 4}},830468:(s,l,h)=>{n.Ob(s,he().subarray(l>>>0,l+h>>>0))},830532:()=>n.nc(),830574:s=>{n.Nb(s)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:s=>n.Ub(s),830729:s=>n.Yb(s),830761:(s,l,h)=>{n.Kb(Number(s),Number(l),Number(h),!0)},830824:(s,l,h)=>{n.Kb(Number(s),Number(l),Number(h))},830881:()=>typeof wasmOffsetConverter<"u",830938:s=>{n.jb("Abs",s,void 0)},830989:s=>{n.jb("Neg",s,void 0)},831040:s=>{n.jb("Floor",s,void 0)},831093:s=>{n.jb("Ceil",s,void 0)},831145:s=>{n.jb("Reciprocal",s,void 0)},831203:s=>{n.jb("Sqrt",s,void 0)},831255:s=>{n.jb("Exp",s,void 0)},831306:s=>{n.jb("Erf",s,void 0)},831357:s=>{n.jb("Sigmoid",s,void 0)},831412:(s,l,h)=>{n.jb("HardSigmoid",s,{alpha:l,beta:h})},831491:s=>{n.jb("Log",s,void 0)},831542:s=>{n.jb("Sin",s,void 0)},831593:s=>{n.jb("Cos",s,void 0)},831644:s=>{n.jb("Tan",s,void 0)},831695:s=>{n.jb("Asin",s,void 0)},831747:s=>{n.jb("Acos",s,void 0)},831799:s=>{n.jb("Atan",s,void 0)},831851:s=>{n.jb("Sinh",s,void 0)},831903:s=>{n.jb("Cosh",s,void 0)},831955:s=>{n.jb("Asinh",s,void 0)},832008:s=>{n.jb("Acosh",s,void 0)},832061:s=>{n.jb("Atanh",s,void 0)},832114:s=>{n.jb("Tanh",s,void 0)},832166:s=>{n.jb("Not",s,void 0)},832217:(s,l,h)=>{n.jb("Clip",s,{min:l,max:h})},832286:s=>{n.jb("Clip",s,void 0)},832338:(s,l)=>{n.jb("Elu",s,{alpha:l})},832396:s=>{n.jb("Gelu",s,void 0)},832448:s=>{n.jb("Relu",s,void 0)},832500:(s,l)=>{n.jb("LeakyRelu",s,{alpha:l})},832564:(s,l)=>{n.jb("ThresholdedRelu",s,{alpha:l})},832634:(s,l)=>{n.jb("Cast",s,{to:l})},832692:s=>{n.jb("Add",s,void 0)},832743:s=>{n.jb("Sub",s,void 0)},832794:s=>{n.jb("Mul",s,void 0)},832845:s=>{n.jb("Div",s,void 0)},832896:s=>{n.jb("Pow",s,void 0)},832947:s=>{n.jb("Equal",s,void 0)},833e3:s=>{n.jb("Greater",s,void 0)},833055:s=>{n.jb("GreaterOrEqual",s,void 0)},833117:s=>{n.jb("Less",s,void 0)},833169:s=>{n.jb("LessOrEqual",s,void 0)},833228:(s,l,h,y,w)=>{n.jb("ReduceMean",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},833403:(s,l,h,y,w)=>{n.jb("ReduceMax",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},833577:(s,l,h,y,w)=>{n.jb("ReduceMin",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},833751:(s,l,h,y,w)=>{n.jb("ReduceProd",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},833926:(s,l,h,y,w)=>{n.jb("ReduceSum",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},834100:(s,l,h,y,w)=>{n.jb("ReduceL1",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},834273:(s,l,h,y,w)=>{n.jb("ReduceL2",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},834446:(s,l,h,y,w)=>{n.jb("ReduceLogSum",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},834623:(s,l,h,y,w)=>{n.jb("ReduceSumSquare",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},834803:(s,l,h,y,w)=>{n.jb("ReduceLogSumExp",s,{keepDims:!!l,noopWithEmptyAxes:!!h,axes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},834983:s=>{n.jb("Where",s,void 0)},835036:(s,l,h)=>{n.jb("Transpose",s,{perm:l?Array.from(C().subarray(Number(l)>>>0,Number(h)>>>0)):[]})},835160:(s,l,h,y)=>{n.jb("DepthToSpace",s,{blocksize:l,mode:Te(h),format:y?"NHWC":"NCHW"})},835293:(s,l,h,y)=>{n.jb("DepthToSpace",s,{blocksize:l,mode:Te(h),format:y?"NHWC":"NCHW"})},835426:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke,Bt)=>{n.jb("ConvTranspose",s,{format:G?"NHWC":"NCHW",autoPad:l,dilations:[h],group:y,kernelShape:[w],pads:[A,B],strides:[R],wIsConst:()=>!!ue()[K>>>0],outputPadding:ae?Array.from(C().subarray(Number(ae)>>>0,Number(le)>>>0)):[],outputShape:_e?Array.from(C().subarray(Number(_e)>>>0,Number(ke)>>>0)):[],activation:Te(Bt)})},835859:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke)=>{n.jb("ConvTranspose",s,{format:R?"NHWC":"NCHW",autoPad:l,dilations:Array.from(C().subarray(Number(h)>>>0,2+(Number(h)>>>0)>>>0)),group:y,kernelShape:Array.from(C().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(C().subarray(Number(A)>>>0,4+(Number(A)>>>0)>>>0)),strides:Array.from(C().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!ue()[G>>>0],outputPadding:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],outputShape:le?Array.from(C().subarray(Number(le)>>>0,Number(_e)>>>0)):[],activation:Te(ke)})},836520:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke,Bt)=>{n.jb("ConvTranspose",s,{format:G?"NHWC":"NCHW",autoPad:l,dilations:[h],group:y,kernelShape:[w],pads:[A,B],strides:[R],wIsConst:()=>!!ue()[K>>>0],outputPadding:ae?Array.from(C().subarray(Number(ae)>>>0,Number(le)>>>0)):[],outputShape:_e?Array.from(C().subarray(Number(_e)>>>0,Number(ke)>>>0)):[],activation:Te(Bt)})},836953:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke)=>{n.jb("ConvTranspose",s,{format:R?"NHWC":"NCHW",autoPad:l,dilations:Array.from(C().subarray(Number(h)>>>0,2+(Number(h)>>>0)>>>0)),group:y,kernelShape:Array.from(C().subarray(Number(w)>>>0,2+(Number(w)>>>0)>>>0)),pads:Array.from(C().subarray(Number(A)>>>0,4+(Number(A)>>>0)>>>0)),strides:Array.from(C().subarray(Number(B)>>>0,2+(Number(B)>>>0)>>>0)),wIsConst:()=>!!ue()[G>>>0],outputPadding:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],outputShape:le?Array.from(C().subarray(Number(le)>>>0,Number(_e)>>>0)):[],activation:Te(ke)})},837614:(s,l)=>{n.jb("GlobalAveragePool",s,{format:l?"NHWC":"NCHW"})},837705:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke)=>{n.jb("AveragePool",s,{format:ke?"NHWC":"NCHW",auto_pad:l,ceil_mode:h,count_include_pad:y,storage_order:w,dilations:A?Array.from(C().subarray(Number(A)>>>0,Number(B)>>>0)):[],kernel_shape:R?Array.from(C().subarray(Number(R)>>>0,Number(G)>>>0)):[],pads:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],strides:le?Array.from(C().subarray(Number(le)>>>0,Number(_e)>>>0)):[]})},838184:(s,l)=>{n.jb("GlobalAveragePool",s,{format:l?"NHWC":"NCHW"})},838275:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke)=>{n.jb("AveragePool",s,{format:ke?"NHWC":"NCHW",auto_pad:l,ceil_mode:h,count_include_pad:y,storage_order:w,dilations:A?Array.from(C().subarray(Number(A)>>>0,Number(B)>>>0)):[],kernel_shape:R?Array.from(C().subarray(Number(R)>>>0,Number(G)>>>0)):[],pads:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],strides:le?Array.from(C().subarray(Number(le)>>>0,Number(_e)>>>0)):[]})},838754:(s,l)=>{n.jb("GlobalMaxPool",s,{format:l?"NHWC":"NCHW"})},838841:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke)=>{n.jb("MaxPool",s,{format:ke?"NHWC":"NCHW",auto_pad:l,ceil_mode:h,count_include_pad:y,storage_order:w,dilations:A?Array.from(C().subarray(Number(A)>>>0,Number(B)>>>0)):[],kernel_shape:R?Array.from(C().subarray(Number(R)>>>0,Number(G)>>>0)):[],pads:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],strides:le?Array.from(C().subarray(Number(le)>>>0,Number(_e)>>>0)):[]})},839316:(s,l)=>{n.jb("GlobalMaxPool",s,{format:l?"NHWC":"NCHW"})},839403:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke)=>{n.jb("MaxPool",s,{format:ke?"NHWC":"NCHW",auto_pad:l,ceil_mode:h,count_include_pad:y,storage_order:w,dilations:A?Array.from(C().subarray(Number(A)>>>0,Number(B)>>>0)):[],kernel_shape:R?Array.from(C().subarray(Number(R)>>>0,Number(G)>>>0)):[],pads:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],strides:le?Array.from(C().subarray(Number(le)>>>0,Number(_e)>>>0)):[]})},839878:(s,l,h,y,w)=>{n.jb("Gemm",s,{alpha:l,beta:h,transA:y,transB:w})},839982:s=>{n.jb("MatMul",s,void 0)},840036:(s,l,h,y)=>{n.jb("ArgMax",s,{keepDims:!!l,selectLastIndex:!!h,axis:y})},840144:(s,l,h,y)=>{n.jb("ArgMin",s,{keepDims:!!l,selectLastIndex:!!h,axis:y})},840252:(s,l)=>{n.jb("Softmax",s,{axis:l})},840315:(s,l)=>{n.jb("Concat",s,{axis:l})},840375:(s,l,h,y,w)=>{n.jb("Split",s,{axis:l,numOutputs:h,splitSizes:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},840531:s=>{n.jb("Expand",s,void 0)},840585:(s,l)=>{n.jb("Gather",s,{axis:Number(l)})},840656:(s,l)=>{n.jb("GatherElements",s,{axis:Number(l)})},840735:(s,l)=>{n.jb("GatherND",s,{batch_dims:Number(l)})},840814:(s,l,h,y,w,A,B,R,G,K,ae)=>{n.jb("Resize",s,{antialias:l,axes:h?Array.from(C().subarray(Number(h)>>>0,Number(y)>>>0)):[],coordinateTransformMode:Te(w),cubicCoeffA:A,excludeOutside:B,extrapolationValue:R,keepAspectRatioPolicy:Te(G),mode:Te(K),nearestMode:Te(ae)})},841176:(s,l,h,y,w,A,B)=>{n.jb("Slice",s,{starts:l?Array.from(C().subarray(Number(l)>>>0,Number(h)>>>0)):[],ends:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[],axes:A?Array.from(C().subarray(Number(A)>>>0,Number(B)>>>0)):[]})},841440:s=>{n.jb("Tile",s,void 0)},841492:(s,l,h)=>{n.jb("InstanceNormalization",s,{epsilon:l,format:h?"NHWC":"NCHW"})},841606:(s,l,h)=>{n.jb("InstanceNormalization",s,{epsilon:l,format:h?"NHWC":"NCHW"})},841720:s=>{n.jb("Range",s,void 0)},841773:(s,l)=>{n.jb("Einsum",s,{equation:Te(l)})},841854:(s,l,h,y,w)=>{n.jb("Pad",s,{mode:l,value:h,pads:y?Array.from(C().subarray(Number(y)>>>0,Number(w)>>>0)):[]})},841997:(s,l,h,y,w,A)=>{n.jb("BatchNormalization",s,{epsilon:l,momentum:h,spatial:!!w,trainingMode:!!y,format:A?"NHWC":"NCHW"})},842166:(s,l,h,y,w,A)=>{n.jb("BatchNormalization",s,{epsilon:l,momentum:h,spatial:!!w,trainingMode:!!y,format:A?"NHWC":"NCHW"})},842335:(s,l,h)=>{n.jb("CumSum",s,{exclusive:Number(l),reverse:Number(h)})},842432:(s,l,h)=>{n.jb("DequantizeLinear",s,{axis:l,blockSize:h})},842522:(s,l,h,y,w)=>{n.jb("GridSample",s,{align_corners:l,mode:Te(h),padding_mode:Te(y),format:w?"NHWC":"NCHW"})},842692:(s,l,h,y,w)=>{n.jb("GridSample",s,{align_corners:l,mode:Te(h),padding_mode:Te(y),format:w?"NHWC":"NCHW"})},842862:(s,l)=>{n.jb("ScatterND",s,{reduction:Te(l)})},842947:(s,l,h,y,w,A,B,R,G)=>{n.jb("Attention",s,{numHeads:l,isUnidirectional:h,maskFilterValue:y,scale:w,doRotary:A,qkvHiddenSizes:B?Array.from(C().subarray(Number(R)>>>0,Number(R)+B>>>0)):[],pastPresentShareBuffer:!!G})},843219:s=>{n.jb("BiasAdd",s,void 0)},843274:s=>{n.jb("BiasSplitGelu",s,void 0)},843335:s=>{n.jb("FastGelu",s,void 0)},843391:(s,l,h,y,w,A,B,R,G,K,ae,le,_e,ke,Bt,Rp)=>{n.jb("Conv",s,{format:le?"NHWC":"NCHW",auto_pad:l,dilations:h?Array.from(C().subarray(Number(h)>>>0,Number(y)>>>0)):[],group:w,kernel_shape:A?Array.from(C().subarray(Number(A)>>>0,Number(B)>>>0)):[],pads:R?Array.from(C().subarray(Number(R)>>>0,Number(G)>>>0)):[],strides:K?Array.from(C().subarray(Number(K)>>>0,Number(ae)>>>0)):[],w_is_const:()=>!!ue()[Number(_e)>>>0],activation:Te(ke),activation_params:Bt?Array.from(de().subarray(Number(Bt)>>>0,Number(Rp)>>>0)):[]})},843975:s=>{n.jb("Gelu",s,void 0)},844027:(s,l,h,y,w,A,B,R,G)=>{n.jb("GroupQueryAttention",s,{numHeads:l,kvNumHeads:h,scale:y,softcap:w,doRotary:A,rotaryInterleaved:B,smoothSoftmax:R,localWindowSize:G})},844244:(s,l,h,y)=>{n.jb("LayerNormalization",s,{axis:l,epsilon:h,simplified:!!y})},844355:(s,l,h,y)=>{n.jb("LayerNormalization",s,{axis:l,epsilon:h,simplified:!!y})},844466:(s,l,h,y,w,A)=>{n.jb("MatMulNBits",s,{k:l,n:h,accuracyLevel:y,bits:w,blockSize:A})},844593:(s,l,h,y,w,A)=>{n.jb("MultiHeadAttention",s,{numHeads:l,isUnidirectional:h,maskFilterValue:y,scale:w,doRotary:A})},844752:(s,l)=>{n.jb("QuickGelu",s,{alpha:l})},844816:(s,l,h,y,w)=>{n.jb("RotaryEmbedding",s,{interleaved:!!l,numHeads:h,rotaryEmbeddingDim:y,scale:w})},844955:(s,l,h)=>{n.jb("SkipLayerNormalization",s,{epsilon:l,simplified:!!h})},845057:(s,l,h)=>{n.jb("SkipLayerNormalization",s,{epsilon:l,simplified:!!h})},845159:(s,l,h,y)=>{n.jb("GatherBlockQuantized",s,{gatherAxis:l,quantizeAxis:h,blockSize:y})},845280:s=>{n.Zb(s)},845314:(s,l)=>n.ac(Number(s),Number(l),n.Fb.dc,n.Fb.errors)};function bc(s,l,h){return mi(async()=>{await n.Xb(Number(s),Number(l),Number(h))})}function yc(){return typeof wasmOffsetConverter<"u"}class pn{name="ExitStatus";constructor(l){this.message=`Program terminated with exit(${l})`,this.status=l}}var Bo=s=>{s.terminate(),s.onmessage=()=>{}},mn=[],Do=s=>{ct.length==0&&(Wo(),Vo(ct[0]));var l=ct.pop();if(!l)return 6;Gt.push(l),wt[s.Ab]=l,l.Ab=s.Ab;var h={Bb:"run",fc:s.ec,Hb:s.Hb,Ab:s.Ab};return l.postMessage(h,s.Mb),0},lt=0,xe=(s,l,...h)=>{for(var y=2*h.length,w=Pn(),A=kn(8*y),B=A>>>3,R=0;R>>0]=G)}return s=Di(s,0,y,A,l),mr(w),s};function fn(s){if(u)return xe(0,1,s);if(I=s,!(0{if(I=s,u)throw Mo(s),"unwind";fn(s)},ct=[],Gt=[],Ro=[],wt={},Uo=s=>{var l=s.Ab;delete wt[l],ct.push(s),Gt.splice(Gt.indexOf(s),1),s.Ab=0,Mi(l)};function No(){Ro.forEach(s=>s())}var Vo=s=>new Promise(l=>{s.onmessage=w=>{var A=(w=w.data).Bb;if(w.Gb&&w.Gb!=cr()){var B=wt[w.Gb];B?B.postMessage(w,w.Mb):x(`Internal error! Worker sent a message "${A}" to target pthread ${w.Gb}, but that thread no longer exists!`)}else A==="checkMailbox"?nr():A==="spawnThread"?Do(w):A==="cleanupThread"?Uo(wt[w.hc]):A==="loaded"?(s.loaded=!0,l(s)):A==="alert"?alert(`Thread ${w.ic}: ${w.text}`):w.target==="setimmediate"?s.postMessage(w):A==="callHandler"?n[w.Qb](...w.args):A&&x(`worker sent an unknown command ${A}`)},s.onerror=w=>{throw x(`worker sent an error! ${w.filename}:${w.lineno}: ${w.message}`),w};var h,y=[];for(h of[])n.propertyIsEnumerable(h)&&y.push(h);s.postMessage({Bb:"load",Rb:y,kc:T,lc:E})});function Wo(){var s=new Worker((()=>{let l=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new l(/* asset import */ __webpack_require__(/*! ort.bundle.min.mjs */ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"), __webpack_require__.b):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ct.push(s)}var _c=s=>{Ce();var l=V()[s+52>>>2>>>0];s=V()[s+56>>>2>>>0],Ni(l,l-s),mr(l)},wc=(s,l)=>{lt=0,s=Vi(s,l),0>>=0);throw l>>>=0,h>>>=0,V()[y.Ib+16>>>2>>>0]=0,V()[y.Ib+4>>>2>>>0]=l,V()[y.Ib+8>>>2>>>0]=h,s}function Lo(s,l,h,y){return u?xe(2,1,s,l,h,y):Go(s,l,h,y)}function Go(s,l,h,y){if(s>>>=0,h>>>=0,y>>>=0,d===void 0)return 6;var w=[];return u&&w.length===0?Lo(s,l>>>=0,h,y):(s={ec:h,Ab:s,Hb:y,Mb:w},u?(s.Bb="spawnThread",postMessage(s,w),0):Do(s))}var Ho=typeof TextDecoder<"u"?new TextDecoder:void 0,Fo=(s,l=0,h=NaN)=>{var y=(l>>>=0)+h;for(h=l;s[h]&&!(h>=y);)++h;if(16(w=(240&w)==224?(15&w)<<12|A<<6|B:(7&w)<<18|A<<12|B<<6|63&s[l++])?y+=String.fromCharCode(w):(w-=65536,y+=String.fromCharCode(55296|w>>10,56320|1023&w))}}else y+=String.fromCharCode(w)}return y},Te=(s,l)=>(s>>>=0)?Fo(he(),s,l):"";function qo(s,l,h){return u?xe(3,1,s,l,h):0}function jo(s,l){if(u)return xe(4,1,s,l)}var Ko=s=>{for(var l=0,h=0;h=y?l++:2047>=y?l+=2:55296<=y&&57343>=y?(l+=4,++h):l+=3}return l},zt=(s,l,h)=>{var y=he();if(l>>>=0,0=B&&(B=65536+((1023&B)<<10)|1023&s.charCodeAt(++A)),127>=B){if(l>=h)break;y[l++>>>0]=B}else{if(2047>=B){if(l+1>=h)break;y[l++>>>0]=192|B>>6}else{if(65535>=B){if(l+2>=h)break;y[l++>>>0]=224|B>>12}else{if(l+3>=h)break;y[l++>>>0]=240|B>>18,y[l++>>>0]=128|B>>12&63}y[l++>>>0]=128|B>>6&63}y[l++>>>0]=128|63&B}}y[l>>>0]=0,s=l-w}else s=0;return s};function Zo(s,l){if(u)return xe(5,1,s,l)}function Qo(s,l,h){if(u)return xe(6,1,s,l,h)}function Yo(s,l,h){return u?xe(7,1,s,l,h):0}function Xo(s,l){if(u)return xe(8,1,s,l)}function Jo(s,l,h){if(u)return xe(9,1,s,l,h)}function ei(s,l,h,y){if(u)return xe(10,1,s,l,h,y)}function ti(s,l,h,y){if(u)return xe(11,1,s,l,h,y)}function ri(s,l,h,y){if(u)return xe(12,1,s,l,h,y)}function ni(s){if(u)return xe(13,1,s)}function oi(s,l){if(u)return xe(14,1,s,l)}function ii(s,l,h){if(u)return xe(15,1,s,l,h)}var ai,pt,xc=()=>dt(""),Ke=s=>{for(var l="";he()[s>>>0];)l+=ai[he()[s++>>>0]];return l},gn={},bn={},Sc={};function it(s,l,h={}){return function(y,w,A={}){var B=w.name;if(!y)throw new pt(`type "${B}" must have a positive integer typeid pointer`);if(bn.hasOwnProperty(y)){if(A.Sb)return;throw new pt(`Cannot register type '${B}' twice`)}bn[y]=w,delete Sc[y],gn.hasOwnProperty(y)&&(w=gn[y],delete gn[y],w.forEach(R=>R()))}(s,l,h)}var si=(s,l,h)=>{switch(l){case 1:return h?y=>ue()[y>>>0]:y=>he()[y>>>0];case 2:return h?y=>ye()[y>>>1>>>0]:y=>re()[y>>>1>>>0];case 4:return h?y=>C()[y>>>2>>>0]:y=>V()[y>>>2>>>0];case 8:return h?y=>Z[y>>>3]:y=>we[y>>>3];default:throw new TypeError(`invalid integer width (${l}): ${s}`)}};function Tc(s,l,h){h>>>=0,it(s>>>=0,{name:l=Ke(l>>>0),fromWireType:y=>y,toWireType:function(y,w){if(typeof w!="bigint"&&typeof w!="number")throw w=w===null?"null":(y=typeof w)=="object"||y==="array"||y==="function"?w.toString():""+w,new TypeError(`Cannot convert "${w}" to ${this.name}`);return typeof w=="number"&&(w=BigInt(w)),w},Cb:mt,readValueFromPointer:si(l,h,l.indexOf("u")==-1),Db:null})}var mt=8;function Ic(s,l,h,y){it(s>>>=0,{name:l=Ke(l>>>0),fromWireType:function(w){return!!w},toWireType:function(w,A){return A?h:y},Cb:mt,readValueFromPointer:function(w){return this.fromWireType(he()[w>>>0])},Db:null})}var yn=[],at=[];function _n(s){9<(s>>>=0)&&--at[s+1]==0&&(at[s]=void 0,yn.push(s))}var De=s=>{if(!s)throw new pt("Cannot use deleted val. handle = "+s);return at[s]},Ve=s=>{switch(s){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let l=yn.pop()||at.length;return at[l]=s,at[l+1]=1,l}};function wn(s){return this.fromWireType(V()[s>>>2>>>0])}var Cc={name:"emscripten::val",fromWireType:s=>{var l=De(s);return _n(s),l},toWireType:(s,l)=>Ve(l),Cb:mt,readValueFromPointer:wn,Db:null};function Ac(s){return it(s>>>0,Cc)}var Ec=(s,l)=>{switch(l){case 4:return function(h){return this.fromWireType(de()[h>>>2>>>0])};case 8:return function(h){return this.fromWireType(ze()[h>>>3>>>0])};default:throw new TypeError(`invalid float width (${l}): ${s}`)}};function kc(s,l,h){h>>>=0,it(s>>>=0,{name:l=Ke(l>>>0),fromWireType:y=>y,toWireType:(y,w)=>w,Cb:mt,readValueFromPointer:Ec(l,h),Db:null})}function Pc(s,l,h,y,w){if(s>>>=0,h>>>=0,l=Ke(l>>>0),w===-1&&(w=4294967295),w=R=>R,y===0){var A=32-8*h;w=R=>R<>>A}var B=l.includes("unsigned")?function(R,G){return G>>>0}:function(R,G){return G};it(s,{name:l,fromWireType:w,toWireType:B,Cb:mt,readValueFromPointer:si(l,h,y!==0),Db:null})}function zc(s,l,h){function y(A){var B=V()[A>>>2>>>0];return A=V()[A+4>>>2>>>0],new w(ue().buffer,A,B)}var w=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][l];it(s>>>=0,{name:h=Ke(h>>>0),fromWireType:y,Cb:mt,readValueFromPointer:y},{Sb:!0})}function Oc(s,l){it(s>>>=0,{name:l=Ke(l>>>0),fromWireType:function(h){for(var y,w=V()[h>>>2>>>0],A=h+4,B=A,R=0;R<=w;++R){var G=A+R;R!=w&&he()[G>>>0]!=0||(B=Te(B,G-B),y===void 0?y=B:(y+="\0",y+=B),B=G+1)}return Qe(h),y},toWireType:function(h,y){y instanceof ArrayBuffer&&(y=new Uint8Array(y));var w=typeof y=="string";if(!(w||y instanceof Uint8Array||y instanceof Uint8ClampedArray||y instanceof Int8Array))throw new pt("Cannot pass non-string to std::string");var A=w?Ko(y):y.length,B=pr(4+A+1),R=B+4;if(V()[B>>>2>>>0]=A,w)zt(y,R,A+1);else if(w)for(w=0;w>>0]=G}else for(w=0;w>>0]=y[w];return h!==null&&h.push(Qe,B),B},Cb:mt,readValueFromPointer:wn,Db(h){Qe(h)}})}var ui=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Bc=(s,l)=>{for(var h=s>>1,y=h+l/2;!(h>=y)&&re()[h>>>0];)++h;if(32<(h<<=1)-s&&ui)return ui.decode(he().slice(s,h));for(h="",y=0;!(y>=l/2);++y){var w=ye()[s+2*y>>>1>>>0];if(w==0)break;h+=String.fromCharCode(w)}return h},Dc=(s,l,h)=>{if(h??=2147483647,2>h)return 0;var y=l;h=(h-=2)<2*s.length?h/2:s.length;for(var w=0;w>>1>>>0]=A,l+=2}return ye()[l>>>1>>>0]=0,l-y},Mc=s=>2*s.length,Rc=(s,l)=>{for(var h=0,y="";!(h>=l/4);){var w=C()[s+4*h>>>2>>>0];if(w==0)break;++h,65536<=w?(w-=65536,y+=String.fromCharCode(55296|w>>10,56320|1023&w)):y+=String.fromCharCode(w)}return y},Uc=(s,l,h)=>{if(l>>>=0,h??=2147483647,4>h)return 0;var y=l;h=y+h-4;for(var w=0;w=A&&(A=65536+((1023&A)<<10)|1023&s.charCodeAt(++w)),C()[l>>>2>>>0]=A,(l+=4)+4>h)break}return C()[l>>>2>>>0]=0,l-y},Nc=s=>{for(var l=0,h=0;h=y&&++h,l+=4}return l};function Vc(s,l,h){if(s>>>=0,l>>>=0,h=Ke(h>>>=0),l===2)var y=Bc,w=Dc,A=Mc,B=R=>re()[R>>>1>>>0];else l===4&&(y=Rc,w=Uc,A=Nc,B=R=>V()[R>>>2>>>0]);it(s,{name:h,fromWireType:R=>{for(var G,K=V()[R>>>2>>>0],ae=R+4,le=0;le<=K;++le){var _e=R+4+le*l;le!=K&&B(_e)!=0||(ae=y(ae,_e-ae),G===void 0?G=ae:(G+="\0",G+=ae),ae=_e+l)}return Qe(R),G},toWireType:(R,G)=>{if(typeof G!="string")throw new pt(`Cannot pass non-string to C++ string type ${h}`);var K=A(G),ae=pr(4+K+l);return V()[ae>>>2>>>0]=K/l,w(G,ae+4,K+l),R!==null&&R.push(Qe,ae),ae},Cb:mt,readValueFromPointer:wn,Db(R){Qe(R)}})}function Wc(s,l){it(s>>>=0,{Tb:!0,name:l=Ke(l>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function Lc(s){An(s>>>0,!a,1,!i,131072,!1),No()}var vn=s=>{if(!te)try{if(s(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(C(),s>>>2,s).value.then(nr),s+=128,Atomics.store(C(),s>>>2,1))}var nr=()=>{var s=cr();s&&($n(s),vn(Ui))};function Gc(s,l){(s>>>=0)==l>>>0?setTimeout(nr):u?postMessage({Gb:s,Bb:"checkMailbox"}):(s=wt[s])&&s.postMessage({Bb:"checkMailbox"})}var xn=[];function Hc(s,l,h,y,w){for(l>>>=0,y/=2,xn.length=y,h=w>>>0>>>3,w=0;w>>0];return(l?cn[l]:Mp[s])(...xn)}var Fc=()=>{lt=0};function qc(s){s>>>=0,u?postMessage({Bb:"cleanupThread",hc:s}):Uo(wt[s])}function jc(s){}var or=(s,l)=>{var h=bn[s];if(h===void 0)throw s=zi(s),h=Ke(s),Qe(s),new pt(`${l} has unknown type ${h}`);return h},di=(s,l,h)=>{var y=[];return s=s.toWireType(y,h),y.length&&(V()[l>>>2>>>0]=Ve(y)),s};function Kc(s,l,h){return l>>>=0,h>>>=0,s=De(s>>>0),l=or(l,"emval::as"),di(l,h,s)}function Zc(s,l){return l>>>=0,s=De(s>>>0),(l=or(l,"emval::as")).toWireType(null,s)}var ir=s=>{try{s()}catch(l){dt(l)}},ft=0,Ze=null,li=0,ar=[],ci={},pi={},Qc=0,Sn=null,Yc=[];function mi(s){return function(l){if(!te){if(ft===0){var h=!1,y=!1;l((w=0)=>{if(!te&&(li=w,h=!0,y)){ft=2,ir(()=>Gi(Ze)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),w=!1;try{var A=function(){var G=C()[Ze+8>>>2>>>0];return G=Y[pi[G]],--lt,G()}()}catch(G){A=G,w=!0}var B=!1;if(!Ze){var R=Sn;R&&(Sn=null,(w?R.reject:R.resolve)(A),B=!0)}if(w&&!B)throw A}}),y=!0,h||(ft=1,Ze=function(){var w=pr(65548),A=w+12;V()[w>>>2>>>0]=A,V()[w+4>>>2>>>0]=A+65536,A=ar[0];var B=ci[A];return B===void 0&&(B=Qc++,ci[A]=B,pi[B]=A),A=B,C()[w+8>>>2>>>0]=A,w}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),ir(()=>Wi(Ze)))}else ft===2?(ft=0,ir(Hi),Qe(Ze),Ze=null,Yc.forEach(vn)):dt(`invalid state: ${ft}`);return li}}(l=>{s().then(l)})}function Xc(s){return s>>>=0,mi(async()=>{var l=await De(s);return Ve(l)})}var sr=[];function Jc(s,l,h,y){return h>>>=0,y>>>=0,(s=sr[s>>>0])(null,l=De(l>>>0),h,y)}var ep={},ur=s=>{var l=ep[s];return l===void 0?Ke(s):l};function tp(s,l,h,y,w){return h>>>=0,y>>>=0,w>>>=0,(s=sr[s>>>0])(l=De(l>>>0),l[h=ur(h)],y,w)}var fi=()=>typeof globalThis=="object"?globalThis:Function("return this")();function rp(s){return(s>>>=0)==0?Ve(fi()):(s=ur(s),Ve(fi()[s]))}var np=s=>{var l=sr.length;return sr.push(s),l},op=(s,l)=>{for(var h=Array(s),y=0;y>>2>>>0],"parameter "+y);return h},hi=(s,l)=>Object.defineProperty(l,"name",{value:s});function ip(s,l,h){var y=(l=op(s,l>>>0)).shift();s--;var w=`return function (obj, func, destructorsRef, args) { -`,A=0,B=[];h===0&&B.push("obj");for(var R=["retType"],G=[y],K=0;Kae.name).join(", ")}) => ${y.name}>`,np(hi(h,s))}function ap(s){return s=ur(s>>>0),Ve(n[s])}function sp(s,l){return l>>>=0,s=De(s>>>0),l=De(l),Ve(s[l])}function up(s){9<(s>>>=0)&&(at[s+1]+=1)}function dp(){return Ve([])}function lp(s){s=De(s>>>0);for(var l=Array(s.length),h=0;h>>0))}function pp(){return Ve({})}function mp(s){for(var l=De(s>>>=0);l.length;){var h=l.pop();l.pop()(h)}_n(s)}function fp(s,l,h){l>>>=0,h>>>=0,s=De(s>>>0),l=De(l),h=De(h),s[l]=h}function hp(s,l){return l>>>=0,s=(s=or(s>>>0,"_emval_take_value")).readValueFromPointer(l),Ve(s)}function gp(s,l){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),C()[l>>>2>>>0]=s.getUTCSeconds(),C()[l+4>>>2>>>0]=s.getUTCMinutes(),C()[l+8>>>2>>>0]=s.getUTCHours(),C()[l+12>>>2>>>0]=s.getUTCDate(),C()[l+16>>>2>>>0]=s.getUTCMonth(),C()[l+20>>>2>>>0]=s.getUTCFullYear()-1900,C()[l+24>>>2>>>0]=s.getUTCDay(),s=(s.getTime()-Date.UTC(s.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,C()[l+28>>>2>>>0]=s}var gi=s=>s%4==0&&(s%100!=0||s%400==0),bi=[0,31,60,91,121,152,182,213,244,274,305,335],yi=[0,31,59,90,120,151,181,212,243,273,304,334];function bp(s,l){s=-9007199254740992>s||9007199254740992>>=0,s=new Date(1e3*s),C()[l>>>2>>>0]=s.getSeconds(),C()[l+4>>>2>>>0]=s.getMinutes(),C()[l+8>>>2>>>0]=s.getHours(),C()[l+12>>>2>>>0]=s.getDate(),C()[l+16>>>2>>>0]=s.getMonth(),C()[l+20>>>2>>>0]=s.getFullYear()-1900,C()[l+24>>>2>>>0]=s.getDay();var h=(gi(s.getFullYear())?bi:yi)[s.getMonth()]+s.getDate()-1|0;C()[l+28>>>2>>>0]=h,C()[l+36>>>2>>>0]=-60*s.getTimezoneOffset(),h=new Date(s.getFullYear(),6,1).getTimezoneOffset();var y=new Date(s.getFullYear(),0,1).getTimezoneOffset();s=0|(h!=y&&s.getTimezoneOffset()==Math.min(y,h)),C()[l+32>>>2>>>0]=s}function yp(s){s>>>=0;var l=new Date(C()[s+20>>>2>>>0]+1900,C()[s+16>>>2>>>0],C()[s+12>>>2>>>0],C()[s+8>>>2>>>0],C()[s+4>>>2>>>0],C()[s>>>2>>>0],0),h=C()[s+32>>>2>>>0],y=l.getTimezoneOffset(),w=new Date(l.getFullYear(),6,1).getTimezoneOffset(),A=new Date(l.getFullYear(),0,1).getTimezoneOffset(),B=Math.min(A,w);return 0>h?C()[s+32>>>2>>>0]=+(w!=A&&B==y):0>>2>>>0]=l.getDay(),h=(gi(l.getFullYear())?bi:yi)[l.getMonth()]+l.getDate()-1|0,C()[s+28>>>2>>>0]=h,C()[s>>>2>>>0]=l.getSeconds(),C()[s+4>>>2>>>0]=l.getMinutes(),C()[s+8>>>2>>>0]=l.getHours(),C()[s+12>>>2>>>0]=l.getDate(),C()[s+16>>>2>>>0]=l.getMonth(),C()[s+20>>>2>>>0]=l.getYear(),s=l.getTime(),BigInt(isNaN(s)?-1:s/1e3)}function _i(s,l,h,y,w,A,B){return u?xe(16,1,s,l,h,y,w,A,B):-52}function wi(s,l,h,y,w,A){if(u)return xe(17,1,s,l,h,y,w,A)}var Ht={},_p=()=>performance.timeOrigin+performance.now();function vi(s,l){if(u)return xe(18,1,s,l);if(Ht[s]&&(clearTimeout(Ht[s].id),delete Ht[s]),!l)return 0;var h=setTimeout(()=>{delete Ht[s],vn(()=>Ri(s,performance.timeOrigin+performance.now()))},l);return Ht[s]={id:h,qc:l},0}function wp(s,l,h,y){s>>>=0,l>>>=0,h>>>=0,y>>>=0;var w=new Date().getFullYear(),A=new Date(w,0,1).getTimezoneOffset();w=new Date(w,6,1).getTimezoneOffset();var B=Math.max(A,w);V()[s>>>2>>>0]=60*B,C()[l>>>2>>>0]=+(A!=w),s=(l=R=>{var G=Math.abs(R);return`UTC${0<=R?"-":"+"}${String(Math.floor(G/60)).padStart(2,"0")}${String(G%60).padStart(2,"0")}`})(A),l=l(w),wDate.now(),$p=1;function xp(s,l,h){if(!(0<=s&&3>=s))return 28;if(s===0)s=Date.now();else{if(!$p)return 52;s=performance.timeOrigin+performance.now()}return Z[h>>>0>>>3]=BigInt(Math.round(1e6*s)),0}var Tn=[],$i=(s,l)=>{Tn.length=0;for(var h;h=he()[s++>>>0];){var y=h!=105;l+=(y&=h!=112)&&l%8?4:0,Tn.push(h==112?V()[l>>>2>>>0]:h==106?Z[l>>>3]:h==105?C()[l>>>2>>>0]:ze()[l>>>3>>>0]),l+=y?8:4}return Tn};function Sp(s,l,h){return s>>>=0,l=$i(l>>>0,h>>>0),cn[s](...l)}function Tp(s,l,h){return s>>>=0,l=$i(l>>>0,h>>>0),cn[s](...l)}var Ip=()=>{};function Cp(s,l){return x(Te(s>>>0,l>>>0))}var Ap=()=>{throw lt+=1,"unwind"};function Ep(){return 4294901760}var kp=()=>navigator.hardwareConcurrency;function Pp(){return dt("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function zp(s){s>>>=0;var l=he().length;if(s<=l||4294901760=h;h*=2){var y=l*(1+.2/h);y=Math.min(y,s+100663296);e:{y=(Math.min(4294901760,65536*Math.ceil(Math.max(s,y)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(y),Ce();var w=1;break e}catch{}w=void 0}if(w)return!0}return!1}var dr=()=>(dt("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Ot={},xi=s=>{s.forEach(l=>{var h=dr();h&&(Ot[h]=l)})};function Op(){var s=Error().stack.toString().split(` -`);return s[0]=="Error"&&s.shift(),xi(s),Ot.Lb=dr(),Ot.cc=s,Ot.Lb}function Bp(s,l,h){if(s>>>=0,l>>>=0,Ot.Lb==s)var y=Ot.cc;else(y=Error().stack.toString().split(` -`))[0]=="Error"&&y.shift(),xi(y);for(var w=3;y[w]&&dr()!=s;)++w;for(s=0;s>>2>>>0]=dr();return s}var In,Cn={},Si=()=>{if(!In){var s,l={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(s in Cn)Cn[s]===void 0?delete l[s]:l[s]=Cn[s];var h=[];for(s in l)h.push(`${s}=${l[s]}`);In=h}return In};function Ti(s,l){if(u)return xe(19,1,s,l);s>>>=0,l>>>=0;var h=0;return Si().forEach((y,w)=>{var A=l+h;for(w=V()[s+4*w>>>2>>>0]=A,A=0;A>>0]=y.charCodeAt(A);ue()[w>>>0]=0,h+=y.length+1}),0}function Ii(s,l){if(u)return xe(20,1,s,l);s>>>=0,l>>>=0;var h=Si();V()[s>>>2>>>0]=h.length;var y=0;return h.forEach(w=>y+=w.length+1),V()[l>>>2>>>0]=y,0}function Ci(s){return u?xe(21,1,s):52}function Ai(s,l,h,y){return u?xe(22,1,s,l,h,y):52}function Ei(s,l,h,y){return u?xe(23,1,s,l,h,y):70}var Dp=[null,[],[]];function ki(s,l,h,y){if(u)return xe(24,1,s,l,h,y);l>>>=0,h>>>=0,y>>>=0;for(var w=0,A=0;A>>2>>>0],R=V()[l+4>>>2>>>0];l+=8;for(var G=0;G>>0],ae=Dp[s];K===0||K===10?((s===1?v:x)(Fo(ae)),ae.length=0):ae.push(K)}w+=R}return V()[y>>>2>>>0]=w,0}u||function(){for(var s=n.numThreads-1;s--;)Wo();mn.unshift(()=>{Pt++,function(l){u?l():Promise.all(ct.map(Vo)).then(l)}(()=>zo())})}();for(var Pi=Array(256),lr=0;256>lr;++lr)Pi[lr]=String.fromCharCode(lr);ai=Pi,pt=n.BindingError=class extends Error{constructor(s){super(s),this.name="BindingError"}},n.InternalError=class extends Error{constructor(s){super(s),this.name="InternalError"}},at.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>at.length/2-5-yn.length;var Y,Mp=[fn,Mo,Lo,qo,jo,Zo,Qo,Yo,Xo,Jo,ei,ti,ri,ni,oi,ii,_i,wi,vi,Ti,Ii,Ci,Ai,Ei,ki];(async function(){function s(y,w){return Y=y.exports,Y=function(){var A=Y,B={};for(let[R,G]of Object.entries(A))B[R]=typeof G=="function"?(...K)=>{ar.push(R);try{return G(...K)}finally{te||(ar.pop(),Ze&&ft===1&&ar.length===0&&(ft=0,lt+=1,ir(Li),typeof Fibers<"u"&&Fibers.rc()))}}:G;return B}(),Y=function(){var A=Y,B=G=>K=>G(K)>>>0,R=G=>()=>G()>>>0;return(A=Object.assign({},A)).Da=B(A.Da),A.fb=R(A.fb),A.hb=B(A.hb),A.tb=B(A.tb),A.ub=R(A.ub),A.__cxa_get_exception_ptr=B(A.__cxa_get_exception_ptr),A}(),Ro.push(Y.ib),E=w,zo(),Y}Pt++;var l=Oo();if(n.instantiateWasm)return new Promise(y=>{n.instantiateWasm(l,(w,A)=>{s(w,A),y(w.exports)})});if(u)return new Promise(y=>{ve=w=>{var A=new WebAssembly.Instance(w,Oo());y(s(A,w))}});kt??=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",_):_+"ort-wasm-simd-threaded.jsep.wasm":new URL(/* asset import */ __webpack_require__(/*! ort-wasm-simd-threaded.jsep.wasm */ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"), __webpack_require__.b).href;try{var h=await async function(y){var w=kt;if(!j&&typeof WebAssembly.instantiateStreaming=="function"&&!X(w))try{var A=fetch(w,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(A,y)}catch(B){x(`wasm streaming compile failed: ${B}`),x("falling back to ArrayBuffer instantiation")}return async function(B,R){try{var G=await async function(K){if(!j)try{var ae=await m(K);return new Uint8Array(ae)}catch{}if(K==kt&&j)K=new Uint8Array(j);else{if(!f)throw"both async and sync fetching of the wasm failed";K=f(K)}return K}(B);return await WebAssembly.instantiate(G,R)}catch(K){x(`failed to asynchronously prepare wasm: ${K}`),dt(K)}}(w,y)}(l);return s(h.instance,h.module)}catch(y){return r(y),Promise.reject(y)}})();var zi=s=>(zi=Y.Da)(s),Oi=()=>(Oi=Y.Ea)();n._OrtInit=(s,l)=>(n._OrtInit=Y.Fa)(s,l),n._OrtGetLastError=(s,l)=>(n._OrtGetLastError=Y.Ga)(s,l),n._OrtCreateSessionOptions=(s,l,h,y,w,A,B,R,G,K)=>(n._OrtCreateSessionOptions=Y.Ha)(s,l,h,y,w,A,B,R,G,K),n._OrtAppendExecutionProvider=(s,l,h,y,w)=>(n._OrtAppendExecutionProvider=Y.Ia)(s,l,h,y,w),n._OrtAddFreeDimensionOverride=(s,l,h)=>(n._OrtAddFreeDimensionOverride=Y.Ja)(s,l,h),n._OrtAddSessionConfigEntry=(s,l,h)=>(n._OrtAddSessionConfigEntry=Y.Ka)(s,l,h),n._OrtReleaseSessionOptions=s=>(n._OrtReleaseSessionOptions=Y.La)(s),n._OrtCreateSession=(s,l,h)=>(n._OrtCreateSession=Y.Ma)(s,l,h),n._OrtReleaseSession=s=>(n._OrtReleaseSession=Y.Na)(s),n._OrtGetInputOutputCount=(s,l,h)=>(n._OrtGetInputOutputCount=Y.Oa)(s,l,h),n._OrtGetInputOutputMetadata=(s,l,h,y)=>(n._OrtGetInputOutputMetadata=Y.Pa)(s,l,h,y),n._OrtFree=s=>(n._OrtFree=Y.Qa)(s),n._OrtCreateTensor=(s,l,h,y,w,A)=>(n._OrtCreateTensor=Y.Ra)(s,l,h,y,w,A),n._OrtGetTensorData=(s,l,h,y,w)=>(n._OrtGetTensorData=Y.Sa)(s,l,h,y,w),n._OrtReleaseTensor=s=>(n._OrtReleaseTensor=Y.Ta)(s),n._OrtCreateRunOptions=(s,l,h,y)=>(n._OrtCreateRunOptions=Y.Ua)(s,l,h,y),n._OrtAddRunConfigEntry=(s,l,h)=>(n._OrtAddRunConfigEntry=Y.Va)(s,l,h),n._OrtReleaseRunOptions=s=>(n._OrtReleaseRunOptions=Y.Wa)(s),n._OrtCreateBinding=s=>(n._OrtCreateBinding=Y.Xa)(s),n._OrtBindInput=(s,l,h)=>(n._OrtBindInput=Y.Ya)(s,l,h),n._OrtBindOutput=(s,l,h,y)=>(n._OrtBindOutput=Y.Za)(s,l,h,y),n._OrtClearBoundOutputs=s=>(n._OrtClearBoundOutputs=Y._a)(s),n._OrtReleaseBinding=s=>(n._OrtReleaseBinding=Y.$a)(s),n._OrtRunWithBinding=(s,l,h,y,w)=>(n._OrtRunWithBinding=Y.ab)(s,l,h,y,w),n._OrtRun=(s,l,h,y,w,A,B,R)=>(n._OrtRun=Y.bb)(s,l,h,y,w,A,B,R),n._OrtEndProfiling=s=>(n._OrtEndProfiling=Y.cb)(s),n._JsepOutput=(s,l,h)=>(n._JsepOutput=Y.db)(s,l,h),n._JsepGetNodeName=s=>(n._JsepGetNodeName=Y.eb)(s);var cr=()=>(cr=Y.fb)(),Qe=n._free=s=>(Qe=n._free=Y.gb)(s),pr=n._malloc=s=>(pr=n._malloc=Y.hb)(s),An=(s,l,h,y,w,A)=>(An=Y.kb)(s,l,h,y,w,A),Bi=()=>(Bi=Y.lb)(),Di=(s,l,h,y,w)=>(Di=Y.mb)(s,l,h,y,w),Mi=s=>(Mi=Y.nb)(s),En=s=>(En=Y.ob)(s),Ri=(s,l)=>(Ri=Y.pb)(s,l),Ui=()=>(Ui=Y.qb)(),Ni=(s,l)=>(Ni=Y.rb)(s,l),mr=s=>(mr=Y.sb)(s),kn=s=>(kn=Y.tb)(s),Pn=()=>(Pn=Y.ub)(),Vi=n.dynCall_ii=(s,l)=>(Vi=n.dynCall_ii=Y.vb)(s,l),Wi=s=>(Wi=Y.wb)(s),Li=()=>(Li=Y.xb)(),Gi=s=>(Gi=Y.yb)(s),Hi=()=>(Hi=Y.zb)();return n.stackSave=()=>Pn(),n.stackRestore=s=>mr(s),n.stackAlloc=s=>kn(s),n.setValue=function(s,l,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":ue()[s>>>0]=l;break;case"i16":ye()[s>>>1>>>0]=l;break;case"i32":C()[s>>>2>>>0]=l;break;case"i64":Z[s>>>3]=BigInt(l);break;case"float":de()[s>>>2>>>0]=l;break;case"double":ze()[s>>>3>>>0]=l;break;case"*":V()[s>>>2>>>0]=l;break;default:dt(`invalid type for setValue: ${h}`)}},n.getValue=function(s,l="i8"){switch(l.endsWith("*")&&(l="*"),l){case"i1":case"i8":return ue()[s>>>0];case"i16":return ye()[s>>>1>>>0];case"i32":return C()[s>>>2>>>0];case"i64":return Z[s>>>3];case"float":return de()[s>>>2>>>0];case"double":return ze()[s>>>3>>>0];case"*":return V()[s>>>2>>>0];default:dt(`invalid type for getValue: ${l}`)}},n.UTF8ToString=Te,n.stringToUTF8=zt,n.lengthBytesUTF8=Ko,function s(){if(0{"use strict";yr();Ea=typeof location>"u"?void 0:location.origin,Gn=import.meta.url>"file:"&&import.meta.url<"file;",jp=()=>{if(true){if(Gn){let e=URL;return new URL(new e(/* asset import */ __webpack_require__(/*! ort.bundle.min.mjs */ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?46eb"), __webpack_require__.b).href,Ea).href}return import.meta.url}},Ue=jp(),ka=()=>{if(Ue&&!Ue.startsWith("blob:"))return Ue.substring(0,Ue.lastIndexOf("/")+1)},Ln=(e,t)=>{try{let r=t??Ue;return(r?new URL(e,r):new URL(e)).origin===Ea}catch{return!1}},Kp=(e,t)=>{let r=t??Ue;try{return(r?new URL(e,r):new URL(e)).href}catch{return}},Zp=(e,t)=>`${t??"./"}${e}`,Pa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Qp=async e=>(await import(/*webpackIgnore:true*/e)).default,Ca=(xa(),Ft($a)).default,za=async()=>{if(!Ue)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ln(Ue))return[void 0,Ca()];let e=await Pa(Ue);return[e,Ca(e)]},Aa=(Ia(),Ft(Ta)).default,Oa=async(e,t,r)=>{if(!e&&!t&&Aa&&Ue&&Ln(Ue))return[void 0,Aa];{let n="ort-wasm-simd-threaded.jsep.mjs",o=e??Kp(n,t),i= true&&r&&o&&!Ln(o,t),a=i?await Pa(o):o??Zp(n,t);return[i?a:void 0,await Qp(a)]}}});var Hn,Fn,Ar,Ba,Yp,Xp,Jp,wr,fe,ht=U(()=>{"use strict";_r();Fn=!1,Ar=!1,Ba=!1,Yp=()=>{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}},Xp=()=>{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}},Jp=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},wr=async e=>{if(Fn)return Promise.resolve();if(Ar)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ba)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ar=!0;let t=e.initTimeout,r=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Jp())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Xp())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=Yp();r>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+r+", 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=r=1);let o=e.wasmPaths,i=typeof o=="string"?o:void 0,a=o?.mjs,u=a?.href??a,d=o?.wasm,c=d?.href??d,p=e.wasmBinary,[m,f]=await Oa(u,i,r>1),b=!1,g=[];if(t>0&&g.push(new Promise(_=>{setTimeout(()=>{b=!0,_()},t)})),g.push(new Promise((_,S)=>{let $={numThreads:r};if(p)$.wasmBinary=p;else if(c||i)$.locateFile=v=>c??i+v;else if(u&&u.indexOf("blob:")!==0)$.locateFile=v=>new URL(v,u).href;else if(m){let v=ka();v&&($.locateFile=x=>v+x)}f($).then(v=>{Ar=!1,Fn=!0,Hn=v,_(),m&&URL.revokeObjectURL(m)},v=>{Ar=!1,Ba=!0,S(v)})})),await Promise.race(g),b)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},fe=()=>{if(Fn&&Hn)return Hn;throw new Error("WebAssembly is not initialized yet.")}});var Ne,Kt,pe,Er=U(()=>{"use strict";ht();Ne=(e,t)=>{let r=fe(),n=r.lengthBytesUTF8(e)+1,o=r._malloc(n);return r.stringToUTF8(e,o,n),t.push(o),o},Kt=(e,t,r,n)=>{if(typeof e=="object"&&e!==null){if(r.has(e))throw new Error("Circular reference in options");r.add(e)}Object.entries(e).forEach(([o,i])=>{let a=t?t+o:o;if(typeof i=="object")Kt(i,a+".",r,n);else if(typeof i=="string"||typeof i=="number")n(a,i.toString());else if(typeof i=="boolean")n(a,i?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof i}`)})},pe=e=>{let t=fe(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetLastError(o,o+n);let i=Number(t.getValue(o,n===4?"i32":"i64")),a=t.getValue(o+n,"*"),u=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${u}`)}finally{t.stackRestore(r)}}});var Da,Ma=U(()=>{"use strict";ht();Er();Da=e=>{let t=fe(),r=0,n=[],o=e||{};try{if(e?.logSeverityLevel===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(o.terminate=!1);let i=0;return e?.tag!==void 0&&(i=Ne(e.tag,n)),r=t._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,i),r===0&&pe("Can't create run options."),e?.extra!==void 0&&Kt(e.extra,"",new WeakSet,(a,u)=>{let d=Ne(a,n),c=Ne(u,n);t._OrtAddRunConfigEntry(r,d,c)!==0&&pe(`Can't set a run config entry: ${a} - ${u}.`)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseRunOptions(r),n.forEach(a=>t._free(a)),i}}});var em,tm,rm,kr,nm,Ra,Ua=U(()=>{"use strict";ht();Er();em=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}`)}},tm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},rm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(r=>(typeof r=="string"?r:r.name)==="webgpu")&&(e.enableMemPattern=!1)},kr=(e,t,r,n)=>{let o=Ne(t,n),i=Ne(r,n);fe()._OrtAddSessionConfigEntry(e,o,i)!==0&&pe(`Can't set a session config entry: ${t} - ${r}.`)},nm=async(e,t,r)=>{for(let n of t){let o=typeof n=="string"?n:n.name,i=[];switch(o){case"webnn":if(o="WEBNN",typeof n!="string"){let m=n?.deviceType;m&&kr(e,"deviceType",m,r)}break;case"webgpu":if(o="JS",typeof n!="string"){let p=n;if(p?.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);kr(e,"preferredLayout",p.preferredLayout,r)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let a=Ne(o,r),u=i.length,d=0,c=0;if(u>0){d=fe()._malloc(u*fe().PTR_SIZE),r.push(d),c=fe()._malloc(u*fe().PTR_SIZE),r.push(c);for(let p=0;p{let t=fe(),r=0,n=[],o=e||{};rm(o);try{let i=em(o.graphOptimizationLevel??"all"),a=tm(o.executionMode??"sequential"),u=typeof o.logId=="string"?Ne(o.logId,n):0,d=o.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let c=o.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof o.optimizedModelFilePath=="string"?Ne(o.optimizedModelFilePath,n):0;if(r=t._OrtCreateSessionOptions(i,!!o.enableCpuMemArena,!!o.enableMemPattern,a,!!o.enableProfiling,0,u,d,c,p),r===0&&pe("Can't create session options."),o.executionProviders&&await nm(r,o.executionProviders,n),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);kr(r,"enableGraphCapture",o.enableGraphCapture.toString(),n)}if(o.freeDimensionOverrides)for(let[m,f]of Object.entries(o.freeDimensionOverrides)){if(typeof m!="string")throw new Error(`free dimension override name must be a string: ${m}`);if(typeof f!="number"||!Number.isInteger(f)||f<0)throw new Error(`free dimension override value must be a non-negative integer: ${f}`);let b=Ne(m,n);t._OrtAddFreeDimensionOverride(r,b,f)!==0&&pe(`Can't set a free dimension override: ${m} - ${f}.`)}return o.extra!==void 0&&Kt(o.extra,"",new WeakSet,(m,f)=>{kr(r,m,f,n)}),[r,n]}catch(i){throw r!==0&&t._OrtReleaseSessionOptions(r)!==0&&pe("Can't release session options."),n.forEach(a=>t._free(a)),i}}});var Mt,Ye,gt,Pr,Zt,zr,Or,qn,ee=U(()=>{"use strict";Mt=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}`)}},Ye=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}`)}},gt=(e,t)=>{let r=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((o,i)=>o*i,1);return r>0?Math.ceil(n*r):void 0},Pr=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}`)}},Zt=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}`)}},zr=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Or=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",qn=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}`)}}});var Qt,jn=U(()=>{"use strict";yr();Qt=async e=>{if(typeof e=="string")if(false){}else{let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let r=t.headers.get("Content-Length"),n=r?parseInt(r,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=t.body.getReader(),i;try{i=new ArrayBuffer(n)}catch(u){if(u instanceof RangeError){let d=Math.ceil(n/65536);i=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw u}let a=0;for(;;){let{done:u,value:d}=await o.read();if(u)break;let c=d.byteLength;new Uint8Array(i,a,c).set(d),a+=c}return new Uint8Array(i,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}});var om,im,Na,Va,Br,am,se,Xe=U(()=>{"use strict";ee();om=["V","I","W","E","F"],im=(e,t)=>{console.log(`[${om[e]},${new Date().toISOString()}]${t}`)},Br=(e,t)=>{Na=e,Va=t},am=(e,t)=>{let r=Zt(e),n=Zt(Na);r>=n&&im(r,typeof t=="function"?t():t)},se=(...e)=>{Va&&am(...e)}});var Kn,Je,k,Tt,Dr,Wa,La,ne=U(()=>{"use strict";Kn=class{static calcMatMulShape(t,r){return t[1]!==r[0]?void 0:[t[0],r[1]]}},Je=class{static calcShape(t,r,n=!1){let o=t.length,i=r.length;if(o===0)return r;if(i===0)return t;let a=Math.max(t.length,r.length),u=new Array(a);if(n){if(o<2||i<2)return;let d=Kn.calcMatMulShape([t[o-2],t[o-1]],[r[i-2],r[i-1]]);if(d===void 0)return;[u[a-2],u[a-1]]=d}for(let d=n?3:1;d<=a;d++){let c=o-d<0?1:t[o-d],p=i-d<0?1:r[i-d];if(c!==p&&c>1&&p>1)return;let m=Math.max(c,p);if(c&&p)u[a-d]=Math.max(c,p);else{if(m>1)return;u[a-d]=0}}return u}static isValidBroadcast(t,r){let n=t.length,o=r.length;if(n>o)return!1;for(let i=1;i<=n;i++)if(t[n-i]!==1&&t[n-i]!==r[o-i])return!1;return!0}},k=class e{static size(t){return e.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,r=4){let n=t.length;if(n===0)return[];let o=new Array(n),i=n-1;for(;i>=0;){if(t[i]%r===0){o[i]=t[i]/r;break}if(r%t[i]!==0)throw new Error("cannot convert shape");o[i]=1,r/=t[i],i--}for(i--;i>=0;i--)o[i]=t[i];return o}static sizeFromDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,r,t.length)}static sizeToDimension(t,r){if(r<0||r>t.length)throw new Error(`invalid dimension of ${r} for sizeToDimension as Tensor has ${t.length} dimensions.`);return e.getSizeFromDimensionRange(t,0,r)}static getSizeFromDimensionRange(t,r,n){let o=1;for(let i=r;i=0;--o)n[o]=n[o+1]*t[o+1];return n}static normalizeAxis(t,r){if(t<-r&&t>=r)throw new Error("unsupported axis for this operation.");return t<0?t+r:t}static normalizeAxes(t,r){return t.map(n=>this.normalizeAxis(n,r??t.length))}static sortBasedOnPerm(t,r){return r?r.map(n=>t[n]):t.slice().reverse()}static padShape(t,r){let n=t.length;return t.map((o,i)=>o+r[i]+r[i+n])}static areEqual(t,r){return t.length!==r.length?!1:t.every((n,o)=>n===r[o])}},Tt=class e{static adjustPoolAttributes(t,r,n,o,i,a){if(!t&&n.length!==r.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let u=0;u=n.length?n.push(r[u+2]):n[u]=r[u+2];for(let u=0;u=n[u]||a[u+n.length]>=n[u])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,r,n,o,i,a,u){if(u){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{"use strict";ee();Mr=(e,t)=>new(Pr(t))(e)});var Yn,Ha,sm,Ga,um,Fa,Rr,Ur,Qn,qa,ja=U(()=>{"use strict";Xe();Yn=(e,t=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let r=e.byteLength/8,n=new BigInt64Array(e.buffer,e.byteOffset,r),o=new Int32Array(r);for(let i=0;i2147483647n||a<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${i}: ${a}`);o[i]=Number(a)}return t?new Uint8Array(o.buffer):o},Ha=(e,t=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let r=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,r),o=BigInt64Array.from(n,BigInt);return t?new Uint8Array(o.buffer):o},sm=1,Ga=()=>sm++,um=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Fa=(e,t)=>{let r=um.get(e);if(!r)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,o)=>n*o)*r/8):0},Rr=class{constructor(t){this.shouldConvertInt64toInt32=!1;this.isInt64ToInt32Converted=!1;let{sessionId:r,context:n,tensor:o,dataType:i,shape:a,shouldConvertInt64toInt32:u=!1}=t;this.sessionId=r,this.mlContext=n,this.mlTensor=o,this.dataType=i,this.tensorShape=a,this.shouldConvertInt64toInt32=u}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Fa(this.dataType,this.tensorShape)}destroy(){se("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(t){this.mlContext.writeTensor(this.mlTensor,t)}async read(t,r){if(t){let n=await this.mlContext.readTensor(this.mlTensor),o=Ha(new Uint8Array(n));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(o);return}else return o.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(t,r,n){return this.mlContext===t&&this.dataType===r&&this.tensorShape.length===n.length&&this.tensorShape.every((o,i)=>o===n[i])}setIsInt64ToInt32Converted(t){this.isInt64ToInt32Converted=t}},Ur=class{constructor(t,r){this.tensorManager=t;this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(t,r,n,o){let i=r,a=this.tensorManager.getMLContext(t),u=i==="int64"&&!a.opSupportLimits().input.dataTypes.includes("int64");if(u&&(i="int32",se("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(a,i,n))return this.wrapper.tensor;if(o){if(this.wrapper.byteLength!==Fa(i,n))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 d=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(t,i,n,d,!0,!0,u),o&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(t){let r=t;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=Yn(t,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else se("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(t){if(this.activeUpload){let r=this.wrapper?.isInt64ToInt32Converted?Ha(this.activeUpload):this.activeUpload;if(t){t instanceof ArrayBuffer?new Uint8Array(t).set(r):new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(r);return}else return r.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return t?this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32,t):this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32)}},Qn=class{constructor(t){this.backend=t;this.tensorTrackersById=new Map;this.freeTensors=[];this.externalTensors=new Set}getMLContext(t){let r=this.backend.getMLContext(t);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let t=Ga();return this.tensorTrackersById.set(t,new Ur(this)),t}releaseTensorId(t){let r=this.tensorTrackersById.get(t);r&&(this.tensorTrackersById.delete(t),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(t,r,n,o,i){se("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${n}, shape: ${o}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(r);if(!a)throw new Error("Tensor not found.");return a.ensureTensor(t,n,o,i)}upload(t,r){let n=this.tensorTrackersById.get(t);if(!n)throw new Error("Tensor not found.");n.upload(r)}async download(t,r){se("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${t}, dstBuffer: ${r?.byteLength}}`);let n=this.tensorTrackersById.get(t);if(!n)throw new Error("Tensor not found.");return n.download(r)}releaseTensorsForSession(t){for(let r of this.freeTensors)r.sessionId===t&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==t)}registerTensor(t,r,n,o){let i=this.getMLContext(t),a=Ga(),u=new Rr({sessionId:t,context:i,tensor:r,dataType:n,shape:o});return this.tensorTrackersById.set(a,new Ur(this,u)),this.externalTensors.add(u),a}async getCachedTensor(t,r,n,o,i,a,u=!1){let d=this.getMLContext(t);for(let[p,m]of this.freeTensors.entries())if(m.canReuseTensor(d,r,n)){se("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${n}}`);let f=this.freeTensors.splice(p,1)[0];return f.sessionId=t,f}se("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${n}}`);let c=await d.createTensor({dataType:r,shape:n,dimensions:n,usage:o,writable:i,readable:a});return new Rr({sessionId:t,context:d,tensor:c,dataType:r,shape:n,shouldConvertInt64toInt32:u})}releaseTensor(t){this.externalTensors.has(t)&&this.externalTensors.delete(t),this.freeTensors.push(t)}},qa=(...e)=>new Qn(...e)});var Xn,dm,Nr,Ka=U(()=>{"use strict";ee();ht();Zn();ja();Xe();Xn=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),dm=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let r=Object.keys(e).sort(),n=Object.keys(t).sort();return r.length===n.length&&r.every((o,i)=>o===n[i]&&e[o]===t[o])},Nr=class{constructor(t){this.tensorManager=qa(this);this.mlContextBySessionId=new Map;this.sessionIdsByMLContext=new Map;this.mlContextCache=[];this.sessionGraphInputs=new Map;this.temporaryGraphInputs=[];this.temporarySessionTensorIds=new Map;Br(t.logLevel,!!t.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(t){se("verbose",()=>`[WebNN] onRunStart {sessionId: ${t}}`),this.activeSessionId=t}onRunEnd(t){se("verbose",()=>`[WebNN] onRunEnd {sessionId: ${t}}`);let r=this.temporarySessionTensorIds.get(t);if(r){for(let n of r)se("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(t),this.activeSessionId=void 0}}async createMLContext(t){if(t instanceof GPUDevice){let n=this.mlContextCache.findIndex(o=>o.gpuDevice===t);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext(t);return this.mlContextCache.push({gpuDevice:t,mlContext:o}),o}}else if(t===void 0){let n=this.mlContextCache.findIndex(o=>o.options===void 0&&o.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let o=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:o}),o}}let r=this.mlContextCache.findIndex(n=>dm(n.options,t));if(r!==-1)return this.mlContextCache[r].mlContext;{let n=await navigator.ml.createContext(t);return this.mlContextCache.push({options:t,mlContext:n}),n}}registerMLContext(t,r){this.mlContextBySessionId.set(t,r);let n=this.sessionIdsByMLContext.get(r);n||(n=new Set,this.sessionIdsByMLContext.set(r,n)),n.add(t),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(t,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(t){this.sessionGraphInputs.delete(t);let r=this.mlContextBySessionId.get(t);if(!r)return;this.tensorManager.releaseTensorsForSession(t),this.mlContextBySessionId.delete(t);let n=this.sessionIdsByMLContext.get(r);if(n.delete(t),n.size===0){this.sessionIdsByMLContext.delete(r);let o=this.mlContextCache.findIndex(i=>i.mlContext===r);o!==-1&&this.mlContextCache.splice(o,1)}}getMLContext(t){return this.mlContextBySessionId.get(t)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(t){se("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t)}async ensureTensor(t,r,n,o,i){let a=Xn.get(n);if(!a)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(t??this.currentSessionId,r,a,o,i)}async createTemporaryTensor(t,r,n){se("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${n}}`);let o=Xn.get(r);if(!o)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(t,i,o,n,!1);let a=this.temporarySessionTensorIds.get(t);return a?a.push(i):this.temporarySessionTensorIds.set(t,[i]),i}uploadTensor(t,r){if(!fe().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");se("verbose",()=>`[WebNN] uploadTensor {tensorId: ${t}, data: ${r.byteLength}}`),this.tensorManager.upload(t,r)}async downloadTensor(t,r){return this.tensorManager.download(t,r)}createMLTensorDownloader(t,r){return async()=>{let n=await this.tensorManager.download(t);return Mr(n,r)}}registerMLTensor(t,r,n,o){let i=Xn.get(n);if(!i)throw new Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(t,r,i,o);return se("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${o}} -> {tensorId: ${a}}`),a}registerMLConstant(t,r,n,o,i,a,u=!1){if(!a)throw new Error("External mounted files are not available.");let d=t;t.startsWith("./")&&(d=t.substring(2));let c=a.get(d);if(!c)throw new Error(`File with name ${d} not found in preloaded files.`);if(r+n>c.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let p=c.slice(r,r+n).buffer,m;switch(i.dataType){case"float32":m=new Float32Array(p);break;case"float16":m=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(p):new Uint16Array(p);break;case"int32":m=new Int32Array(p);break;case"uint32":m=new Uint32Array(p);break;case"int64":u?(m=Yn(new Uint8Array(p),!1),i.dataType="int32"):m=new BigInt64Array(p);break;case"uint64":m=new BigUint64Array(p);break;case"int8":m=new Int8Array(p);break;case"int4":case"uint4":case"uint8":m=new Uint8Array(p);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return se("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${u?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),o.constant(i,m)}registerGraphInput(t){this.temporaryGraphInputs.push(t)}isGraphInput(t,r){let n=this.sessionGraphInputs.get(t);return n?n.includes(r):!1}isInt64Supported(t){return!!this.mlContextBySessionId.get(t)?.opSupportLimits().input.dataTypes.includes("int64")}flush(){}}});var Vr=U(()=>{"use strict"});var Za,Jn,eo,lm,cm,Qa,ro,to,Xa,Ja=U(()=>{"use strict";Xe();Vr();Za=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]]),Jn=[],eo=e=>Math.ceil(Number(e)/16)*16,lm=e=>{for(let t=0;tcm++,ro=async(e,t,r,n)=>{let o=eo(r),i=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,i,0,o),e.flush(),await i.mapAsync(GPUMapMode.READ);let u=i.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(u,0,r)),d}else return new Uint8Array(u.slice(0,r))}finally{i.destroy()}},to=class{constructor(t){this.backend=t;this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of Za)Jn.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(t,r){let n=r.buffer,o=r.byteOffset,i=r.byteLength,a=eo(i),u=this.storageCache.get(t);if(!u)throw new Error("gpu data for uploading does not exist");if(Number(u.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${u.originalSize}, data size=${i}`);let d=this.backend.device.createBuffer({mappedAtCreation:!0,size:a,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),c=d.getMappedRange();new Uint8Array(c).set(new Uint8Array(n,o,i)),d.unmap();let p=this.backend.device.createCommandEncoder();p.copyBufferToBuffer(d,0,u.gpuData.buffer,0,a),this.backend.device.queue.submit([p.finish()]),d.destroy(),se("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${t})`)}memcpy(t,r){let n=this.storageCache.get(t);if(!n)throw new Error("source gpu data for memcpy does not exist");let o=this.storageCache.get(r);if(!o)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==o.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=eo(n.originalSize),a=this.backend.getCommandEncoder();this.backend.endComputePass(),a.copyBufferToBuffer(n.gpuData.buffer,0,o.gpuData.buffer,0,i)}registerExternalBuffer(t,r,n){let o;if(n){if(o=n[0],t===n[1])return se("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, buffer is the same, skip.`),o;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 o=Qa();return this.storageCache.set(o,{gpuData:{id:o,type:0,buffer:t},originalSize:r}),se("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${o}, registered.`),o}unregisterExternalBuffer(t){t!==void 0&&(this.storageCache.delete(t),se("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${t}`))}create(t,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=lm(t),o,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,a=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||a){let c=(i?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?o=c.pop():o=this.backend.device.createBuffer({size:n,usage:r}):o=this.backend.device.createBuffer({size:n,usage:r})}else o=this.backend.device.createBuffer({size:n,usage:r});let u={id:Qa(),type:0,buffer:o};return this.storageCache.set(u.id,{gpuData:u,originalSize:Number(t)}),se("verbose",()=>`[WebGPU] GpuDataManager.create(size=${t}) => id=${u.id}`),u}get(t){return this.storageCache.get(t)?.gpuData}release(t){let r=typeof t=="bigint"?Number(t):t,n=this.storageCache.get(r);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return se("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(t,r){let n=this.storageCache.get(Number(t));if(!n)throw new Error("data does not exist");await ro(this.backend,n.gpuData.buffer,n.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let t of this.buffersPending){let r=Za.get(t.size);if((t.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else if((t.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(t.size)||[];r===void 0||n.length>=r?t.destroy():n.push(t)}else t.destroy()}this.buffersPending=[]}else{let t=this.capturedPendingBuffers.get(this.backend.currentSessionId);t||(t=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,t));for(let r of this.buffersPending)t.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(t=>{t.forEach(r=>{r.destroy()})}),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(t=>{t.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(t){let r=this.capturedPendingBuffers.get(t);r&&(r.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(t)),this.sessionCount-=1,this.sessionCount===0&&(se("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Xa=(...e)=>new to(...e)});var no,J,Se=U(()=>{"use strict";no=class{constructor(t){Object.assign(this,t)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(t=>`${this[t]}`).join(";")),this.key}},J=e=>new no(e)});var It,io,be,Ae,N,ce,ao,Ct,He,F,Wr,P,M,es,Lr,oo,ts,ie=U(()=>{"use strict";ee();ne();It=64,io=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},be=(e,t=1)=>{let r=io(e,t);return typeof r=="string"?r:r[0]},Ae=(e,t=1)=>{let r=io(e,t);return typeof r=="string"?r:r[1]},N=(...e)=>{let t=[];return e.forEach(r=>{r.length!==0&&t.push({type:12,data:r},{type:12,data:k.computeStrides(r)})}),t},ce=e=>e%4===0?4:e%2===0?2:1,ao=(e="f32",t,r="0")=>!t||t===1?`${e}(${r})`:`vec${t}<${e}>(${r})`,Ct=(e,t,r)=>e==="f32"?r:t===1?`f32(${r})`:`vec${t}(${r})`,He=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,F=(e,t,r,n)=>e.startsWith("uniforms.")&&r>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:r>1?`${e}[${t}]`:e,Wr=(e,t,r,n,o)=>{let i=typeof r=="number",a=i?r:r.length,u=[...new Array(a).keys()],d=a<2?"u32":a<=4?`vec${a}`:`array`,c=io(t,o),p=typeof c=="string"?c:c[1],m=typeof c=="string"?c:c[0],f={indices:d,value:p,storage:m,tensor:t},b=C=>typeof C=="string"?C:`${C}u`,g={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},_=i?"uniforms.":"",S=`${_}${e}_shape`,$=`${_}${e}_strides`,v="";for(let C=0;C ${f.indices} { - var indices: ${f.indices}; - var current = offset; - ${v} - return indices; - }`,T=C=>(g.offsetToIndices=!0,a<2?C:`o2i_${e}(${C})`),E=[];if(a>=2)for(let C=a-1;C>=0;C--)E.push(`${F($,C,a)} * (indices[${C}])`);let I=a<2?"":` - fn i2o_${e}(indices: ${f.indices}) -> u32 { - return ${E.join("+")}; - }`,z=C=>(g.indicesToOffset=!0,a<2?C:`i2o_${e}(${C})`),O=(...C)=>a===0?"0u":`${f.indices}(${C.map(b).join(",")})`,D=(C,V)=>a<2?`${C}`:`${F(C,V,a)}`,L=(C,V,de)=>a<2?`${C}=${de};`:`${F(C,V,a)}=${de};`,q={},Q=(C,V)=>{g.broadcastedIndicesToOffset=!0;let de=`${V.name}broadcastedIndicesTo${e}Offset`;if(de in q)return`${de}(${C})`;let ze=[];for(let ve=a-1;ve>=0;ve--){let $e=V.indicesGet("outputIndices",ve+V.rank-a);ze.push(`${D($,ve)} * (${$e} % ${D(S,ve)})`)}return q[de]=`fn ${de}(outputIndices: ${V.type.indices}) -> u32 { - return ${ze.length>0?ze.join("+"):"0u"}; - }`,`${de}(${C})`},W=(C,V)=>(()=>{if(f.storage===f.value)return`${e}[${C}]=${V};`;if(f.storage==="vec2"&&f.value==="i32")return`${e}[${C}]=vec2(u32(${V}), select(0u, 0xFFFFFFFFu, ${V} < 0));`;if(f.storage==="vec2"&&f.value==="u32")return`${e}[${C}]=vec2(u32(${V}), 0u);`;if(f.storage==="u32"&&f.value==="vec4")return`${e}[${C}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${V}));`;throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`)})(),Z=C=>(()=>{if(f.storage===f.value)return`${e}[${C}]`;if(f.storage==="vec2"&&f.value==="i32")return`i32(${e}[${C}].x)`;if(f.storage==="vec2"&&f.value==="u32")return`u32(${e}[${C}].x)`;if(f.storage==="u32"&&f.value==="vec4")return`vec4(bool(${e}[${C}] & 0xFFu), bool(${e}[${C}] & 0xFF00u), bool(${e}[${C}] & 0xFF0000u), bool(${e}[${C}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${f.storage} and value type ${f.value} yet`)})(),we=a<2?"":` - fn get_${e}ByIndices(indices: ${f.indices}) -> ${p} { - return ${Z(`i2o_${e}(indices)`)}; - }`,H=a<2?"":(()=>{let C=u.map(de=>`d${de}: u32`).join(", "),V=u.map(de=>`d${de}`).join(", ");return` - fn get_${e}(${C}) -> ${p} { - return get_${e}ByIndices(${O(V)}); - }`})(),j=(...C)=>{if(C.length!==a)throw new Error(`indices length must be ${a}`);let V=C.map(b).join(",");return a===0?Z("0u"):a===1?Z(V[0]):(g.get=!0,g.getByIndices=!0,g.indicesToOffset=!0,`get_${e}(${V})`)},te=C=>a<2?Z(C):(g.getByIndices=!0,g.indicesToOffset=!0,`get_${e}ByIndices(${C})`),X=a<2?"":` - fn set_${e}ByIndices(indices: ${f.indices}, value: ${p}) { - ${W(`i2o_${e}(indices)`,"value")} - }`,ue=a<2?"":(()=>{let C=u.map(de=>`d${de}: u32`).join(", "),V=u.map(de=>`d${de}`).join(", ");return` - fn set_${e}(${C}, value: ${p}) { - set_${e}ByIndices(${O(V)}, value); - }`})();return{impl:()=>{let C=[],V=!1;return g.offsetToIndices&&(C.push(x),V=!0),g.indicesToOffset&&(C.push(I),V=!0),g.broadcastedIndicesToOffset&&(Object.values(q).forEach(de=>C.push(de)),V=!0),g.set&&(C.push(ue),V=!0),g.setByIndices&&(C.push(X),V=!0),g.get&&(C.push(H),V=!0),g.getByIndices&&(C.push(we),V=!0),!i&&V&&C.unshift(`const ${S} = ${f.indices}(${r.join(",")});`,`const ${$} = ${f.indices}(${k.computeStrides(r).join(",")});`),C.join(` -`)},type:f,offsetToIndices:T,indicesToOffset:z,broadcastedIndicesToOffset:Q,indices:O,indicesGet:D,indicesSet:L,set:(...C)=>{if(C.length!==a+1)throw new Error(`indices length must be ${a}`);let V=C[a];if(typeof V!="string")throw new Error("value must be string");let de=C.slice(0,a).map(b).join(",");return a===0?W("0u",V):a===1?W(de[0],V):(g.set=!0,g.setByIndices=!0,g.indicesToOffset=!0,`set_${e}(${de}, ${V})`)},setByOffset:W,setByIndices:(C,V)=>a<2?W(C,V):(g.setByIndices=!0,g.indicesToOffset=!0,`set_${e}ByIndices(${C}, ${V});`),get:j,getByOffset:Z,getByIndices:te,usage:n,name:e,strides:$,shape:S,rank:a}},P=(e,t,r,n=1)=>Wr(e,t,r,"input",n),M=(e,t,r,n=1)=>Wr(e,t,r,"output",n),es=(e,t,r)=>Wr(e,t,r,"atomicOutput",1),Lr=(e,t,r,n=1)=>Wr(e,t,r,"internal",n),oo=class{constructor(t,r){this.normalizedDispatchGroup=t;this.limits=r;this.internalVariables=[];this.variables=[];this.uniforms=[];this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(t){return`if (global_idx >= ${typeof t=="number"?`${t}u`:t}) { return; }`}mainStart(t=It){let r=typeof t=="number"?t:t[0],n=typeof t=="number"?1:t[1],o=typeof t=="number"?1:t[2];if(r>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||o>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*n*o>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${n}, ${o}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,a=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`,u=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*n*o}u + local_idx;`;return`@compute @workgroup_size(${r}, ${n}, ${o}) - fn main(${a}) { - ${u} - `}appendVariableUniforms(t){t.rank!==0&&(t.shape.startsWith("uniforms.")&&this.uniforms.push({name:t.shape.replace("uniforms.",""),type:"u32",length:t.rank}),t.strides.startsWith("uniforms.")&&this.uniforms.push({name:t.strides.replace("uniforms.",""),type:"u32",length:t.rank}))}declareVariable(t,r){if(t.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(t),this.appendVariableUniforms(t);let n=t.usage==="input"?"read":"read_write",o=t.usage==="atomicOutput"?"atomic":t.type.storage;return`@group(0) @binding(${r}) var ${t.name}: array<${o}>;`}declareVariables(...t){return t.map(r=>this.declareVariable(r,this.variableIndex++)).join(` -`)}registerInternalVariable(t){if(t.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(t),this.appendVariableUniforms(t)}registerInternalVariables(...t){return t.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(t,r,n=1){return this.uniforms.push({name:t,type:r,length:n}),this}registerUniforms(t){return this.uniforms=this.uniforms.concat(t),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let t=[];for(let{name:r,type:n,length:o}of this.uniforms)if(o&&o>4)n==="f16"?t.push(`@align(16) ${r}:array, ${Math.ceil(o/8)}>`):t.push(`${r}:array, ${Math.ceil(o/4)}>`);else{let i=o==null||o===1?n:`vec${o}<${n}>`;t.push(`${r}:${i}`)}return` - struct Uniforms { ${t.join(", ")} }; - @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(t=>t.impl()).join(` -`)+this.internalVariables.map(t=>t.impl()).join(` -`)}get variablesInfo(){if(this.uniforms.length===0)return;let t=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[t(r.type),r.length??1])}},ts=(e,t)=>new oo(e,t)});var pm,rs,mm,fm,hm,gm,Ee,ns,os,st=U(()=>{"use strict";ee();ne();Se();ie();pm=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},rs=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),mm=(e,t)=>k.sortBasedOnPerm(e,rs(e.length,t)),fm=(e,t,r,n)=>{let o=`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { - var a: ${r.type.indices};`;for(let i=0;i{let r=[],n=[];for(let o=0;o{let r=0;for(let n=0;n{let r=e.dataType,n=e.dims.length,o=rs(n,t),i=mm(e.dims,o),a=e.dims,u=i,d=n<2||gm(o,e.dims),c;if(d)return c=_=>{let S=P("input",r,a,4),$=M("output",r,u,4);return` - ${_.registerUniform("output_size","u32").declareVariables(S,$)} - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:m}=hm(e.dims,o),f=k.areEqual(m,[2,3,1]),b=k.areEqual(m,[3,1,2]);if(p.length===2||f||b){a=f?[p[0],p[1]*p[2]]:b?[p[0]*p[1],p[2]]:p,u=[a[1],a[0]];let _=16;return c=S=>{let $=P("a",r,a.length),v=M("output",r,u.length);return` - ${S.registerUniform("output_size","u32").declareVariables($,v)} - var tile : array, ${_}>; - ${S.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] = ${$.getByIndices(`${$.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 S=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u[1]/_),y:Math.ceil(u[0]/_)},programUniforms:[{type:12,data:S},...N(a,u)]}},getShaderSource:c}}return c=_=>{let S=P("a",r,a.length),$=M("output",r,u.length);return` - ${_.registerUniform("output_size","u32").declareVariables(S,$)} - - ${fm(o,n,S,$)} - - ${_.mainStart()} - ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${$.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${$.setByOffset("global_idx",S.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let _=k.size(i);return{outputs:[{dims:i,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...N(a,u)]}},getShaderSource:c}},ns=(e,t)=>{pm(e.inputs,t.perm),e.compute(Ee(e.inputs[0],t.perm))},os=e=>J({perm:e.perm})});var bm,ym,_m,wm,vm,$m,xm,Sm,Tm,Im,et,is,as,ss,us,ds,ls,cs,ps,ms,fs,hs=U(()=>{"use strict";ee();ne();ie();Gr();st();bm={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"},ym={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"},_m={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},wm={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},vm=(e,t)=>{let r=[];for(let n=t-e;n{let r=[],n=e.length;for(let i=0;ie[i]);return[r,o]},xm=(e,t)=>{let r=e.length+t.length,n=[],o=0;for(let i=0;i{for(let r=0;r{let r=[];if(!Sm(e,t)){for(let n=0;nr.push(n))}return r},Im=(e,t,r,n,o,i,a)=>{let u=r[0].dims,d=k.size(i),c=k.size(a),p=P("_A",r[0].dataType,u),m=M("output",o,i),f=64;d===1&&(f=256);let b=` - var aBestValues : array; - `,g=_=>` - ${_.registerUniform("reduceSize","u32").declareVariables(p,m)} - ${b} - fn DIV_CEIL(a : u32, b : u32) -> u32 { - return ((a - 1u) / b + 1u); - } - ${_.mainStart(f)} - - let outputIndex = global_idx / ${f}; - let offset = outputIndex * uniforms.reduceSize; - - var bestValue = f32(${_m[n]}); - let Length = uniforms.reduceSize; - for (var k = local_idx; k < Length; k = k + ${f}) { - let candidate = f32(${p.getByOffset("offset + k")}); - bestValue = ${bm[n]}; - } - aBestValues[local_idx] = bestValue; - workgroupBarrier(); - - var reduceSize = min(Length, ${f}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 = ${ym[n]}; - aBestValues[local_idx] = bestValue; - } - reduceSize = interval; - workgroupBarrier(); - } - - if (local_idx == 0u) { - ${m.setByOffset("outputIndex",`${n==="mean"?`${m.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${m.type.storage}(${wm[n]})`}`)}; - } - }`;return{name:e,shaderCache:{hint:`${t};${f}`,inputDependencies:["type"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:d},programUniforms:[{type:12,data:c}]})}},et=(e,t,r,n)=>{let o=e.inputs.length===1?r:so(e.inputs,r),i=o.axes;i.length===0&&!o.noopWithEmptyAxes&&(i=e.inputs[0].dims.map((b,g)=>g));let a=k.normalizeAxes(i,e.inputs[0].dims.length),u=a,d=e.inputs[0],c=Tm(u,e.inputs[0].dims.length);c.length>0&&(d=e.compute(Ee(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],u=vm(u.length,d.dims.length));let[p,m]=$m(d.dims,u),f=p;o.keepDims&&(f=xm(p,a)),e.compute(Im(t,o.cacheKey,[d],n,e.inputs[0].dataType,f,m),{inputs:[d]})},is=(e,t)=>{et(e,"ReduceMeanShared",t,"mean")},as=(e,t)=>{et(e,"ReduceL1Shared",t,"l1")},ss=(e,t)=>{et(e,"ReduceL2Shared",t,"l2")},us=(e,t)=>{et(e,"ReduceLogSumExpShared",t,"logSumExp")},ds=(e,t)=>{et(e,"ReduceMaxShared",t,"max")},ls=(e,t)=>{et(e,"ReduceMinShared",t,"min")},cs=(e,t)=>{et(e,"ReduceProdShared",t,"prod")},ps=(e,t)=>{et(e,"ReduceSumShared",t,"sum")},ms=(e,t)=>{et(e,"ReduceSumSquareShared",t,"sumSquare")},fs=(e,t)=>{et(e,"ReduceLogSumShared",t,"logSum")}});var tt,Cm,Hr,so,rt,Am,Em,km,Pm,zm,Om,Bm,Dm,Mm,Rm,nt,gs,bs,ys,_s,ws,vs,$s,xs,Ss,Ts,Gr=U(()=>{"use strict";ee();ne();Se();ie();hs();tt=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.")},Cm=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Hr=(e,t,r,n,o,i,a=!1,u=!1)=>{let d=[],c=r[0].dims,p=c.length,m=k.normalizeAxes(o,p),f=!u&&m.length===0;c.forEach((S,$)=>{f||m.indexOf($)>=0?a&&d.push(1):d.push(S)});let b=d.length,g=k.size(d);return{name:e,shaderCache:t,getShaderSource:S=>{let $=[],v=P("_A",r[0].dataType,p),x=M("output",i,b),T=n(v,x,m),E=T[2];for(let I=0,z=0;I=0?(a&&z++,E=`for(var j${I}: u32 = 0; j${I} < ${c[I]}; j${I}++) { - ${T[2].includes("last_index")?`let last_index = j${I};`:""} - ${v.indicesSet("input_indices",I,`j${I}`)} - ${E} - }`):($.push(`${v.indicesSet("input_indices",I,x.indicesGet("output_indices",z))};`),z++);return` - - ${S.registerUniform("output_size","u32").declareVariables(v,x)} - - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var input_indices: ${v.type.indices}; - let output_indices = ${x.offsetToIndices("global_idx")}; - - ${$.join(` -`)} - ${T[0]} // init ops for reduce max/min - ${T[1]} - ${E} - ${T[3]} - ${T.length===4?x.setByOffset("global_idx","value"):T.slice(4).join(` -`)} - }`},getRunData:()=>({outputs:[{dims:d,dataType:i}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:[{type:12,data:g},...N(c,d)]})}},so=(e,t)=>{let r=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>r.push(Number(n))),J({axes:r,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},rt=(e,t,r,n)=>{let o=e.inputs,i=o.length===1?r:so(o,r);e.compute(Hr(t,{hint:i.cacheKey,inputDependencies:["rank"]},[o[0]],i.noopWithEmptyAxes&&i.axes.length===0?Cm:n,i.axes,o[0].dataType,i.keepDims,i.noopWithEmptyAxes),{inputs:[0]})},Am=(e,t)=>{tt(e.inputs),rt(e,"ReduceLogSum",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},Em=(e,t)=>{tt(e.inputs),rt(e,"ReduceL1",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},km=(e,t)=>{tt(e.inputs),rt(e,"ReduceL2",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Pm=(e,t)=>{tt(e.inputs),rt(e,"ReduceLogSumExp",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},zm=(e,t)=>{tt(e.inputs),rt(e,"ReduceMax",t,(n,o,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(n.indicesSet("input_indices",u,0));return[`${a.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Om=(e,t)=>{tt(e.inputs),rt(e,"ReduceMean",t,(n,o,i)=>{let a=1;for(let u=0;u=0||i.length===0)&&(a*=e.inputs[0].dims[u]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${o.type.value}(sum / ${a});`]})},Bm=(e,t)=>{tt(e.inputs),rt(e,"ReduceMin",t,(n,o,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Dm=(e,t)=>{tt(e.inputs),rt(e,"ReduceProd",t,(n,o)=>[`var value = ${o.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Mm=(e,t)=>{tt(e.inputs),rt(e,"ReduceSum",t,(n,o)=>[`var value = ${o.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Rm=(e,t)=>{tt(e.inputs),rt(e,"ReduceSumSquare",t,(n,o)=>[`var t = ${o.type.value}(0); var value = ${o.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},nt=(e,t,r)=>{if(t.length===0)return r;let n=1,o=1;for(let i=0;i1024},gs=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Om(e,t):is(e,t)},bs=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Em(e,t):as(e,t)},ys=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?km(e,t):ss(e,t)},_s=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pm(e,t):us(e,t)},ws=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?zm(e,t):ds(e,t)},vs=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Bm(e,t):ls(e,t)},$s=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Dm(e,t):cs(e,t)},xs=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Mm(e,t):ps(e,t)},Ss=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Rm(e,t):ms(e,t)},Ts=(e,t)=>{nt(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Am(e,t):fs(e,t)}});var Is,Cs,As,uo,Es=U(()=>{"use strict";ee();Se();Gr();Is=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.")},Cs=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` -`)}`,`var value = ${n.getByIndices("input_indices")}; -var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { - value = ${n.getByIndices("input_indices")}; - best_index = i32(last_index); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(Hr("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},As=(e,t)=>{Is(e.inputs);let r=(n,o,i)=>{let a=[];for(let u=0;u=0||i.length===0)&&a.push(`input_indices[${u}] = 0;`);return[`${a.join(` -`)}`,`var value = ${n.getByIndices("input_indices")}; -var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { - value = ${n.getByIndices("input_indices")}; - best_index = i32(last_index); - }`,"",o.setByOffset("global_idx","best_index")]};e.compute(Hr("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],r,[t.axis],7,t.keepDims),{inputs:[0]})},uo=e=>J(e)});var Um,lo,Nm,Vm,Wm,Rt,Lm,ks,Fr=U(()=>{"use strict";ee();ne();Vr();ie();Um=(e,t)=>{let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4],u=e[5];if(a&&u)throw new Error("Attention cannot have both past and attention_bias");if(r.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=r.dims[0],c=r.dims[1],p=r.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let m=o.dims[0]/3,f=m,b=f;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let x of t.qkvHiddenSizes)if(x%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");m=t.qkvHiddenSizes[0],f=t.qkvHiddenSizes[1],b=t.qkvHiddenSizes[2]}let g=c;if(m!==f)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==m+f+b)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let _=0;if(a){if(f!==b)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==f/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(_=a.dims[3])}let S=g+_,$=-1,v=0;if(i)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(u){if(u.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(u.dims[0]!==d||u.dims[1]!==t.numHeads||u.dims[2]!==c||u.dims[3]!==S)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:c,pastSequenceLength:_,kvSequenceLength:g,totalSequenceLength:S,maxSequenceLength:$,inputHiddenSize:p,hiddenSize:m,vHiddenSize:b,headSize:Math.floor(m/t.numHeads),vHeadSize:Math.floor(b/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:v,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},lo=(e,t,r)=>t&&e?` - let total_sequence_length_input = u32(${t.getByOffset("0")}); - let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); - let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; - let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; - total_sequence_length = u32(${e?.getByOffset("batchIdx")}) + 1; - var past_sequence_length: u32 = 0; - if (is_first_prompt == false) { - past_sequence_length = total_sequence_length - sequence_length; - } - `:` - ${r?"let past_sequence_length = uniforms.past_sequence_length":""}; - let present_sequence_length = total_sequence_length; - `,Nm=(e,t,r,n,o,i,a,u)=>{let d=ce(a?1:i),c=64,p=i/d;p{let v=M("x",e.dataType,e.dims,d),x=[v],T=a?P("seq_lens",a.dataType,a.dims):void 0;T&&x.push(T);let E=u?P("total_sequence_length_input",u.dataType,u.dims):void 0;E&&x.push(E);let I=Ae(e.dataType),z=[{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; - ${$.registerUniforms(z).declareVariables(...x)} - ${$.mainStart([c,1,1])} - let batchIdx = workgroup_id.z / uniforms.num_heads; - let headIdx = workgroup_id.z % uniforms.num_heads; - let sequence_length = uniforms.sequence_length; - var total_sequence_length = uniforms.total_sequence_length; - ${lo(T,E,!1)} - let local_offset = local_idx * uniforms.elements_per_thread; - let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; - let seq_causal_length = ${a?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; - var thread_max_vector = ${g}(-3.402823e+38f); - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - thread_max_vector = max(${g}(x[offset + i]), thread_max_vector); - } - thread_max[local_idx] = ${(()=>{switch(d){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${d}`)}})()}; - workgroupBarrier(); - - var max_value = f32(-3.402823e+38f); - for (var i = 0u; i < ${c}; i++) { - max_value = max(thread_max[i], max_value); - } - - var sum_vector = ${g}(0); - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - sum_vector += exp(${g}(x[offset + i]) - max_value); - } - thread_sum[local_idx] = ${(()=>{switch(d){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${d}`)}})()}; - workgroupBarrier(); - - var sum: f32 = 0; - for (var i = 0u; i < ${c}; i++) { - sum += thread_sum[i]; - } - - if (sum == 0) { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - x[offset + i] = ${v.type.value}(${I}(1.0) / ${I}(seq_causal_length)); - } - } else { - for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { - var f32input = ${g}(x[offset + i]); - x[offset + i] = ${v.type.value}(exp(f32input - max_value) / sum); - } - } - ${a?` - for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { - x[offset + total_seq_id] = ${v.type.value}(${I}(0)); - }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${b};${d}`,inputDependencies:_},getShaderSource:S,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:t*r},programUniforms:f})}},Vm=(e,t,r,n,o,i,a,u,d)=>{let c=a+i.kvSequenceLength,p=[i.batchSize,i.numHeads,i.sequenceLength,c],m=e>1&&n,f=i.kvNumHeads?i.kvNumHeads:i.numHeads,b=m?[i.batchSize,f,c,i.headSize]:void 0,g=i.nReps?i.nReps:1,_=i.scale===0?1/Math.sqrt(i.headSize):i.scale,S=ce(i.headSize),$=i.headSize/S,v=12,x={x:Math.ceil(c/v),y:Math.ceil(i.sequenceLength/v),z:i.batchSize*i.numHeads},T=[{type:12,data:i.sequenceLength},{type:12,data:$},{type:12,data:c},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:1,data:_},{type:12,data:a},{type:12,data:i.kvSequenceLength},{type:12,data:g}],E=m&&n&&k.size(n.dims)>0,I=["type","type"];E&&I.push("type"),o&&I.push("type"),u&&I.push("type"),d&&I.push("type");let z=[{dims:p,dataType:t.dataType,gpuDataType:0}];m&&z.push({dims:b,dataType:t.dataType,gpuDataType:0});let O=D=>{let L=P("q",t.dataType,t.dims,S),q=P("key",r.dataType,r.dims,S),Q=[L,q];if(E){let X=P("past_key",n.dataType,n.dims,S);Q.push(X)}o&&Q.push(P("attention_bias",o.dataType,o.dims));let W=u?P("seq_lens",u.dataType,u.dims):void 0;W&&Q.push(W);let Z=d?P("total_sequence_length_input",d.dataType,d.dims):void 0;Z&&Q.push(Z);let we=M("output",t.dataType,p),H=[we];m&&H.push(M("present_key",t.dataType,b,S));let j=Ae(1,S),te=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` - const TILE_SIZE = ${v}u; - - var tileQ: array<${L.type.storage}, ${v*v}>; - var tileK: array<${L.type.storage}, ${v*v}>; - ${D.registerUniforms(te).declareVariables(...Q,...H)} - ${D.mainStart([v,v,1])} - // x holds the N and y holds the M - let headIdx = workgroup_id.z % uniforms.num_heads; - let kvHeadIdx = ${g===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${g===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; - ${lo(W,Z,!0)} - let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; - let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; - ${E&&m?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; - let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; - ${m?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} - var value = ${j}(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; - ${E&&m?` - if (n + local_id.y < past_sequence_length) { - tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { - tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; - }`:` - if (n + local_id.y < uniforms.kv_sequence_length) { - tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; - }`} - ${m?`if (n + local_id.y < present_sequence_length) { - present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; - }`:""} - } - workgroupBarrier(); - - for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { - value += ${j}(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(S){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: ${S}`)}})()}; - output[outputIdx] = ${we.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; - } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${S};${o!==void 0};${n!==void 0};${e}`,inputDependencies:I},getRunData:()=>({outputs:z,dispatchGroup:x,programUniforms:T}),getShaderSource:O}},Wm=(e,t,r,n,o,i,a=void 0,u=void 0)=>{let d=i+o.kvSequenceLength,c=o.nReps?o.nReps:1,p=o.vHiddenSize*c,m=e>1&&n,f=o.kvNumHeads?o.kvNumHeads:o.numHeads,b=m?[o.batchSize,f,d,o.headSize]:void 0,g=[o.batchSize,o.sequenceLength,p],_=12,S={x:Math.ceil(o.vHeadSize/_),y:Math.ceil(o.sequenceLength/_),z:o.batchSize*o.numHeads},$=[{type:12,data:o.sequenceLength},{type:12,data:d},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:c}],v=m&&n&&k.size(n.dims)>0,x=["type","type"];v&&x.push("type"),a&&x.push("type"),u&&x.push("type");let T=[{dims:g,dataType:t.dataType,gpuDataType:0}];m&&T.push({dims:b,dataType:t.dataType,gpuDataType:0});let E=I=>{let z=P("probs",t.dataType,t.dims),O=P("v",r.dataType,r.dims),D=[z,O];v&&D.push(P("past_value",n.dataType,n.dims));let L=a?P("seq_lens",a.dataType,a.dims):void 0;a&&D.push(L);let q=u?P("total_sequence_length_input",u.dataType,u.dims):void 0;u&&D.push(q);let W=[M("output",t.dataType,g)];m&&W.push(M("present_value",t.dataType,b));let Z=[{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 = ${_}u; - var tileQ: array<${z.type.value}, ${_*_}>; - var tileV: array<${z.type.value}, ${_*_}>; - ${I.registerUniforms(Z).declareVariables(...D,...W)} - ${I.mainStart([_,_,1])} - let headIdx = workgroup_id.z % uniforms.num_heads; - let batchIdx = workgroup_id.z / uniforms.num_heads; - let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; - let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; - let m = global_id.y; - let n = global_id.x; - let sequence_length = uniforms.M; - var total_sequence_length = uniforms.K; - ${lo(L,q,!0)} - let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; - let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch - ${v&&m?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; - let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; - ${m?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} - var value = ${z.type.storage}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (m < uniforms.M && w + local_id.x < uniforms.K) { - tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; - } - if (n < uniforms.N && w + local_id.y < uniforms.K) { - var idx = TILE_SIZE * local_id.y + local_id.x; - ${v&&m?` - if (w + local_id.y < past_sequence_length) { - tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; - } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { - tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; - } - `:` - if (w + local_id.y < uniforms.kv_sequence_length) { - tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; - }`} - ${m?` - if (w + local_id.y < present_sequence_length) { - present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; - }`:""} - } - workgroupBarrier(); - for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { - value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; - } - workgroupBarrier(); - } - - // we need to transpose output from BNSH_v to BSND_v - if (m < uniforms.M && n < uniforms.N) { - let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size - + headIdx * uniforms.N + n; - output[outputIdx] = value; - } - }`};return{name:"AttentionScore",shaderCache:{hint:`${n!==void 0};${e}`,inputDependencies:x},getRunData:()=>({outputs:T,dispatchGroup:S,programUniforms:$}),getShaderSource:E}},Rt=(e,t,r,n,o,i,a,u,d,c,p=void 0,m=void 0)=>{let f=Math.min(e.outputCount,1+(a?1:0)+(u?1:0)),b=f>1?c.pastSequenceLength:0,g=b+c.kvSequenceLength,_=d&&k.size(d.dims)>0?d:void 0,S=[t,r];f>1&&a&&k.size(a.dims)>0&&S.push(a),_&&S.push(_),p&&S.push(p),m&&S.push(m);let $=e.compute(Vm(f,t,r,a,_,c,b,p,m),{inputs:S,outputs:f>1?[-1,1]:[-1]})[0];e.compute(Nm($,c.batchSize,c.numHeads,b,c.sequenceLength,g,p,m),{inputs:p&&m?[$,p,m]:[$],outputs:[]});let v=[$,n];f>1&&u&&k.size(u.dims)>0&&v.push(u),p&&v.push(p),m&&v.push(m),e.compute(Wm(f,$,n,u,c,b,p,m),{inputs:v,outputs:f>1?[0,2]:[0]})},Lm=(e,t)=>{let r=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,o=t.inputHiddenSize,i=t.headSize,a=12,u={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],p=m=>{let f=M("output_q",d[0].dataType,r),b=M("output_k",d[0].dataType,r),g=M("output_v",d[0].dataType,r),_=P("input",d[0].dataType,d[0].dims),S=P("weight",d[1].dataType,d[1].dims),$=P("bias",d[2].dataType,d[2].dims),v=_.type.storage,x=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` - const TILE_SIZE = ${a}u; - var tileInput: array<${v}, ${a*a}>; - var tileWeightQ: array<${v}, ${a*a}>; - var tileWeightK: array<${v}, ${a*a}>; - var tileWeightV: array<${v}, ${a*a}>; - ${m.registerUniforms(x).declareVariables(_,S,$,f,b,g)} - ${m.mainStart([a,a,1])} - let batchIndex = workgroup_id.z / uniforms.num_heads; - let headNumber = workgroup_id.z % uniforms.num_heads; - let m = global_id.y; - let n = global_id.x; - - let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; - let biasOffsetQ = headNumber * uniforms.head_size; - let biasOffsetK = uniforms.hidden_size + biasOffsetQ; - let biasOffsetV = uniforms.hidden_size + biasOffsetK; - - var valueQ = ${v}(0); - var valueK = ${v}(0); - var valueV = ${v}(0); - for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { - if (m < uniforms.M && w + local_id.x < uniforms.K) { - tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; - } - if (n < uniforms.N && w + local_id.y < uniforms.K) { - let offset = n + (w + local_id.y) * uniforms.ldb; - tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; - tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; - tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; - } - workgroupBarrier(); - for (var k: u32 = 0u; k({outputs:[{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:r,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:u,programUniforms:c}),getShaderSource:p},{inputs:d,outputs:[-1,-1,-1]})},ks=(e,t)=>{let r=Um(e.inputs,t),[n,o,i]=Lm(e,r);return Rt(e,n,o,i,e.inputs[4],void 0,void 0,void 0,e.inputs[5],r)}});var Gm,Hm,Fm,Ps,zs=U(()=>{"use strict";We();ee();ne();Se();ie();Gm=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let r=(n,o,i)=>{let a=o.length;if(a!==n.length)throw new Error(`${i}: num dimensions != ${a}`);o.forEach((u,d)=>{if(u!==n[d])throw new Error(`${i}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);r(e[1].dims,n,"Invalid input scale"),r(e[2].dims,n,"Invalid input B"),r(e[3].dims,n,"Invalid input mean"),r(e[4].dims,n,"Invalid input var")}else r(e[1].dims,[1],"Invalid input scale"),r(e[2].dims,[1],"Invalid input B"),r(e[3].dims,[1],"Invalid input mean"),r(e[4].dims,[1],"Invalid input var")},Hm=(e,t)=>{let{epsilon:r,spatial:n,format:o}=t,i=e[0].dims,a=n?ce(i[i.length-1]):1,u=o==="NHWC"&&i.length>1?a:1,d=k.size(i)/a,c=n,p=c?i.length:i,m=P("x",e[0].dataType,e[0].dims,a),f=P("scale",e[1].dataType,e[1].dims,u),b=P("bias",e[2].dataType,e[2].dims,u),g=P("inputMean",e[3].dataType,e[3].dims,u),_=P("inputVar",e[4].dataType,e[4].dims,u),S=M("y",e[0].dataType,p,a),$=()=>{let x="";if(n)x=`let cOffset = ${i.length===1?"0u":o==="NHWC"?`outputIndices[${i.length-1}] / ${a}`:"outputIndices[1]"};`;else if(o==="NCHW")x=` - ${S.indicesSet("outputIndices","0","0")} - let cOffset = ${S.indicesToOffset("outputIndices")};`;else{x=`var cIndices = ${f.type.indices}(0); - cIndices[0] = outputIndices[${i.length-1}];`;for(let T=1;T` - const epsilon = ${r}; - ${x.registerUniform("outputSize","u32").declareVariables(m,f,b,g,_,S)} - ${x.mainStart()} - ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${S.offsetToIndices(`global_idx * ${a}`)}; - ${$()} - let scale = ${f.getByOffset("cOffset")}; - let bias = ${b.getByOffset("cOffset")}; - let inputMean = ${g.getByOffset("cOffset")}; - let inputVar = ${_.getByOffset("cOffset")}; - let x = ${m.getByOffset("global_idx")}; - let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; - ${S.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c?[{type:12,data:d},...N(i)]:[{type:12,data:d}]})}},Fm=e=>J(e),Ps=(e,t)=>{let{inputs:r,outputCount:n}=e,o=Fm({...t,outputCount:n});if(ge.webgpu.validateInputContent&&Gm(r,o),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Hm(r,o))}});var qm,jm,Os,Bs=U(()=>{"use strict";ne();ie();qm=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")},jm=e=>{let t=e[0].dims,r=e[0].dims[2],n=k.size(t)/4,o=e[0].dataType,i=P("input",o,t,4),a=P("bias",o,[r],4),u=P("residual",o,t,4),d=M("output",o,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:p=>` - const channels = ${r}u / 4; - ${p.declareVariables(i,a,u,d)} - - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes(n)} - let value = ${i.getByOffset("global_idx")} - + ${a.getByOffset("global_idx % channels")} + ${u.getByOffset("global_idx")}; - ${d.setByOffset("global_idx","value")} - }`}},Os=e=>{qm(e.inputs),e.compute(jm(e.inputs))}});var Km,me,Ds,Ms,Rs,Us,Ns,Vs,Ws,Ls,Gs,Zm,Hs,Fs,qs,js,Yt,Ks,qr,Zs,Qs,Ys,Xs,Js,eu,tu,ru,nu,ou,iu,au,su,uu,du,lu,cu,pu,co,po,mu,fu,hu,Qm,Ym,gu,jr=U(()=>{"use strict";ee();ne();Se();ie();Km=(e,t,r,n,o,i,a)=>{let u=Math.ceil(t/4),d="";typeof o=="string"?d=`${o}(a)`:d=o("a");let c=P("inputData",r,[u],4),p=M("outputData",n,[u],4),m=[{name:"vec_size",type:"u32"}];return a&&m.push(...a),` - ${e.registerUniforms(m).declareVariables(c,p)} - - ${i??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - - let a = ${c.getByOffset("global_idx")}; - ${p.setByOffset("global_idx",d)} - }`},me=(e,t,r,n,o,i=e.dataType,a,u)=>{let d=[{type:12,data:Math.ceil(k.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:c=>Km(c,k.size(e.dims),e.dataType,i,r,n,u),getRunData:c=>({outputs:[{dims:e.dims,dataType:i}],dispatchGroup:{x:Math.ceil(k.size(c[0].dims)/64/4)},programUniforms:d})}},Ds=e=>{e.compute(me(e.inputs[0],"Abs","abs"))},Ms=e=>{e.compute(me(e.inputs[0],"Acos","acos"))},Rs=e=>{e.compute(me(e.inputs[0],"Acosh","acosh"))},Us=e=>{e.compute(me(e.inputs[0],"Asin","asin"))},Ns=e=>{e.compute(me(e.inputs[0],"Asinh","asinh"))},Vs=e=>{e.compute(me(e.inputs[0],"Atan","atan"))},Ws=e=>{e.compute(me(e.inputs[0],"Atanh","atanh"))},Ls=e=>J(e),Gs=(e,t)=>{let r;switch(t.to){case 10:r="vec4";break;case 1:r="vec4";break;case 12:r="vec4";break;case 6:r="vec4";break;case 9:r="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(me(e.inputs[0],"Cast",r,void 0,t.cacheKey,t.to))},Zm=e=>{let t,r,n=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,r=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,r=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return J({min:t,max:r})},Hs=(e,t)=>{let r=t||Zm(e.inputs),n=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,r.cacheKey,void 0,[{type:e.inputs[0].dataType,data:r.min},{type:e.inputs[0].dataType,data:r.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},Fs=e=>{e.compute(me(e.inputs[0],"Ceil","ceil"))},qs=e=>{e.compute(me(e.inputs[0],"Cos","cos"))},js=e=>{e.compute(me(e.inputs[0],"Cosh","cosh"))},Yt=e=>J(e),Ks=(e,t)=>{let r=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` - const elu_alpha_ = ${r}(${t.alpha}); - - fn elu_f32(a: ${r}) -> ${r} { - return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); - } - - fn elu_vf32(v: vec4<${r}>) -> vec4<${r}> { - return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,t.cacheKey))},qr=(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)); -}`,Zs=e=>{let t=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"Erf",r=>`erf_vf32(${r})`,qr(t)))},Qs=e=>{e.compute(me(e.inputs[0],"Exp","exp"))},Ys=e=>{e.compute(me(e.inputs[0],"Floor","floor"))},Xs=e=>{let t=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"Gelu",r=>`0.5 * ${r} * (1.0 + erf_vf32(${r} * 0.7071067811865475))`,qr(t)))},Js=(e,t)=>{let r=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${r}>(0.0))`,`const leaky_relu_alpha_ = ${r}(${t.alpha});`,t.cacheKey))},eu=e=>{e.compute(me(e.inputs[0],"Not",t=>`!${t}`))},tu=e=>{e.compute(me(e.inputs[0],"Neg",t=>`-${t}`))},ru=e=>{e.compute(me(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},nu=e=>{let t=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"Relu",r=>`select(vec4<${t}>(0.0), ${r}, ${r} > vec4<${t}>(0.0))`))},ou=e=>{e.compute(me(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},iu=e=>J(e),au=(e,t)=>{let r=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"HardSigmoid",n=>`max(vec4<${r}>(0.0), min(vec4<${r}>(1.0), ${t.alpha} * ${n} + vec4<${r}>(${t.beta})))`,void 0,t.cacheKey))},su=e=>{e.compute(me(e.inputs[0],"Sin","sin"))},uu=e=>{e.compute(me(e.inputs[0],"Sinh","sinh"))},du=e=>{e.compute(me(e.inputs[0],"Sqrt","sqrt"))},lu=e=>{e.compute(me(e.inputs[0],"Tan","tan"))},cu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,pu=e=>{e.compute(me(e.inputs[0],"Tanh",cu))},co=(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 ${cu("v")}; -} -`,po=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,mu=e=>{let t=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"FastGelu",po,co(t),void 0,e.inputs[0].dataType))},fu=(e,t)=>{let r=Ae(e.inputs[0].dataType);return e.compute(me(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${r}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${r}>(${t.alpha});`,t.cacheKey)),0},hu=e=>{e.compute(me(e.inputs[0],"Log","log"))},Qm=(e,t)=>` -const alpha = vec4<${e}>(${t}); -const one = ${e}(1.0); -const zero = ${e}(0.0); - -fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { - let v = x *alpha; - var x1 : vec4<${e}>; - for (var i = 0; i < 4; i = i + 1) { - if (v[i] >= zero) { - x1[i] = one / (one + exp(-v[i])); - } else { - x1[i] = one - one / (one + exp(v[i])); - } - } - return x * x1; -} -`,Ym=e=>`quick_gelu_impl(${e})`,gu=(e,t)=>{let r=Ae(e.inputs[0].dataType);e.compute(me(e.inputs[0],"QuickGelu",Ym,Qm(r,t.alpha),t.cacheKey,e.inputs[0].dataType))}});var Xm,Jm,yu,_u=U(()=>{"use strict";ne();ie();jr();Xm=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")},Jm=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let r=P("input",e[0].dataType,e[0].dims,4),n=P("bias",e[0].dataType,[e[0].dims[2]],4),o=M("output",e[0].dataType,t,4),i=k.size(t)/4,a=be(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:d=>` - const M_SQRT2 = sqrt(2.0); - const halfChannels = ${e[0].dims[2]/4/2}u; - - ${d.declareVariables(r,n,o)} - - ${qr(a)} - - ${d.mainStart()} - ${d.guardAgainstOutOfBoundsWorkgroupSizes(i)} - let biasIdx = global_idx % halfChannels; - let batchIndex = global_idx / halfChannels; - let inputOffset = biasIdx + batchIndex * halfChannels * 2; - let valueLeft = input[inputOffset] + bias[biasIdx]; - let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; - let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); - - ${o.setByOffset("global_idx","valueLeft * geluRight")} - }`}},yu=e=>{Xm(e.inputs),e.compute(Jm(e.inputs))}});var ef,tf,ot,wu,vu,$u,xu,Su,Tu,Iu,Cu,Au,Eu,ku=U(()=>{"use strict";ee();ne();ie();ef=(e,t,r,n,o,i,a,u,d,c,p,m)=>{let f,b;typeof u=="string"?f=b=(v,x)=>`${u}((${v}),(${x}))`:typeof u=="function"?f=b=u:(f=u.scalar,b=u.vector);let g=M("outputData",p,n.length,4),_=P("aData",d,t.length,4),S=P("bData",c,r.length,4),$;if(o)if(i){let v=k.size(t)===1,x=k.size(r)===1,T=t.length>0&&t[t.length-1]%4===0,E=r.length>0&&r[r.length-1]%4===0;v||x?$=g.setByOffset("global_idx",b(v?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"),x?`${S.type.value}(${S.getByOffset("0")}.x)`:S.getByOffset("global_idx"))):$=` - let outputIndices = ${g.offsetToIndices("global_idx * 4u")}; - let offsetA = ${_.broadcastedIndicesToOffset("outputIndices",g)}; - let offsetB = ${S.broadcastedIndicesToOffset("outputIndices",g)}; - ${g.setByOffset("global_idx",b(a||T?_.getByOffset("offsetA / 4u"):`${_.type.value}(${_.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||E?S.getByOffset("offsetB / 4u"):`${S.type.value}(${S.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} - `}else $=g.setByOffset("global_idx",b(_.getByOffset("global_idx"),S.getByOffset("global_idx")));else{if(!i)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(x,T,E="")=>{let I=`aData[indexA${T}][componentA${T}]`,z=`bData[indexB${T}][componentB${T}]`;return` - let outputIndices${T} = ${g.offsetToIndices(`global_idx * 4u + ${T}u`)}; - let offsetA${T} = ${_.broadcastedIndicesToOffset(`outputIndices${T}`,g)}; - let offsetB${T} = ${S.broadcastedIndicesToOffset(`outputIndices${T}`,g)}; - let indexA${T} = offsetA${T} / 4u; - let indexB${T} = offsetB${T} / 4u; - let componentA${T} = offsetA${T} % 4u; - let componentB${T} = offsetB${T} % 4u; - ${x}[${T}] = ${E}(${f(I,z)}); - `};p===9?$=` - var data = vec4(0); - ${v("data",0,"u32")} - ${v("data",1,"u32")} - ${v("data",2,"u32")} - ${v("data",3,"u32")} - outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:$=` - ${v("outputData[global_idx]",0)} - ${v("outputData[global_idx]",1)} - ${v("outputData[global_idx]",2)} - ${v("outputData[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(_,S,g)} - - ${m??""} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${$} - }`},tf=(e,t,r,n,o,i,a=r.dataType)=>{let u=r.dims.map(_=>Number(_)??1),d=n.dims.map(_=>Number(_)??1),c=!k.areEqual(u,d),p=u,m=k.size(u),f=!1,b=!1,g=[c];if(c){let _=Je.calcShape(u,d,!1);if(!_)throw new Error("Can't perform binary op on the given tensors");p=_.slice(),m=k.size(p);let S=k.size(u)===1,$=k.size(d)===1,v=u.length>0&&u[u.length-1]%4===0,x=d.length>0&&d[d.length-1]%4===0;g.push(S),g.push($),g.push(v),g.push(x);let T=1;for(let E=1;E_.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:_=>ef(_,u,d,p,f,c,b,o,r.dataType,n.dataType,a,i),getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:Math.ceil(k.size(p)/4)},...N(u,d,p)]})}},ot=(e,t,r,n,o,i)=>{e.compute(tf(t,o??"",e.inputs[0],e.inputs[1],r,n,i))},wu=e=>{ot(e,"Add",(t,r)=>`${t}+${r}`)},vu=e=>{ot(e,"Div",(t,r)=>`${t}/${r}`)},$u=e=>{ot(e,"Equal",{scalar:(t,r)=>`u32(${t}==${r})`,vector:(t,r)=>`vec4(${t}==${r})`},void 0,void 0,9)},xu=e=>{ot(e,"Mul",(t,r)=>`${t}*${r}`)},Su=e=>{let t=P("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ot(e,"Pow",{scalar:(n,o)=>`pow_custom(${n},${o})`,vector:(n,o)=>`pow_vector_custom(${n},${o})`},` - fn pow_custom(a : ${t}, b : ${t}) -> ${t} { - if (b == ${t}(0.0)) { - return ${t}(1.0); - } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { - return ${t}(pow(f32(a), f32(b))); // NaN - } - return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); - } - fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { - // TODO: implement vectorized pow - return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); - } - `)},Tu=e=>{ot(e,"Sub",(t,r)=>`${t}-${r}`)},Iu=e=>{ot(e,"Greater",{scalar:(t,r)=>`u32(${t}>${r})`,vector:(t,r)=>`vec4(${t}>${r})`},void 0,void 0,9)},Cu=e=>{ot(e,"Less",{scalar:(t,r)=>`u32(${t}<${r})`,vector:(t,r)=>`vec4(${t}<${r})`},void 0,void 0,9)},Au=e=>{ot(e,"GreaterOrEqual",{scalar:(t,r)=>`u32(${t}>=${r})`,vector:(t,r)=>`vec4(${t}>=${r})`},void 0,void 0,9)},Eu=e=>{ot(e,"LessOrEqual",{scalar:(t,r)=>`u32(${t}<=${r})`,vector:(t,r)=>`vec4(${t}<=${r})`},void 0,void 0,9)}});var nf,of,af,sf,Pu,zu,Ou=U(()=>{"use strict";ee();ne();Se();ie();nf=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let r=0,n=e[r],o=n.dataType,i=n.dims.length;e.forEach((a,u)=>{if(u!==r){if(a.dataType!==o)throw new Error("input tensors should be one type");if(a.dims.length!==i)throw new Error("input tensors should have the same shape");a.dims.forEach((d,c)=>{if(c!==t&&d!==n.dims[c])throw new Error("non concat dimensions must match")})}})},of=(e,t)=>` - fn calculateInputIndex(index: u32) -> u32 { - let sizeInConcatAxis = array(${t}); - for (var i: u32 = 0u; i < ${e}; i += 1u ) { - if (index < sizeInConcatAxis[i]) { - return i; - } - } - return ${e}u; - }`,af=(e,t)=>{let r=e.length,n=[];for(let o=0;o{let o=k.size(r),i=new Array(e.length),a=new Array(e.length),u=0,d=[],c=[],p=[{type:12,data:o}];for(let _=0;_`uniforms.sizeInConcatAxis${_}`).join(","),g=_=>` - - ${(()=>{_.registerUniform("outputSize","u32");for(let S=0;S(${b}); - ${f} -= sizeInConcatAxis[inputIndex - 1u]; - } - - ${af(a,m)} - }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:r,dataType:n}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:g}},Pu=(e,t)=>{let r=e.inputs,n=r[0].dims,o=k.normalizeAxis(t.axis,n.length);nf(r,o);let i=n.slice();i[o]=r.reduce((u,d)=>u+(d.dims.length>o?d.dims[o]:0),0);let a=r.filter(u=>k.size(u.dims)>0);e.compute(sf(a,o,i,r[0].dataType),{inputs:a})},zu=e=>J({axis:e.axis})});var Fe,qe,je,Kr,bt=U(()=>{"use strict";ee();ne();Fe=(e,t,r="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${r}(uniforms.clip_min)), ${t}(${r}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${r}(uniforms.alpha) * value + ${r}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${r}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); - value = sign(value) * (1.0 - e2x) / (1.0 + e2x); - `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},qe=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},je=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Kr=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[r,n]=e?.activation_params||[.2,.5];return{activation:t,alpha:r,beta:n}}else if(t==="Clip"){let[r,n]=e?.activation_params||[Wa,La];return{activation:t,clipMax:n,clipMin:r}}else if(t==="LeakyRelu"){let[r]=e?.activation_params||[.01];return{activation:t,alpha:r}}return{activation:t}}});var Ie,Bu,Zr=U(()=>{"use strict";Ie=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Bu=e=>` - ${e?"value = value + getBiasByOutputCoords(coords);":""} - `});var Du,Mu=U(()=>{"use strict";Du=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)); -} -`});var Xt,Qr,Yr=U(()=>{"use strict";ee();ne();ie();bt();Xt=(e,t,r,n,o)=>{let i=n-r;return` - ${Array.from({length:r}).map((a,u)=>` - if (${F(t.shape,u,t.rank)} != 1) { - ${t.indicesSet(e,u,F(o,u+i,n))} - } else { - ${t.indicesSet(e,u,0)} - }`).join("")} -`},Qr=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,u=e[1].dims,d=a[a.length-2],c=u[u.length-1],p=a[a.length-1],m=ce(c),f=ce(p),b=ce(d),g=k.size(r)/m/b,_=e.length>2,S=n?n.slice(0,-2):r.slice(0,-2),v=[k.size(S),d,c],x=[{type:12,data:g},{type:12,data:d},{type:12,data:c},{type:12,data:p}];qe(t,x),x.push(...N(S,a,u)),_&&x.push(...N(e[2].dims)),x.push(...N(v));let T=E=>{let I=Lr("batch_dims",e[0].dataType,S.length),z=P("a",e[0].dataType,a.length,f),O=P("b",e[1].dataType,u.length,m),D=M("output",e[0].dataType,v.length,m),L=be(D.type.tensor),q=Fe(t,D.type.value,L),Q=[z,O],W="";if(_){let H=o?m:1;Q.push(P("bias",e[2].dataType,e[2].dims.length,H)),W=`${o?`value += bias[col / ${H}];`:`value += ${D.type.value}(bias[row + i]);`}`}let Z=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];je(t,Z);let we=()=>{let H=`var a_data: ${z.type.value};`;for(let j=0;j; - for (var k: u32 = 0u; k < uniforms.K; k = k + ${f}) { - ${we()} - } - for (var i = 0u; i < ${b}u; i++) { - var value = values[i]; - ${W} - ${q} - let cur_indices = ${D.type.indices}(batch, row + i, col); - let offset = ${D.indicesToOffset("cur_indices")}; - ${D.setByOffset(`offset / ${m}`,"value")}; - } - } - `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${m};${f};${b};${o}`,inputDependencies:_?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:x}),getShaderSource:T}}});var uf,df,mo,Ru,lf,fo,cf,Jt,Xr=U(()=>{"use strict";ee();ne();ie();bt();Yr();Zr();uf=(e,t)=>e?` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - kStart + inputRow, - globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); - `:` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - globalRow + innerRow, - kStart / innerElementSize + inputCol${t?", batchIndices":""}); - `,df=(e,t)=>e?` - let ACached0 = mm_Asub[k * innerElementSize][localRow]; - let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; - let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; - ${t===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} - for (var i = 0; i < rowPerThread; i = i + 1) { - acc[i] = BCached0 * ACached0[i] + acc[i]; - acc[i] = BCached1 * ACached1[i] + acc[i]; - acc[i] = BCached2 * ACached2[i] + acc[i]; - ${t===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} - }`:` - for (var i = 0; i < rowPerThread; i = i + 1) { - let ACached = mm_Asub[tileRow + i][k]; - acc[i] = BCached0 * ACached.x + acc[i]; - acc[i] = BCached1 * ACached.y + acc[i]; - acc[i] = BCached2 * ACached.z + acc[i]; - ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,mo=(e,t,r="f32",n,o=!1,i=32,a=!1,u=32)=>{let d=t[1]*e[1],c=t[0]*e[0],p=o?d:i,m=o?i:d,f=p/t[0],b=i/t[1];if(!((o&&f===4&&e[1]===4||!o&&(f===3||f===4))&&p%t[0]===0&&i%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${f} and workPerThread[1] ${e[1]} must be 4. - Otherwise, innerElementSize ${f} must be 3 or 4. - tileAWidth ${p} must be divisible by workgroupSize[0]${t[0]}. tileInner ${i} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` -var mm_Asub: array, ${p/f}>, ${m}>; -var mm_Bsub: array, ${c/e[0]}>, ${i}>; - -const rowPerThread = ${e[1]}; -const colPerThread = ${e[0]}; -const innerElementSize = ${f}; -const tileInner = ${i}; - -@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let localRow = i32(localId.y); - let tileRow = localRow * rowPerThread; - let tileCol = i32(localId.x); - - let globalRow =i32(globalId.y) * rowPerThread; - let globalCol = i32(globalId.x); - let batch = ${a?"0":"i32(globalId.z)"}; - ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} - let globalRowStart = i32(workgroupId.y) * ${d}; - - let num_tiles = ${a?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; - - var acc: array, rowPerThread>; - - // Loop over shared dimension. - let tileRowB = localRow * ${b}; - for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let inputRow = tileRow + innerRow; - let inputCol = tileCol; - ${uf(o,n)} - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", batchIndices":""}); - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { - let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; - let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; - let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; - ${f===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - - ${df(o,f)} - } - - workgroupBarrier(); - } - - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); - } -}`},Ru=(e,t)=>e?` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - kStart + inputRow, - globalRowStart + inputCol${t?", batchIndices":""}); - `:` - mm_Asub[inputRow][inputCol] = mm_readA(batch, - globalRowStart + inputRow, - kStart + inputCol${t?", batchIndices":""}); - `,lf=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",fo=(e,t,r="f32",n,o=!1,i=32,a=!1,u=32,d=!1)=>{let c=e[1]*t[1],p=e[0]*t[0],m=o?c:i,f=o?i:c;if(!(f%t[1]===0&&m%t[0]===0&&i%t[1]===0))throw new Error(`tileAHight ${f} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${m} must be divisible by workgroupSize[0]${t[0]}, tileInner ${i} must be divisible by workgroupSize[1]${t[1]}`);let b=f/t[1],g=m/t[0],_=i/t[1],S=d?` - let localRow = i32(localId.y); - let localCol = i32(localId.x); - let globalRowStart = i32(workgroupId.y) * ${c}; - let globalColStart = i32(workgroupId.x) * ${p}; - - // Loop over shared dimension. - for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var inputRow = localRow; inputRow < ${f}; inputRow = inputRow + ${t[1]}) { - for (var inputCol = localCol; inputCol < ${m}; inputCol = inputCol + ${t[0]}) { - ${Ru(o,n)} - } - } - // Load one tile of B into local memory. - for (var inputRow = localRow; inputRow < ${i}; inputRow = inputRow + ${t[1]}) { - for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${t[0]}) { - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalColStart + inputCol${n?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${r}, colPerThread>; - for (var k = 0; k < tileInner; k = k + 1) { - for (var inner = 0; inner < colPerThread; inner = inner + 1) { - BCached[inner] = mm_Bsub[k][localCol + inner * ${t[0]}]; - } - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[1]}][k];`} - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - acc[innerRow][innerCol] = acc[innerRow][innerCol] + - ACached * BCached[innerCol]; - } - } - } - workgroupBarrier(); - } - for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - let gRow = globalRowStart + localRow + innerRow * ${t[1]}; - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let gCol = globalColStart + localCol + innerCol * ${t[0]}; - mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); - } - } - `:` -let tileRow = i32(localId.y) * rowPerThread; -let tileCol = i32(localId.x) * colPerThread; - -let globalRow = i32(globalId.y) * rowPerThread; -let globalCol = i32(globalId.x) * colPerThread; -let globalRowStart = i32(workgroupId.y) * ${c}; - -let tileRowA = i32(localId.y) * ${b}; -let tileColA = i32(localId.x) * ${g}; -let tileRowB = i32(localId.y) * ${_}; -// Loop over shared dimension. -for (var t = 0; t < num_tiles; t = t + 1) { - // Load one tile of A into local memory. - for (var innerRow = 0; innerRow < ${b}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < ${g}; innerCol = innerCol + 1) { - let inputRow = tileRowA + innerRow; - let inputCol = tileColA + innerCol; - ${Ru(o,n)} - } - } - - // Load one tile of B into local memory. - for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - let inputRow = tileRowB + innerRow; - let inputCol = tileCol + innerCol; - mm_Bsub[inputRow][inputCol] = mm_readB(batch, - kStart + inputRow, - globalCol + innerCol${n?", batchIndices":""}); - } - } - kStart = kStart + tileInner; - workgroupBarrier(); - - // Compute acc values for a single thread. - var BCached : array<${r}, 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) { - ${lf(o)} - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; - } - } - } - - workgroupBarrier(); -} - -for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { - mm_write(batch, globalRow + innerRow, globalCol + innerCol, - acc[innerRow][innerCol]); - } -} -`;return` - var mm_Asub : array, ${f}>; - var mm_Bsub : array, ${i}>; - const rowPerThread = ${e[1]}; - const colPerThread = ${e[0]}; - const tileInner = ${i}; - -@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) -fn main(@builtin(local_invocation_id) localId : vec3, - @builtin(global_invocation_id) globalId : vec3, - @builtin(workgroup_id) workgroupId : vec3) { - let batch = ${a?"0":"i32(globalId.z)"}; - ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} - let num_tiles = ${a?`${Math.ceil(u/i)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; - var kStart = ${a?`i32(globalId.z) * ${u}`:"0"}; - - var acc : array, rowPerThread>; - ${S} - } -`},cf=(e,t,r,n,o=!1)=>{let[i,a,u,d]=n,c=be(n[0].type.tensor);return` - fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ie(e,c)} { - var value = ${Ie(e,c)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) - { - var aIndices: ${a.type.indices}; - ${Xt("aIndices",a,a.rank-2,i.rank,"batchIndices")} - ${a.indicesSet("aIndices",a.rank-2,"u32(row)")} - ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")} - value = ${a.getByIndices("aIndices")}; - } - return value; - } - - fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${i.type.indices}) -> ${Ie(e,c)} { - var value = ${Ie(e,c)}(0.0); - let col = colIn * ${e}; - if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) - { - var bIndices: ${u.type.indices}; - ${Xt("bIndices",u,u.rank-2,i.rank,"batchIndices")} - ${u.indicesSet("bIndices",u.rank-2,"u32(row)")} - ${u.indicesSet("bIndices",u.rank-1,"u32(colIn)")} - value = ${u.getByIndices("bIndices")}; - } - return value; - } - - fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Ie(e,c)}) { - let col = colIn * ${e}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { - var value = valueIn; - let coords = vec3(batch, row, colIn); - ${t?`value = value + ${o?"bias[colIn]":`${Ie(e,c)}(bias[row])`};`:""} - ${r} - ${d.setByIndices("vec3(coords)","value")} - } - } - `},Jt=(e,t,r,n,o=!1,i)=>{let a=e[0].dims,u=e[1].dims,d=a.slice(0,-2),c=u.slice(0,-2),p=n?n.slice(0,-2):r.slice(0,-2),m=k.size(p),f=a[a.length-2],b=a[a.length-1],g=u[u.length-1],_=b%4===0&&g%4===0,S=f<=8?[4,1,1]:[4,4,1],$=[8,8,1],v=[Math.ceil(g/$[0]/S[0]),Math.ceil(f/$[1]/S[1]),Math.ceil(m/$[2]/S[2])],x=_?4:1,T=[...d,f,b/x],E=T.length,I=[...c,b,g/x],z=I.length,O=[m,f,g/x],D=[{type:6,data:f},{type:6,data:g},{type:6,data:b}];qe(t,D),D.push(...N(p,T,I));let L=["rank","rank"],q=e.length>2;q&&(D.push(...N(e[2].dims)),L.push("rank")),D.push(...N(O));let Q=W=>{let Z=p.length,we=Lr("batchDims",e[0].dataType,Z,1),H=be(e[0].dataType),j=P("a",e[0].dataType,E,x),te=P("b",e[1].dataType,z,x),X=M("result",e[0].dataType,O.length,x),ue=[j,te];if(q){let V=o?x:1;ue.push(P("bias",e[2].dataType,e[2].dims.length,V))}let he=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];je(t,he);let ye=be(X.type.tensor),re=Fe(t,X.type.value,ye),C=cf(x,q,re,[we,j,te,X],o);return` - ${W.registerUniforms(he).registerInternalVariables(we).declareVariables(...ue,X)} - ${C} - ${_?mo(S,$,H,we):fo(S,$,H,we)} - `};return{name:"MatMul",shaderCache:{hint:`${S};${t.activation};${_};${o}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:i?i(r):r,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:D}),getShaderSource:Q}}});var pf,Uu,Nu=U(()=>{"use strict";ee();Xe();ie();bt();Zr();Mu();Xr();pf=(e,t,r,n,o=!1,i,a=4,u=4,d=4,c="f32")=>{let p=L=>{switch(L){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${L} is not supported.`)}},m=L=>{switch(L){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 ${L} is not supported.`)}},f=e?` - let coord = vec4(batch, xRow, xCol, xCh); - `:` - let coord = vec4(batch, xCh, xRow, xCol); - `,b=e?` - let coords = vec4( - batch, - row / outWidth, - row % outWidth, - col); - `:` - let coords = vec4( - batch, - row, - col / outWidth, - col % outWidth); - `,g=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",_=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",S=e?"row":"col",$=e?"col":"row",v=` - let inChannels = i32(uniforms.w_shape[2]); - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - let outRow = ${S} / outWidth; - let outCol = ${S} % outWidth; - - let WRow = ${$} / (i32(uniforms.w_shape[1]) * inChannels); - let WCol = ${$} / 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 = ${$} % inChannels; - var resData = ${Ie(a,c)}(0.0); - // The bounds checking is always needed since we use it to pad zero for - // the 'same' padding type. - if (xRow >= 0 && xRow < ${g} && xCol >= 0 && xCol < ${_}) { - ${f} - let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); - ${p(a)} - } - return resData;`,x=e?t&&n?` - let col = colIn * ${a}; - ${v}`:` - let col = colIn * ${a}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { - ${v} - } - return ${Ie(a,c)}(0.0);`:n&&r?` - let col = colIn * ${a}; - ${v}`:` - let col = colIn * ${a}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${v} - } - return ${Ie(a,c)}(0.0);`,T=e?n&&r?m(u):` - let col = colIn * ${u}; - if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { - ${m(u)} - } - return ${Ie(u,c)}(0.0);`:` - let col = colIn * ${u}; - if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { - ${m(u)} - } - return ${Ie(u,c)}(0.0);`,E=Ie(d,c),I=e?Ie(a,c):Ie(u,c),z=e?Ie(u,c):Ie(a,c),O=Fe(i,E,c);return` - fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${I} { - ${e?x:T} - } - - fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${z} { - ${e?T:x} - } - - fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${E}) { - let col = colIn * ${d}; - if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) - { - var value = valueIn; - let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; - ${b} - ${Bu(o)} - ${O} - setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); - } - }`},Uu=(e,t,r,n,o,i,a,u,d)=>{let c=t.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],m=r[0],f=c?r[2]:r[3],b=c?r[1]:r[2],g=c?r[3]:r[1],_=c&&(p%4===0||p%3===0)&&g%4===0,S=c?g:f*b,$=c?f*b:g,v=[8,8,1],x=n<=8?[4,1,1]:[4,4,1],T=[Math.ceil(S/v[0]/x[0]),Math.ceil($/v[1]/x[1]),Math.ceil(m/v[2]/x[2])];se("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let E=_?c&&p%4!==0?3:4:1,I=v[1]*x[1],z=v[0]*x[0],O=Math.max(v[0]*E,v[1]),D=n%I===0,L=o%z===0,q=i%O===0,Q=_?[E,4,4]:[1,1,1],W=[{type:6,data:n},{type:6,data:o},{type:6,data:i},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];qe(t,W),W.push(...N(e[0].dims,e[1].dims));let Z=["rank","rank"];a&&(W.push(...N(e[2].dims)),Z.push("rank")),W.push(...N(r));let we=H=>{let j=[{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}];je(t,j);let te=_?4:1,X=be(e[0].dataType),ue=` - fn setOutputAtIndex(flatIndex : i32, value : ${_?`vec4<${X}>`:X}) { - result[flatIndex] = ${_?`vec4<${X}>`:X}(value); - } - fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${_?`vec4<${X}>`:X}) { - let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); - setOutputAtIndex(flatIndex ${_?"/ 4":""}, value); - }`,he=P("x",e[0].dataType,e[0].dims.length,E===3?1:E),ye=P("w",e[1].dataType,e[1].dims.length,te),re=[he,ye],C=M("result",e[0].dataType,r.length,te);if(a){let V=P("bias",e[2].dataType,e[2].dims.length,te);re.push(V),ue+=` - fn getBiasByOutputCoords(coords : vec4) -> ${_?`vec4<${X}>`:X} { - return bias[coords.${c?"w":"y"}${_?"/ 4":""}]; - }`}return` - ${Du("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 }; - ${H.registerUniforms(j).declareVariables(...re,C)} - ${ue} - ${pf(c,D,L,q,a,t,Q[0],Q[1],Q[2],X)} - ${_?mo(x,v,X,void 0,!c,O):fo(x,v,X,void 0,!c,O,!1,void 0,u)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${E};${_};${D};${L};${q};${I};${z};${O}`,inputDependencies:Z},getRunData:()=>({outputs:[{dims:d?d(r):r,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:W}),getShaderSource:we}}});var mf,Vu,Jr,ff,Wu,hf,Lu,Gu,Hu=U(()=>{"use strict";ee();Xe();ne();ie();bt();Zr();mf=e=>{let t=1;for(let r=0;rtypeof e=="number"?[e,e,e]:e,Jr=(e,t)=>t<=1?e:e+(e-1)*(t-1),ff=(e,t,r,n=1)=>{let o=Jr(t,n);return Math.floor((e[0]*(r-1)-r+o)/2)},Wu=(e,t,r,n,o)=>{o==null&&(o=ff(e,t[0],n[0]));let i=[0,0,0,r];for(let a=0;a<3;a++)e[a]+2*o>=t[a]&&(i[a]=Math.trunc((e[a]-t[a]+2*o)/n[a]+1));return i},hf=(e,t,r,n,o,i,a,u,d,c)=>{let p,m,f,b;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let g=Wu([t,r,n,1],[u,d,c],1,[o,i,a],e);m=g[0],f=g[1],b=g[2]}else if(Array.isArray(e)){if(!e.every((_,S,$)=>_===$[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 g=Wu([t,r,n,1],[u,d,c],1,[o,i,a],e[0]);m=g[0],f=g[1],b=g[2]}else if(e==="SAME_UPPER"){m=Math.ceil(t/o),f=Math.ceil(r/i),b=Math.ceil(n/a);let g=(m-1)*o+u-t,_=(f-1)*i+d-r,S=(b-1)*a+c-n,$=Math.floor(g/2),v=g-$,x=Math.floor(_/2),T=_-x,E=Math.floor(S/2),I=S-E;p={top:x,bottom:T,left:E,right:I,front:$,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:m,outHeight:f,outWidth:b}},Lu=(e,t,r,n,o,i=!1,a="channelsLast")=>{let u,d,c,p,m;if(a==="channelsLast")[u,d,c,p,m]=e;else if(a==="channelsFirst")[u,m,d,c,p]=e;else throw new Error(`Unknown dataFormat ${a}`);let[f,,b,g,_]=t,[S,$,v]=Vu(r),[x,T,E]=Vu(n),I=Jr(b,x),z=Jr(g,T),O=Jr(_,E),{padInfo:D,outDepth:L,outHeight:q,outWidth:Q}=hf(o,d,c,p,S,$,v,I,z,O),W=i?f*m:f,Z=[0,0,0,0,0];return a==="channelsFirst"?Z=[u,W,L,q,Q]:a==="channelsLast"&&(Z=[u,L,q,Q,W]),{batchSize:u,dataFormat:a,inDepth:d,inHeight:c,inWidth:p,inChannels:m,outDepth:L,outHeight:q,outWidth:Q,outChannels:W,padInfo:D,strideDepth:S,strideHeight:$,strideWidth:v,filterDepth:b,filterHeight:g,filterWidth:_,effectiveFilterDepth:I,effectiveFilterHeight:z,effectiveFilterWidth:O,dilationDepth:x,dilationHeight:T,dilationWidth:E,inShape:e,outShape:Z,filterShape:t}},Gu=(e,t,r,n,o,i)=>{let a=i==="channelsLast",u=a?e[0].dims[3]:e[0].dims[1],d=!1,c=[64,1,1],p={x:r.map((v,x)=>x)},m=[Math.ceil(mf(p.x.map(v=>r[v]))/c[0]),1,1];se("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${m}`);let f=d?a&&u%4!==0?3:4:1,b=k.size(r),g=[{type:12,data:b},{type:12,data:n},{type:12,data:o},{type:12,data:t.strides},{type:12,data:t.dilations}];qe(t,g),g.push(...N(e[0].dims,e[1].dims));let _=["rank","rank"],S=e.length===3;S&&(g.push(...N(e[2].dims)),_.push("rank")),g.push(...N(r));let $=v=>{let x=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];je(t,x);let T=d?4:1,E=be(e[0].dataType),I=P("x",e[0].dataType,e[0].dims.length,f===3?1:f),z=P("W",e[1].dataType,e[1].dims.length,T),O=[I,z],D=M("result",e[0].dataType,r.length,T),L="";if(S){let W=P("bias",e[2].dataType,e[2].dims.length,T);O.push(W),L+=` - fn getBiasByOutputCoords(coords : array) -> ${d?`vec4<${E}>`:E} { - return bias[${a?F("coords",4,5):F("coords",1,5)}${d?"/ 4":""}]; - }`}let q=Ie(f,E),Q=Fe(t,q,E);return` - ${L} - fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${I.getByIndices("aIndices")}; - } - fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { - let aIndices = array(d0, d1, d2, d3, d4); - return ${z.getByIndices("aIndices")}; - } - ${v.registerUniforms(x).declareVariables(...O,D)} - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let coords = ${D.offsetToIndices("global_idx")}; - let batch = ${F("coords",0,I.rank)}; - let d2 = ${a?F("coords",I.rank-1,I.rank):F("coords",1,I.rank)}; - let xFRCCorner = vec3(${a?F("coords",1,I.rank):F("coords",2,I.rank)}, - ${a?F("coords",2,I.rank):F("coords",3,I.rank)}, - ${a?F("coords",3,I.rank):F("coords",4,I.rank)}) * uniforms.strides - uniforms.pads; - let xFCorner = xFRCCorner.x; - let xRCorner = xFRCCorner.y; - let xCCorner = xFRCCorner.z; - let xShapeY = ${a?F("uniforms.x_shape",1,I.rank):F("uniforms.x_shape",2,I.rank)}; - let xShapeZ = ${a?F("uniforms.x_shape",2,I.rank):F("uniforms.x_shape",3,I.rank)}; - let xShapeW = ${a?F("uniforms.x_shape",3,I.rank):F("uniforms.x_shape",4,I.rank)}; - let xShapeU = ${a?F("uniforms.x_shape",4,I.rank):F("uniforms.x_shape",1,I.rank)}; - let inputDepthNearestVec4 = (xShapeU / 4) * 4; - let inputDepthVec4Remainder = xShapeU % 4; - - var value = 0.0; - for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { - let xF = xFCorner + wF * uniforms.dilations[0]; - if (xF < 0 || xF >= xShapeY) { - continue; - } - - for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { - let xR = xRCorner + wR * uniforms.dilations[1]; - if (xR < 0 || xR >= xShapeZ) { - continue; - } - - for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { - let xC = xCCorner + wC * uniforms.dilations[2]; - if (xC < 0 || xC >= xShapeW) { - continue; - } - - for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { - ${a?`let xValues = vec4( - getX(batch, xF, xR, xC, d1), - getX(batch, xF, xR, xC, d1 + 1), - getX(batch, xF, xR, xC, d1 + 2), - getX(batch, xF, xR, xC, d1 + 3)); - `:`let xValues = vec4( - getX(batch, d1, xF, xR, xC), - getX(batch, d1 + 1, xF, xR, xC), - getX(batch, d1 + 2, xF, xR, xC), - getX(batch, d1 + 3, xF, xR, xC)); - `} - let wValues = vec4( - getW(d2, d1, wF, wR, wC), - getW(d2, d1 + 1, wF, wR, wC), - getW(d2, d1 + 2, wF, wR, wC), - getW(d2, d1 + 3, wF, wR, wC)); - value += dot(xValues, wValues); - } - if (inputDepthVec4Remainder == 1) { - ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) - * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} - } else if (inputDepthVec4Remainder == 2) { - ${a?`let xValues = vec2( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); - `:`let xValues = vec2( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); - `} - let wValues = vec2( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); - value += dot(xValues, wValues); - } else if (inputDepthVec4Remainder == 3) { - ${a?`let xValues = vec3( - getX(batch, xF, xR, xC, inputDepthNearestVec4), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), - getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); - `:`let xValues = vec3( - getX(batch, inputDepthNearestVec4, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), - getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); - `} - let wValues = vec3( - getW(d2, inputDepthNearestVec4, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), - getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); - value += dot(xValues, wValues); - } - } - } - } - ${S?"value = value + getBiasByOutputCoords(coords)":""}; - ${Q} - result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${f};${S}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:m[0],y:m[1],z:m[2]},programUniforms:g}),getShaderSource:$}}});var Fu,qu,ju=U(()=>{"use strict";ee();ne();ie();bt();Fu=(e,t,r,n)=>{let o=e.length>2,i=o?"value += b[output_channel];":"",a=e[0].dims,u=e[1].dims,d=t.format==="NHWC",c=d?r[3]:r[1],p=c/t.group,m=d&&p>=4?ce(c):1,f=k.size(r)/m,b=[{type:12,data:f},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:p}];qe(t,b),b.push(...N(a,[u[0],u[1],u[2],u[3]/m]));let g=o?["rank","rank","rank"]:["rank","rank"];b.push(...N([r[0],r[1],r[2],r[3]/m]));let _=S=>{let $=M("output",e[0].dataType,r.length,m),v=be($.type.tensor),x=Fe(t,$.type.value,v),T=P("x",e[0].dataType,a.length),E=P("w",e[1].dataType,u.length,m),I=[T,E];o&&I.push(P("b",e[2].dataType,e[2].dims,m));let z=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];je(t,z);let O=d?` - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { - continue; - } - - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - let xVal = ${T.get("batch","xHeight","xWidth","input_channel")}; - let wVal = ${E.get("wHeight","wWidth","wInChannel","output_channel")}; - value += xVal * wVal; - } - } - } - `:` - for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { - let input_channel = in_channel_offset + wInChannel; - for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { - let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; - - if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { - continue; - } - - for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { - let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; - if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { - continue; - } - - let xVal = ${T.get("batch","input_channel","xHeight","xWidth")}; - let wVal = ${E.get("output_channel","wInChannel","wHeight","wWidth")}; - value += xVal * wVal; - } - } - } - `;return` - ${S.registerUniforms(z).declareVariables(...I,$)} - - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let outputIndices = ${$.offsetToIndices("global_idx")}; - let batch: u32 = outputIndices[0]; - let output_channel: u32 = outputIndices[${d?3:1}]; - let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; - let group_id: u32 = output_channel * ${m} / uniforms.output_channels_per_group; - var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; - - var value: ${$.type.value} = ${$.type.value}(0); - ${O} - ${i} - ${x} - ${$.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${m}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:b}),getShaderSource:_}},qu=(e,t,r,n)=>{let o=e.length>2,i=ce(r[3]),a=ce(r[2]),u=k.size(r)/i/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/i],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/i],p=[r[0],r[1],r[2],r[3]/i],m=[{type:12,data:u},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];qe(t,m),m.push(...N(d,c,p));let f=(a-1)*t.strides[1]+c[1],b=g=>{let _=M("output",e[0].dataType,p.length,i),S=be(_.type.tensor),$=Fe(t,_.type.value,S),v=P("x",e[0].dataType,d.length,i),x=P("w",e[1].dataType,c.length,i),T=[v,x];o&&T.push(P("b",e[2].dataType,e[2].dims,i));let E=o?"value += b[output_channel];":"",I=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return je(t,I),` - ${g.registerUniforms(I).declareVariables(...T,_)} - ${g.mainStart()} - ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let width0 = uniforms.output_shape[3]; - let output_channel = global_idx % width0; - var index1 = global_idx / width0; - let width1 = uniforms.output_shape[2] / ${a}u; - let col = (index1 % width1) * ${a}u; - index1 = index1 / width1; - let row = index1 % uniforms.output_shape[1]; - let batch = index1 / uniforms.output_shape[1]; - - let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; - - var x_vals: array<${v.type.value}, ${f}>; - var values: array<${_.type.value}, ${a}>; - let input_channel = output_channel; - // Use constant instead of uniform can give better performance for w's height/width. - for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) { - let x_height = x_corner.x + i32(w_height); - if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { - for (var i = 0; i < ${f}; i++) { - let x_width = x_corner.y + i; - if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { - x_vals[i] = ${v.get("batch","u32(x_height)","u32(x_width)","input_channel")}; - } else { - x_vals[i] = ${v.type.value}(0); - } - } - for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { - let w_val = ${x.get("w_height","w_width","0","output_channel")}; - for (var i = 0u; i < ${a}u; i++) { - values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); - } - } - } - } - - for (var i = 0u; i < ${a}u; i++) { - var value = values[i]; - ${E} - ${$} - ${_.set("batch","row","col + i","output_channel","value")}; - } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${i};${a};${f};${c[0]};${c[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(r):r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:m}),getShaderSource:b}}});var gf,ho,bf,go,bo,Ku,yf,_f,yo,Zu=U(()=>{"use strict";ne();Nu();Hu();Xr();ju();bt();Yr();st();gf=(e,t,r,n,o,i)=>{let a=e[0],u=e.slice(i?1:2,i?3:4),d=u.length,c=t[0],m=t.slice(2).map((g,_)=>g+(g-1)*(r[_]-1)),b=u.map((g,_)=>g+n[_]+n[_+d]).map((g,_)=>Math.floor((g-m[_]+o[_])/o[_]));return b.splice(0,0,a),b.splice(i?3:1,0,c),b},ho=[2,3,1,0],bf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},go=(e,t)=>{let r=e.kernelShape.slice();r.length{let t=Kr(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,i=e.group,a=e.kernel_shape,u=e.pads,d=e.strides,c=e.w_is_const();return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},Ku=(e,t,r,n)=>{let o=r.format==="NHWC",i=gf(t[0].dims,t[1].dims,r.dilations,r.pads,r.strides,o);if(r.group!==1){let I=[t[0]];if(o){let O=e.kernelCustomData.wT??e.compute(Ee(t[1],ho),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=O),I.push(O)}else I.push(t[1]);t.length===3&&I.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&t[1].dims[0]===r.group&&t[1].dims[1]===1&&r.dilations[0]===1&&r.dilations[1]===1?e.compute(qu(I,r,i,n),{inputs:I}):e.compute(Fu(I,r,i,n),{inputs:I});return}let a=t.length===3,u=t[0].dims[o?1:2],d=t[0].dims[o?2:3],c=t[0].dims[o?3:1],p=t[1].dims[2],m=t[1].dims[3],f=i[o?1:2],b=i[o?2:3],g=i[o?3:1],_=o&&p===u&&m===d&&r.pads[0]===0&&r.pads[1]===0;if(_||p===1&&m===1&&r.dilations[0]===1&&r.dilations[1]===1&&r.strides[0]===1&&r.strides[1]===1&&r.pads[0]===0&&r.pads[1]===0){let I=i[0],z,O,D,L=[];if(o){let W=e.kernelCustomData.wT??e.compute(Ee(t[1],ho),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];if(r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W),_){let Z=u*d*c;z=t[0].reshape([1,I,Z]),O=W.reshape([1,Z,g]),D=[1,I,g]}else z=t[0].reshape([I,u*d,c]),O=W.reshape([1,c,g]),D=[I,f*b,g];L.push(z),L.push(O)}else z=t[0].reshape([I,c,u*d]),O=t[1].reshape([1,g,c]),D=[I,g,f*b],L.push(O),L.push(z);a&&L.push(t[2]);let q=D[2],Q=L[0].dims[L[0].dims.length-1];q<8&&Q<8?e.compute(Qr(L,r,i,D,o,n),{inputs:L}):e.compute(Jt(L,r,i,D,o,n),{inputs:L});return}let S=!0,$=e.kernelCustomData.wT??e.compute(Ee(t[1],ho),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=$);let v=[t[0],$];a&&v.push(t[2]);let x=o?f*b:g,T=o?g:f*b,E=p*m*c;e.compute(Uu(v,r,i,x,T,E,a,S,n),{inputs:v})},yf=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=[0,t.pads[0],0,t.pads[1]],i=[1].concat(t.strides),a=[1].concat(t.dilations),u=[1].concat(t.kernelShape),d=go({...t,pads:o,strides:i,dilations:a,kernelShape:u},n);Ku(e,n,d,c=>r?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},_f=(e,t,r)=>{let n=r.format==="NHWC"?"channelsLast":"channelsFirst",o=go(r,t),i=r.autoPad==="NOTSET"?r.pads:r.autoPad,a=Lu(t[0].dims,t[1].dims,r.strides,r.dilations,i,!1,n);e.compute(Gu(t,o,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},yo=(e,t)=>{if(bf(e.inputs,t),e.inputs[0].dims.length===3)yf(e,t);else if(e.inputs[0].dims.length===5)_f(e,e.inputs,t);else{let r=go(t,e.inputs);Ku(e,e.inputs,r)}}});var Qu,Yu=U(()=>{"use strict";ee();Xe();ne();ie();Qu=(e,t,r)=>{let n=e.length>2,o=t.outputShape,i=t.format==="NHWC",a=t.group,u=e[1].dims,d=u[2]/a,c=u[3],p=i?ce(d):1,m=i&&c===1&&d>=4,f=m?Math.floor(d/4)*4:Math.floor(d/p)*p,b=d-f,g=i?ce(c):1,_=i?c===1?p:g:1,S=k.size(o)/g,$=[Math.ceil(S/64),1,1];se("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${$}`);let v=["rank","rank"],x=[t.strides[0],t.strides[1]],T=[t.kernelShape[i?1:2],t.kernelShape[i?2:3]],E=[t.dilations[0],t.dilations[1]],I=[T[0]+(t.dilations[0]<=1?0:(t.kernelShape[i?1:2]-1)*(t.dilations[0]-1)),T[1]+(t.dilations[1]<=1?0:(t.kernelShape[i?2:3]-1)*(t.dilations[1]-1))],z=[I[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),I[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],O=[{type:12,data:S},{type:12,data:x},{type:12,data:T},{type:12,data:E},{type:12,data:I},{type:6,data:z},{type:12,data:f},{type:12,data:d},{type:12,data:c},...N(e[0].dims,e[1].dims)];n&&(O.push(...N(e[2].dims)),v.push("rank")),O.push(...N(o));let D=L=>{let q=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:x.length},{name:"filter_dims",type:"u32",length:T.length},{name:"dilations",type:"u32",length:T.length},{name:"effective_filter_dims",type:"u32",length:I.length},{name:"pads",type:"i32",length:z.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Q=be(e[0].dataType),W=i?1:2,Z=i?2:3,we=i?3:1,H=P("W",e[1].dataType,e[1].dims.length,_),j=P("Dy",e[0].dataType,e[0].dims.length,p),te=[j,H];n&&te.push(P("bias",e[2].dataType,[o[we]].length,g));let X=M("result",e[0].dataType,o.length,g),ue=()=>{let re="";if(m)p===4?re+=` - let xValue = ${j.getByOffset("x_offset")}; - let wValue = ${H.getByOffset("w_offset")}; - dotProd = dotProd + dot(xValue, wValue); - x_offset += 1u; - w_offset += 1u;`:p===2?re+=` - dotProd = dotProd + dot(vec4<${Q}>(${j.getByOffset("x_offset")}, ${j.getByOffset("x_offset + 1u")}), vec4<${Q}>(${H.getByOffset("w_offset")}, ${H.getByOffset("w_offset + 1u")})); - x_offset += 2u; - w_offset += 2u;`:p===1&&(re+=` - dotProd = dotProd + dot(vec4<${Q}>(${j.getByOffset("x_offset")}, ${j.getByOffset("x_offset + 1u")}, ${j.getByOffset("x_offset + 2u")}, ${j.getByOffset("x_offset + 3u")}), vec4<${Q}>(${H.getByOffset("w_offset")}, ${H.getByOffset("w_offset + 1u")}, ${H.getByOffset("w_offset + 2u")}, ${H.getByOffset("w_offset + 3u")})); - x_offset += 4u; - w_offset += 4u;`);else if(re+=` - let xValue = ${i?j.getByOffset(`${j.indicesToOffset(`${j.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):j.get("batch","inputChannel","idyR","idyC")}; - `,p===1)re+=` - let w_offset = ${H.indicesToOffset(`${H.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; - let wValue = ${H.getByOffset(`w_offset / ${_}`)}; - dotProd = dotProd + xValue * wValue;`;else for(let C=0;C{if(b===0)return"";if(!m)throw new Error(`packInputAs4 ${m} is not true.`);let re="";if(p===1){re+="dotProd = dotProd";for(let C=0;C(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 = ${X.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[${W}]) || 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[${Z}]) || - fract(dyC) > 0.0 || wCPerm < 0) { - continue; - } - let idyC: u32 = u32(dyC); - var inputChannel = groupId * uniforms.input_channels_per_group; - ${m?` - var x_offset = ${j.indicesToOffset(`${j.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; - var w_offset = ${H.indicesToOffset(`${H.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${_}; - `:""} - for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${m?4:p}) { - ${ue()} - inputChannel = inputChannel + ${m?4:p}; - } - ${he()} - wC = wC + uniforms.strides.y - 1; - } - wR = wR + uniforms.strides[0] - 1; - } - let value = dotProd${n?` + bias[d1 / ${g}]`:""}; - ${X.setByOffset("global_idx","value")}; - `;return` - ${L.registerUniforms(q).declareVariables(...te,X)} - ${L.mainStart()} - ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${ye}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${p}${_}${g}${m}${b}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:$[0],y:$[1],z:$[2]},outputs:[{dims:r?r(o):o,dataType:e[0].dataType}],programUniforms:O}),getShaderSource:D}}});var wf,vf,$f,Xu,Ju,xf,ed,Sf,td,rd=U(()=>{"use strict";Yu();bt();st();wf=(e,t,r,n,o,i)=>(e-1)*t+r+(n-1)*o+1-i,vf=(e,t,r,n,o)=>{let i=Math.floor(e/2);t==="SAME_UPPER"?(r[n]=i,r[o]=e-i):t==="SAME_LOWER"&&(r[n]=e-i,r[o]=i)},$f=(e,t,r,n,o,i,a,u,d,c)=>{let p=e.length-2,m=c.length===0;d.length{let r=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((m,f)=>m*f,1)===0){r.length=0;for(let m=2;mm+f,0)===0){let m=t[0].dims.length-2;d=new Array(m).fill(1)}let c=e.strides.slice();if(c.reduce((m,f)=>m+f,0)===0){let m=t[0].dims.length-2;c=new Array(m).fill(1)}$f(u,r,d,e.autoPad,e.group,o,c,n,a,i);let p=Object.assign({},e);return Object.assign(p,{kernelShape:r,pads:o,outputPadding:a,outputShape:i,dilations:d,strides:c}),p},Ju=e=>{let t=Kr(e),r=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,i=e.group,a=e.kernelShape,u=e.pads,d=e.strides,c=e.wIsConst(),p=e.outputPadding,m=e.outputShape;return{autoPad:n,format:r,dilations:o,group:i,kernelShape:a,outputPadding:p,outputShape:m,pads:u,strides:d,wIsConst:c,...t,cacheKey:`${e.format};${t.activation};`}},xf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let r=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(r!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let i=e[0].dims.length-2;if(t.dilations.reduce((p,m)=>p+m,0)>0&&t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.reduce((p,m)=>p+m,0)>0&&t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.reduce((p,m)=>p+m,0)>0&&t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.outputPadding.length!==i&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${i}D`);if(t.kernelShape.reduce((p,m)=>p+m,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},ed=(e,t,r,n)=>{let o=e.kernelCustomData.wT??e.compute(Ee(t[1],[2,3,0,1]),{inputs:[1],outputs:[r.wIsConst?-2:-1]})[0];r.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let i=[t[0],o];t.length===3&&i.push(t[2]),e.compute(Qu(i,r,n),{inputs:i})},Sf=(e,t)=>{let r=t.format==="NHWC",n=[e.inputs[0].reshape(r?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&n.push(e.inputs[2]);let o=t.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let i=t.dilations;(i.length===0||i[0]===0)&&(i=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let u=t.pads;u.length===0&&(u=[0,0]),u=[0,u[0],0,u[1]],a=[1].concat(a),i=[1].concat(i),o=[1].concat(o);let d=t.outputPadding;d=[0].concat(d);let c=Xu({...t,pads:u,strides:a,dilations:i,kernelShape:o,outputPadding:d},n);ed(e,n,c,p=>r?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},td=(e,t)=>{if(xf(e.inputs,t),e.inputs[0].dims.length===3)Sf(e,t);else{let r=Xu(t,e.inputs);ed(e,e.inputs,r)}}});var Tf,nd,od,id=U(()=>{"use strict";ee();ne();Se();ie();Tf=(e,t,r,n)=>{let o=k.size(t),i=t.length,a=P("input",e,i),u=M("output",e,i),d=r.dataType===6?r.getInt32Array()[0]:Number(r.getBigInt64Array()[0]),c=k.normalizeAxis(d,i),p=m=>{let f=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,b=F("uniforms.input_shape","uniforms.axis",i),g=n.reverse?f+(n.exclusive?" + 1":""):"0",_=n.reverse?b:f+(n.exclusive?"":" + 1");return` - ${m.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,u)} - ${m.mainStart()} - ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var inputIndices = ${u.offsetToIndices("global_idx")}; - var sum = ${u.type.value}(0); - let first : i32 = ${g}; - let last : i32 = ${_}; - for (var i : i32 = first; i < last; i++) { - ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; - sum = sum + ${a.getByIndices("inputIndices")}; - } - ${u.setByOffset("global_idx","sum")}; - }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...N(t,t)]}),getShaderSource:p}},nd=(e,t)=>{let r=e.inputs[0].dims,n=e.inputs[0].dataType,o=e.inputs[1];e.compute(Tf(n,r,o,t),{inputs:[0]})},od=e=>{let t=e.exclusive===1,r=e.reverse===1;return J({exclusive:t,reverse:r})}});var If,Cf,Af,ad,sd,ud=U(()=>{"use strict";ee();ne();Se();ie();If=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.")},Cf=(e,t,r,n)=>{let o=[];o.push(`fn perm(i: ${n.type.indices}) -> ${r.type.indices} { - var a: ${r.type.indices};`);for(let i=0;i{let r,n,o,i,a,u,d=t.format==="NHWC",c=t.blocksize,p=t.mode==="DCR";d?([r,n,o,i]=e.dims,a=p?[r,n,o,c,c,i/c**2]:[r,n,o,i/c**2,c,c],u=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([r,n,o,i]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=p?[r,c,c,i/c**2,n,o]:[r,i/c**2,c,c,n,o],u=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let m=e.reshape(a),f=m.dims.length,b=e.dataType,g=P("a",b,f),_=M("output",b,f),S=$=>` - ${$.registerUniform("output_size","u32").declareVariables(g,_)} - - ${Cf(u,f,g,_)} - - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${_.offsetToIndices("global_idx")}; - let aIndices = perm(indices); - - ${_.setByOffset("global_idx",g.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:$=>{let v=d?[r,n*c,o*c,i/c**2]:[r,i/c**2,n*c,o*c],x=k.size(v),T=m.dims,E=k.sortBasedOnPerm(T,u);return{outputs:[{dims:v,dataType:$[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:[{type:12,data:x},...N(T,E)]}},getShaderSource:S}},ad=(e,t)=>{If(e.inputs),e.compute(Af(e.inputs[0],t))},sd=e=>J({blocksize:e.blocksize,mode:e.mode,format:e.format})});var _o,en,dd,Ef,kf,wo,vo,ld,Pf,cd,pd,md=U(()=>{"use strict";ee();ne();Se();ie();_o="[a-zA-Z]|\\.\\.\\.",en="("+_o+")+",dd="^"+en+"$",Ef="("+en+",)*"+en,kf="^"+Ef+"$",wo=class{constructor(t=-1){this.symbolToIndices=new Map,this.inputIndex=t}addSymbol(t,r){let n=this.symbolToIndices.get(t);n===void 0?n=[r]:n.push(r),this.symbolToIndices.set(t,n)}},vo=class{constructor(t,r){this.equation=r;this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,o]=r.includes("->")?r.split("->",2):[r,""];if(!n.match(RegExp(kf)))throw new Error("Invalid LHS term");if(n.split(",").forEach((u,d)=>{let c=t[d].dims.slice();if(!u.match(RegExp(dd)))throw new Error("Invalid LHS term");let p=this.processTerm(u,!0,c,d);this.lhs.push(p)}),o==="")o+=[...this.symbolToInfo.entries()].filter(([u,d])=>d.count===1||u==="...").map(([u])=>u).join("");else if(!o.match(RegExp(en)))throw new Error("Invalid RHS");o.match(RegExp(_o,"g"))?.forEach(u=>{if(u==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let d=this.symbolToInfo.get(u);if(d===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(d.dimValue)}}),this.rhs=this.processTerm(o,!1,this.outputDims)}addSymbol(t,r,n){let o=this.symbolToInfo.get(t);if(o!==void 0){if(o.dimValue!==r&&o.count!==1)throw new Error("Dimension mismatch");o.count++,o.inputIndices.push(n)}else o={count:1,dimValue:r,inputIndices:[n]};this.symbolToInfo.set(t,o)}processTerm(t,r,n,o=-1){let i=n.length,a=!1,u=[],d=0;if(!t.match(RegExp(dd))&&!r&&t!=="")throw new Error("Invalid LHS term");let c=t.match(RegExp(_o,"g")),p=new wo(o);return c?.forEach((m,f)=>{if(m==="..."){if(a)throw new Error("Only one ellipsis is allowed per input term");a=!0;let b=i-c.length+1;if(b<0)throw new Error("Ellipsis out of bounds");if(u=n.slice(d,d+b),this.hasEllipsis){if(this.ellipsisDims.length!==u.length||this.ellipsisDims.toString()!==u.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=u;else throw new Error("Ellipsis must be specified in the LHS");for(let g=0;ge+"_max",Pf=(e,t,r,n)=>{let i=e.map(p=>p.length).map((p,m)=>P(`input${m}`,t,p)),a=k.size(n),u=M("output",t,n.length),d=[...r.symbolToInfo.keys()].filter(p=>!r.rhs.symbolToIndices.has(p)),c=p=>{let m=[],f="var prod = 1.0;",b="var sum = 0.0;",g="sum += prod;",_=[],S=[],$=[],v=[],x=r.symbolToInfo.size===r.rhs.symbolToIndices.size;r.symbolToInfo.forEach((E,I)=>{if(r.rhs.symbolToIndices.has(I)){let z=r.rhs.symbolToIndices.get(I)?.[0];z!==void 0&&r.lhs.forEach((O,D)=>{if(E.inputIndices.includes(D)){let L=O.symbolToIndices.get(I);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(q=>{m.push(`${i[D].indicesSet(`input${D}Indices`,q,u.indicesGet("outputIndices",z))}`)})}})}else r.lhs.forEach((z,O)=>{if(E.inputIndices.includes(O)){let D=z.symbolToIndices.get(I);if(D===void 0)throw new Error("Invalid symbol error");D.forEach(L=>{_.push(`${i[O].indicesSet(`input${O}Indices`,L,`${I}`)}`)}),v.push(`prod *= ${i[O].getByIndices(`input${O}Indices`)};`)}}),S.push(`for(var ${I}: u32 = 0; ${I} < uniforms.${ld(I)}; ${I}++) {`),$.push("}")});let T=x?[...m,`let sum = ${i.map((E,I)=>E.getByIndices(`input${I}Indices`)).join(" * ")};`]:[...m,b,...S,..._,f,...v,g,...$];return` - ${p.registerUniforms(d.map(E=>({name:`${ld(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,u)} - - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - var outputIndices = ${u.offsetToIndices("global_idx")}; - ${i.map((E,I)=>`var input${I}Indices: ${i[I].type.indices};`).join(` -`)} - ${T.join(` -`)}; - ${u.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:r.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let p=d.filter(f=>r.symbolToInfo.has(f)).map(f=>({type:12,data:r.symbolToInfo.get(f)?.dimValue||0}));p.push({type:12,data:a});let m=e.map((f,b)=>[...N(f)]).reduce((f,b)=>f.concat(b),p);return m.push(...N(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:m}},getShaderSource:c}},cd=(e,t)=>{let r=new vo(e.inputs,t.equation),n=r.outputDims,o=e.inputs.map((i,a)=>i.dims);e.compute(Pf(o,e.inputs[0].dataType,r,n))},pd=e=>{let t=e.equation.replace(/\s+/g,"");return J({equation:t})}});var zf,fd,Of,Bf,hd,gd=U(()=>{"use strict";ee();ne();ie();zf=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=r.length{let r=e.length-t.length,n=[];for(let o=0;oe.length>t.length?fd(e,t):fd(t,e),Bf=e=>{let t=e[0].dims,r=Array.from(e[1].getBigInt64Array(),Number),n=Of(t,r),o=e[0].dataType,i=o===9||k.size(t)===1,a=o===9||t.length>0&&t[t.length-1]%4===0?4:1,u=i||n.length>0&&n[n.length-1]%4===0?4:1,d=Math.ceil(k.size(n)/u),c=m=>{let f=P("input",o,t.length,a),b=M("output",o,n.length,u),g;if(o===9){let _=(S,$,v="")=>` - let outputIndices${$} = ${b.offsetToIndices(`outputOffset + ${$}u`)}; - let offset${$} = ${f.broadcastedIndicesToOffset(`outputIndices${$}`,b)}; - let index${$} = offset${$} / 4u; - let component${$} = offset${$} % 4u; - ${S}[${$}] = ${v}(${f.getByOffset(`index${$}`)}[component${$}]); - `;g=` - let outputOffset = global_idx * ${u}; - var data = vec4(0); - ${_("data",0,"u32")} - ${_("data",1,"u32")} - ${_("data",2,"u32")} - ${_("data",3,"u32")} - ${b.setByOffset("global_idx","data")} - }`}else g=` - let outputIndices = ${b.offsetToIndices(`global_idx * ${u}`)}; - let inputOffset = ${f.broadcastedIndicesToOffset("outputIndices",b)}; - let data = ${b.type.value}(${f.getByOffset(`inputOffset / ${a}`)}); - ${b.setByOffset("global_idx","data")} - }`;return` - ${m.registerUniform("vec_size","u32").declareVariables(f,b)} - ${m.mainStart()} - ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${g}`},p=[{type:12,data:d},...N(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${a}${u}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p})}},hd=e=>{zf(e.inputs),e.compute(Bf(e.inputs),{inputs:[0]})}});var Df,bd,yd=U(()=>{"use strict";ee();ne();ie();jr();Df=e=>{let t=e[0].dataType,r=k.size(e[0].dims),n=k.size(e[1].dims),o=n%4===0,i=a=>{let u=P("x",t,[1],4),d=P("bias",t,[1],4),c=M("y",t,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],m=b=>` - let bias${b}_offset: u32 = (global_idx * 4 + ${b}) % uniforms.bias_size; - let bias${b} = ${d.getByOffset(`bias${b}_offset / 4`)}[bias${b}_offset % 4];`,f=o?` - let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${m(0)}${m(1)}${m(2)}${m(3)} - let bias = ${u.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(p).declareVariables(u,d,c)} - - ${co(Ae(t))} - - ${a.mainStart(It)} - ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} - - let x = ${u.getByOffset("global_idx")}; - ${f} - let x_in = x + bias; - ${c.setByOffset("global_idx",po("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:i,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(r/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(r/It/4)}})}},bd=e=>{e.inputs.length<2||k.size(e.inputs[1].dims)===0?mu(e):e.compute(Df(e.inputs))}});var Mf,Rf,_d,wd,vd=U(()=>{"use strict";ee();ne();Se();ie();Mf=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Rf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.axis,o),a=r.slice(0);a.splice(i,1,...n);let u=r[i],d=e[0].dataType===9?4:1,c=Math.ceil(k.size(a)/d),p=[{type:12,data:c},{type:6,data:u},{type:12,data:i},...N(e[0].dims,e[1].dims,a)],m=f=>{let b=P("data",e[0].dataType,e[0].dims.length,d),g=P("inputIndices",e[1].dataType,e[1].dims.length),_=M("output",e[0].dataType,a.length,d),S=v=>{let x=n.length,T=`var indicesIndices${v} = ${g.type.indices}(0);`;for(let E=0;E1?`indicesIndices${v}[${E}]`:`indicesIndices${v}`} = ${a.length>1?`outputIndices${v}[uniforms.axis + ${E}]`:`outputIndices${v}`};`;T+=` - var idx${v} = ${g.getByIndices(`indicesIndices${v}`)}; - if (idx${v} < 0) { - idx${v} = idx${v} + uniforms.axisDimLimit; - } - var dataIndices${v} : ${b.type.indices}; - `;for(let E=0,I=0;E1?`dataIndices${v}[${E}]`:`dataIndices${v}`} = u32(idx${v});`,I+=x):(T+=`${o>1?`dataIndices${v}[${E}]`:`dataIndices${v}`} = ${a.length>1?`outputIndices${v}[${I}]`:`outputIndices${v}`};`,I++);return T},$;if(e[0].dataType===9){let v=(x,T,E="")=>` - let outputIndices${T} = ${_.offsetToIndices(`outputOffset + ${T}u`)}; - ${S(T)}; - let offset${T} = ${b.indicesToOffset(`dataIndices${T}`)}; - let index${T} = offset${T} / 4u; - let component${T} = offset${T} % 4u; - ${x}[${T}] = ${E}(${b.getByOffset(`index${T}`)}[component${T}]); - `;$=` - let outputOffset = global_idx * ${d}; - var value = vec4(0); - ${v("value",0,"u32")} - ${v("value",1,"u32")} - ${v("value",2,"u32")} - ${v("value",3,"u32")} - ${_.setByOffset("global_idx","value")} - `}else $=` - let outputIndices = ${_.offsetToIndices("global_idx")}; - ${S("")}; - let value = ${b.getByIndices("dataIndices")}; - ${_.setByOffset("global_idx","value")}; - `;return` - ${f.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(b,g,_)} - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - ${$} - }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:m}},_d=e=>J({axis:e.axis}),wd=(e,t)=>{let r=e.inputs;Mf(r),e.compute(Rf(e.inputs,t))}});var Uf,$d,xd,Sd=U(()=>{"use strict";ee();ne();ie();Uf=(e,t,r,n,o,i,a,u,d)=>{let c=[{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:12,data:r},{type:12,data:a},{type:12,data:u},{type:12,data:d}],p=[i];c.push(...N(t.dims,p));let m=f=>{let b=P("indices_data",t.dataType,t.dims.length),g=M("input_slice_offsets_data",12,1,1),_=[b,g],S=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:r.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` - ${f.registerUniforms(S).declareVariables(..._)} - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let batch_idx = global_idx / uniforms.num_slices_per_batch; - let base_offset = batch_idx * uniforms.input_batch_stride; - - let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; - var relative_slice_offset = 0; - for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { - var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); - let input_dim_idx = uniforms.batch_dims + dim_idx; - if (index < 0) { - ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} - } - ${r.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} - } - - input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); - }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${r.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:c}),getShaderSource:m},{inputs:[t],outputs:[-1]})[0]},$d=(e,t)=>{let r=e.inputs,n=r[0].dims,o=r[0].dataType,i=r[1].dims,a=i[i.length-1],u=k.sizeToDimension(i,i.length-1),d=k.sizeFromDimension(n,t.batchDims+a),c=k.sizeToDimension(n,t.batchDims),p=k.sizeFromDimension(n,t.batchDims),m=u/c,f=new Array(a),b=d;for(let T=0;Tn.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let S=i.slice(0,-1).concat(n.slice(_)),$=k.size(S),v=[{type:12,data:$},{type:12,data:d},...N(r[0].dims,g.dims,S)],x=T=>{let E=P("data",r[0].dataType,r[0].dims.length),I=P("slice_offsets",12,g.dims.length),z=M("output",r[0].dataType,S.length);return` - ${T.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(E,I,z)} - ${T.mainStart()} - ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; - output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; - }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:S,dataType:o}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:v}),getShaderSource:x},{inputs:[r[0],g]})},xd=e=>({batchDims:e.batch_dims,cacheKey:""})});var Nf,Vf,Td,Id,Cd=U(()=>{"use strict";ee();ne();Se();ie();Nf=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let r=k.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,o=e[0],i=e[2],a=e.length===4?e[3]:void 0;if(i.dims.length!==o.dims.length||!o.dims.map((u,d)=>d===r?Math.ceil(u/n)===i.dims[d]:u===i.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==i.dims.length||!a.dims.map((u,d)=>u===i.dims[d]).reduce((u,d)=>u&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Vf=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r.length,i=k.normalizeAxis(t.gatherAxis,o),a=k.normalizeAxis(t.quantizeAxis,o),u=r.slice(0);u.splice(i,1,...n);let d=k.size(u),c=e[2].dataType,m=e[0].dataType===22,f=[{type:12,data:d},{type:12,data:a},{type:12,data:i},{type:12,data:t.blockSize},...N(...e.map((g,_)=>g.dims),u)],b=g=>{let _=P("data",e[0].dataType,e[0].dims.length),S=P("inputIndices",e[1].dataType,e[1].dims.length),$=P("scales",e[2].dataType,e[2].dims.length),v=e.length>3?P("zeroPoint",e[3].dataType,e[3].dims.length):void 0,x=M("output",c,u.length),T=[_,S,$];v&&T.push(v);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${g.registerUniforms(E).declareVariables(...T,x)} - ${g.mainStart()} - let output_indices = ${x.offsetToIndices("global_idx")}; - var indices_indices = ${S.type.indices}(0); - ${n.length>1?` - for (var i: u32 = 0; i < ${n.length}; i++) { - let index = ${x.indicesGet("output_indices","uniforms.gather_axis + i")}; - ${S.indicesSet("indices_indices","i","index")}; - }`:`indices_indices = ${x.indicesGet("output_indices","uniforms.gather_axis")};`}; - var data_indices = ${_.type.indices}(0); - for (var i: u32 = 0; i < uniforms.gather_axis; i++) { - let index = ${x.indicesGet("output_indices","i")}; - ${_.indicesSet("data_indices","i","index")}; - } - var index_from_indices = ${S.getByIndices("indices_indices")}; - if (index_from_indices < 0) { - index_from_indices += ${r[i]}; - } - ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; - for (var i = uniforms.gather_axis + 1; i < ${u.length}; i++) { - let index = ${x.indicesGet("output_indices",`i + ${n.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 = ${m?"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 = ${$.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; - ${$.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; - var scale = ${$.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 = ${m?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); - let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; - let dequantized_data = ${Ae(c)}(quantized_data - zero_point) * scale; - ${x.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((g,_)=>_!==1).map(g=>g.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(g,_)=>"rank")},getRunData:()=>({outputs:[{dims:u,dataType:c}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}),getShaderSource:b}},Td=(e,t)=>{let r=e.inputs;Nf(r,t),e.compute(Vf(e.inputs,t))},Id=e=>J({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})});var Wf,Lf,Ad,Ed,kd=U(()=>{"use strict";ee();ne();Se();ie();Wf=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and - indices input tensors be of same rank.`)},Lf=(e,t)=>{let r=e[0].dims,n=e[0].dataType,o=r.length,i=e[1].dims,a=e[1].dataType,u=k.normalizeAxis(t.axis,o),d=r[u],c=i.slice(0),p=k.size(c),m=P("input",n,o),f=P("indicesInput",a,i.length),b=M("output",n,c.length),g=[{type:12,data:p},{type:6,data:d},{type:12,data:u}];return g.push(...N(r,i,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:g}),getShaderSource:$=>` - ${$.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(m,f,b)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let outputIndices = ${b.offsetToIndices("global_idx")}; - - var idx = ${f.getByOffset("global_idx")}; - if (idx < 0) { - idx = idx + uniforms.axisDimLimit; - } - var inputIndices = ${m.type.indices}(outputIndices); - ${m.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; - let value = ${m.getByIndices("inputIndices")}; - - ${b.setByOffset("global_idx","value")}; - }`}},Ad=e=>J({axis:e.axis}),Ed=(e,t)=>{let r=e.inputs;Wf(r),e.compute(Lf(e.inputs,t))}});var Gf,Hf,Pd,zd,Od=U(()=>{"use strict";ee();ne();ie();Gf=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Hf=(e,t)=>{let r=e[0].dims.slice(),n=e[1].dims.slice(),[o,i,a]=Dr.getShapeOfGemmResult(r,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),u=[o,i];if(!u)throw new Error("Can't use gemm on the given tensors");let d=16,c=Math.ceil(i/d),p=Math.ceil(o/d),m=!0,f=k.size(u),b=[{type:12,data:m?c:f},{type:12,data:o},{type:12,data:i},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],g=["type","type"];e.length===3&&(b.push(...N(e[2].dims)),g.push("rank")),b.push(...N(u));let _=$=>{let v="";t.transA&&t.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let x=t.alpha===1?"":"value *= uniforms.alpha;",T=P("a",e[0].dataType,e[0].dims),E=P("b",e[1].dataType,e[1].dims),I=T.type.value,z=null,O=[T,E];e.length===3&&(z=P("c",e[2].dataType,e[2].dims.length),O.push(z));let D=M("output",e[0].dataType,u.length);O.push(D);let L=[{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` - ${$.registerUniforms(L).declareVariables(...O)} - - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let m = global_idx / uniforms.N; - let n = global_idx % uniforms.N; - - var value = ${I}(0); - for (var k: u32 = 0u; k < uniforms.K; k++) { - ${v} - } - - ${x} - ${z!=null?`let cOffset = ${z.broadcastedIndicesToOffset("vec2(m, n)",D)}; value += ${I}(uniforms.beta) * ${z.getByOffset("cOffset")};`:""} - output[global_idx] = value; - }`},S=$=>{let v=P("a",e[0].dataType,e[0].dims),x=P("b",e[1].dataType,e[1].dims),T=null,E=[v,x];e.length===3&&(T=P("c",e[2].dataType,e[2].dims.length),E.push(T));let I=M("output",e[0].dataType,u.length);E.push(I);let z=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],O="",D="";t.transA&&t.transB?(D=` - var col = tile_row_start + local_id.x; - var row = k_start + local_id.y; - if (col < uniforms.M && row < uniforms.K) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; - } else { - tile_a[local_id.y][local_id.x] = ${v.type.value}(0); - } - - col = k_start + local_id.x; - row = tile_col_start + local_id.y; - if (col < uniforms.K && row < uniforms.N) { - tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; - } else { - tile_b[local_id.y][local_id.x] = ${x.type.value}(0); - } - `,O="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(D=` - var col = tile_row_start + local_id.x; - var row = k_start + local_id.y; - if (col < uniforms.M && row < uniforms.K) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; - } else { - tile_a[local_id.y][local_id.x] = ${v.type.value}(0); - } - - col = tile_col_start + local_id.x; - row = k_start + local_id.y; - if (col < uniforms.N && row < uniforms.K) { - tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; - } else { - tile_b[local_id.y][local_id.x] = ${x.type.value}(0); - } - `,O="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(D=` - var col = k_start + local_id.x; - var row = tile_row_start + local_id.y; - if (col < uniforms.K && row < uniforms.M) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; - } else { - tile_a[local_id.y][local_id.x] = ${v.type.value}(0); - } - - col = k_start + local_id.x; - row = tile_col_start + local_id.y; - if (col < uniforms.K && row < uniforms.N) { - tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; - } else { - tile_b[local_id.y][local_id.x] = ${x.type.value}(0); - } - `,O="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(D=` - var col = k_start + local_id.x; - var row = tile_row_start + local_id.y; - if (col < uniforms.K && row < uniforms.M) { - tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; - } else { - tile_a[local_id.y][local_id.x] = ${v.type.value}(0); - } - - col = tile_col_start + local_id.x; - row = k_start + local_id.y; - if (col < uniforms.N && row < uniforms.K) { - tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; - } else { - tile_b[local_id.y][local_id.x] = ${x.type.value}(0); - } - `,O="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let L=t.alpha===1?"":"value *= uniforms.alpha;";return` - ${$.registerUniforms(z).declareVariables(...E)} - var tile_a: array, ${d}>; - var tile_b: array, ${d}>; - ${$.mainStart([d,d,1])} - let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d}; - let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d}; - let num_tiles = (uniforms.K - 1) / ${d} + 1; - var k_start = 0u; - var value = ${I.type.value}(0); - for (var t: u32 = 0u; t < num_tiles; t++) { - ${D} - k_start = k_start + ${d}; - workgroupBarrier(); - - for (var k: u32 = 0u; k < ${d}; k++) { - ${O} - } - workgroupBarrier(); - } - - ${L} - let m = tile_row_start + local_id.y; - let n = tile_col_start + local_id.x; - ${T!=null?`let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)",I)}; value += ${I.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};`:""} - if (m < uniforms.M && n < uniforms.N) { - output[m * uniforms.N + n] = value; - } - }`};return m?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:b}),getShaderSource:S}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:b}),getShaderSource:_}},Pd=e=>{let t=e.transA,r=e.transB,n=e.alpha,o=e.beta;return{transA:t,transB:r,alpha:n,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},zd=(e,t)=>{Gf(e.inputs),e.compute(Hf(e.inputs,t))}});var ut,yt,Ut,Nt,Ff,qf,jf,Kf,Zf,Qf,Yf,Xf,Bd,Dd,Md=U(()=>{"use strict";ee();ne();Se();ie();[ut,yt,Ut,Nt]=[0,1,2,3],Ff=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},qf=` - 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; - } -`,jf=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; - } -`,Kf=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)); - `} - } -`,Zf=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); - }`:""} -`,Qf=(e,t,r)=>` - fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { - var pixel = ${t}(0); - var indices = vec4(0); - indices[${ut}] = batch; - indices[${yt}] = channel;`+(()=>{switch(r.paddingMode){case"zeros":return` - if (r >= 0 && r < H && c >=0 && c < W) { - indices[${Ut}] = u32(r); - indices[${Nt}] = u32(c); - } else { - return ${t}(0); - } - `;case"border":return` - indices[${Ut}] = u32(clamp(r, 0, H - 1)); - indices[${Nt}] = u32(clamp(c, 0, W - 1)); - `;case"reflection":return` - indices[${Ut}] = gs_reflect(r, border[1], border[3]); - indices[${Nt}] = gs_reflect(c, border[0], border[2]); - `;default:throw new Error(`padding mode ${r.paddingMode} is not supported`)}})()+` - return ${e.getByIndices("indices")}; - } -`,Yf=(e,t,r)=>(()=>{switch(r.mode){case"nearest":return` - let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ut}], indices[${yt}], 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[${ut}], indices[${yt}], border); - let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ut}], indices[${yt}], border); - let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ut}], indices[${yt}], border); - let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ut}], indices[${yt}], border); - - let dx2 = ${t}(f32(x2) - x); - let dx1 = ${t}(x - f32(x1)); - let dy2 = ${t}(f32(y2) - y); - let dy1 = ${t}(y - f32(y1)); - let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); - `;case"bicubic":return` - let x0 = i32(floor(x)) - 1; - let y0 = i32(floor(y)) - 1; - var p: mat4x4<${t}>; - for (var h = 0; h < 4; h++) { - for (var w = 0; w < 4; w++) { - p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${ut}], indices[${yt}], 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 ${r.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Xf=(e,t)=>{let r=P("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=P("grid",e[1].dataType,n.length,2),i=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(i=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ut,yt,Ut,Nt]=[0,3,1,2]);let a=M("output",e[0].dataType,i.length),u=r.type.value,d=k.size(i),c=[{type:12,data:d},...N(e[0].dims,n,i)],p=m=>` - ${m.registerUniform("output_size","u32").declareVariables(r,o,a)} - ${qf} - ${jf(u)} - ${Kf(t)} - ${Zf(t)} - ${Qf(r,u,t)} - - ${m.mainStart()} - ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let H_in = i32(uniforms.x_shape[${Ut}]); - let W_in = i32(uniforms.x_shape[${Nt}]); - - ${t.alignCorners===0?` - let x_min = -0.5; - let x_max = f32(W_in) - 0.5; - let y_min = -0.5; - let y_max = f32(H_in) - 0.5; - `:` - let x_min = 0.0; - let x_max = f32(W_in) - 1.0; - let y_min = 0.0; - let y_max = f32(H_in) - 1.0; - `}; - let border = vec4(x_min, y_min, x_max, y_max); - - let indices = ${a.offsetToIndices("global_idx")}; - var grid_indices = vec3(indices[${ut}], indices[${Ut}], indices[${Nt}]); - let nxy = ${o.getByIndices("grid_indices")}; - var x = gs_denormalize(f32(nxy[0]), W_in); - var y = gs_denormalize(f32(nxy[1]), H_in); - - ${Yf(a,u,t)} - }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:m=>{let f=k.size(i);return{outputs:[{dims:i,dataType:m[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:c}},getShaderSource:p}},Bd=(e,t)=>{Ff(e.inputs),e.compute(Xf(e.inputs,t))},Dd=e=>J({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})});var Be,th,Ud,Rd,rh,er,Nd,$o=U(()=>{"use strict";ee();ne();Se();Vr();Fr();ie();st();Be=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,th=(e,t)=>{let r=e[0],n=Be(e,1),o=Be(e,2),i=Be(e,3),a=Be(e,4),u=Be(e,5),d=Be(e,6),c=Be(e,7);if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=r.dims[0],m=r.dims[1],f=r.dims.length===3?r.dims[2]:t.numHeads*r.dims[4],b=m,g=0,_=0,S=Math.floor(f/t.numHeads);if(d&&c&&k.size(d.dims)&&k.size(c.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==p||d.dims[1]!==t.numHeads||d.dims[3]!==S)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==t.numHeads||c.dims[3]!==S)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');g=d.dims[2],_=d.dims[2]}else if(d&&k.size(d.dims)||c&&k.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let $;if(n&&k.size(n.dims)>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==r.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');$=2,b=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==S)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');$=5,b=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==S)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');$=0,b=n.dims[2]}}else{if(r.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(r.dims[2]!==t.numHeads||r.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');$=3}if(i&&k.size(i.dims)>0){if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=g+b,x=0;if(a&&k.size(a.dims)>0){x=8;let z=a.dims;throw z.length===1?z[0]===p?x=1:z[0]===3*p+2&&(x=3):z.length===2&&z[0]===p&&z[1]===v&&(x=5),x===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let T=!1,E=f;if(o&&k.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(b!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(b!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],T=!0}}let I=!1;if(a&&k.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(u&&k.size(u.dims)>0){if(u.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(u.dims[0]!==p||u.dims[1]!==t.numHeads||u.dims[2]!==m||u.dims[3]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:m,pastSequenceLength:g,kvSequenceLength:b,totalSequenceLength:v,maxSequenceLength:_,inputHiddenSize:0,hiddenSize:f,vHiddenSize:E,headSize:S,vHeadSize:Math.floor(E/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:x,scale:t.scale,broadcastResPosBias:I,passPastInKv:T,qkvFormat:$}},Ud=e=>J({...e}),Rd=J({perm:[0,2,1,3]}),rh=(e,t,r,n,o,i,a)=>{let u=[n,o,i],d=k.size(u),c=[{type:12,data:d},{type:12,data:a},{type:12,data:i}],p=m=>{let f=M("qkv_with_bias",t.dataType,u),b=P("qkv",t.dataType,u),g=P("bias",r.dataType,u),_=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` - ${m.registerUniforms(_).declareVariables(b,g,f)} - ${m.mainStart()} - ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; - - qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; - }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:u,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}),getShaderSource:p},{inputs:[t,r],outputs:[-1]})[0]},er=(e,t,r,n,o,i,a,u)=>{let d=i;if(a&&k.size(a.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=rh(e,i,a,t,n,r*o,u),d=d.reshape([t,n,r,o]),r===1||n===1?d:e.compute(Ee(d,Rd.perm),{inputs:[d],outputs:[-1]})[0]}else return i.dims.length===3&&(d=i.reshape([t,n,r,o])),r===1||n===1?d:e.compute(Ee(d,Rd.perm),{inputs:[d],outputs:[-1]})[0]},Nd=(e,t)=>{let r=th(e.inputs,t),n=e.inputs[0],o=Be(e.inputs,1),i=Be(e.inputs,2),a=Be(e.inputs,3),u=Be(e.inputs,4),d=Be(e.inputs,5),c=Be(e.inputs,6),p=Be(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if(o?.dims.length===5)throw new Error("Packed KV is not implemented");let m=o&&i&&o.dims.length===4&&i.dims.length===4,f=er(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,n,a,0);if(m)return Rt(e,f,o,i,u,void 0,c,p,d,r);if(!o||!i)throw new Error("key and value must be provided");let b=er(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.headSize,o,a,r.hiddenSize),g=er(e,r.batchSize,r.numHeads,r.kvSequenceLength,r.vHeadSize,i,a,2*r.hiddenSize);Rt(e,f,b,g,u,void 0,c,p,d,r)}});var nh,oh,ih,ah,xo,Vd,Wd,So=U(()=>{"use strict";ee();ne();Se();ie();nh=e=>{if(!e||e.length<1)throw new Error("too few inputs")},oh=(e,t)=>{let r=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>r.push(Number(o))),n=r.length),J({numOutputs:n,axis:t.axis,splitSizes:r})},ih=e=>` -fn calculateOutputIndex(index: u32) -> u32 { - for (var i: u32 = 0u; i < ${e}u; i += 1u ) { - if (index < ${F("uniforms.size_in_split_axis","i",e)}) { - return i; - } - } - return ${e}u; -}`,ah=e=>{let t=e.length,r=[];for(let n=0;n{let r=e[0].dims,n=k.size(r),o=e[0].dataType,i=k.normalizeAxis(t.axis,r.length),a=new Array(t.numOutputs),u=P("input",o,r.length),d=new Array(t.numOutputs),c=[],p=[],m=0,f=[{type:12,data:n}];for(let g=0;g` - ${g.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(u,...a)} - ${ih(d.length)} - ${ah(a)} - - ${g.mainStart()} - ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} - - var indices = ${u.offsetToIndices("global_idx")}; - var index = ${u.indicesGet("indices",i)}; - let output_number = calculateOutputIndex(index); - if (output_number != 0) { - index -= ${F("uniforms.size_in_split_axis","output_number - 1u",d.length)}; - ${u.indicesSet("indices",i,"index")}; - } - writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:b,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:f})}},Vd=(e,t)=>{nh(e.inputs);let r=e.inputs.length===1?t:oh(e.inputs,t);e.compute(xo(e.inputs,r),{inputs:[0]})},Wd=e=>{let t=e.axis,r=e.splitSizes,n=e.numOutputs<0?r.length:e.numOutputs;if(n!==r.length)throw new Error("numOutputs and splitSizes lengh must be equal");return J({axis:t,numOutputs:n,splitSizes:r})}});var sh,tn,Ld,To=U(()=>{"use strict";ee();ne();Se();ie();sh=(e,t)=>{let[r,n,o,i]=e,{numHeads:a,rotaryEmbeddingDim:u}=t;if(r.dims.length!==3&&r.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${r.dims.length}`);if(!k.areEqual(n.dims,[])&&!k.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(!k.areEqual(o.dims,i.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(u>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=r.dims[0],c=r.dims[r.dims.length-2],p=o.dims[0],m=k.sizeFromDimension(r.dims,1)/c,f=u===0?o.dims[1]*2:m/a;if(u>f)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(c!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(f/2!==o.dims[1]&&u/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},tn=(e,t)=>{let{interleaved:r,numHeads:n,rotaryEmbeddingDim:o,scale:i}=t,a=e[0].dims[0],u=k.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],c=u/d,p=e[2].dims[1],m=o===0?p*2:c/n,f=new Array(a,d,c/m,m-p),b=k.computeStrides(f),g=[{type:1,data:i},{type:12,data:f},{type:12,data:b},...e[0].dims.length===3?new Array({type:12,data:[u,c,m,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[u,m,d*m,1]}):[],...N(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],_=S=>{let $=P("input",e[0].dataType,e[0].dims.length),v=P("position_ids",e[1].dataType,e[1].dims.length),x=P("cos_cache",e[2].dataType,e[2].dims.length),T=P("sin_cache",e[3].dataType,e[3].dims.length),E=M("output",e[0].dataType,e[0].dims.length);return S.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:f.length},{name:"global_strides",type:"u32",length:b.length},{name:"input_output_strides",type:"u32",length:b.length}]),` - ${S.declareVariables($,v,x,T,E)} - - ${S.mainStart(It)} - let half_rotary_emb_dim = uniforms.${x.name}_shape[1]; - let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; - let size = uniforms.global_shape[0] * uniforms.global_strides[0]; - ${S.guardAgainstOutOfBoundsWorkgroupSizes("size")} - - if (bsnh[3] < half_rotary_emb_dim) { - let position_ids_idx = - ${v.broadcastedIndicesToOffset("bsnh.xy",M("",v.type.tensor,2))}; - let position_id = - u32(${v.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); - let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${r}); - let j = i + select(half_rotary_emb_dim, 1, ${r}); - let re = ${$.getByOffset("i")} * ${x.get("position_id","bsnh[3]")} - - ${$.getByOffset("j")} * ${T.get("position_id","bsnh[3]")}; - ${E.setByOffset("i","re")} - let im = ${$.getByOffset("i")} * ${T.get("position_id","bsnh[3]")} + - ${$.getByOffset("j")} * ${x.get("position_id","bsnh[3]")}; - ${E.setByOffset("j","im")} - } else { - let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; - ${E.setByOffset("k",$.getByOffset("k"))} - } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:J({interleaved:r}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(f)/It)},programUniforms:g})}},Ld=(e,t)=>{sh(e.inputs,t),e.compute(tn(e.inputs,t))}});var uh,dh,Gd,lh,Hd,Fd=U(()=>{"use strict";Se();ee();Fr();$o();So();st();To();ie();uh=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let r=e[0],n=e[1],o=e[2],i=e[3],a=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(r.dims.length!==3&&r.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let u=!1,d=r.dims[0],c=r.dims[1],p=r.dims.length===3?u?r.dims[2]/3:r.dims[2]:t.numHeads*r.dims[4],m=c,f=0,b=!n||n.dims.length===0,g=Math.floor(b?p/(t.numHeads+2*t.kvNumHeads):p/t.numHeads);b&&(p=g*t.numHeads);let _=i&&i.dims.length!==0,S=a&&a.dims.length!==0;if(_&&i.dims.length===4&&i.dims[0]===d&&i.dims[1]!==t.kvNumHeads&&i.dims[2]===t.kvNumHeads&&i.dims[3]===g)throw new Error("BSNH pastKey/pastValue is not supported");if(_&&S){if(i.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=i.dims[2]}else if(_||S)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=1;if(n&&n.dims.length>0){if(r.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(r.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(r.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');m=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==g)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');m=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==g)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');m=n.dims[2]}}else{if(r.dims.length!==3&&r.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(r.dims.length===5&&(r.dims[2]!==t.numHeads||r.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 x=0,T=!1,E=t.kvNumHeads?g*t.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(r.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(m!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(m!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],T=!0}}let I=e.length>4?e[5]:void 0;if(I&&I.dims.length!==1&&I.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:d,sequenceLength:c,pastSequenceLength:f,kvSequenceLength:m,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:g,vHeadSize:Math.floor(E/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:x,scale:t.scale,broadcastResPosBias:!1,passPastInKv:T,qkvFormat:v}},dh=J({perm:[0,2,1,3]}),Gd=(e,t,r)=>{let n=t,o=r.kvNumHeads;return t.dims.length===3&&r.kvSequenceLength!==0&&(n=t.reshape([r.batchSize,r.kvSequenceLength,o,r.headSize]),n=e.compute(Ee(n,dh.perm),{inputs:[n],outputs:[-1]})[0]),n},lh=(e,t,r,n)=>{let o=7,i=["type","type"],a=[e*t],u=e*t,d=[{type:12,data:u},{type:12,data:t},{type:12,data:e}],c=p=>{let m=P("seq_lens",r.dataType,r.dims),f=P("total_seq_lens",n.dataType,n.dims),b=M("pos_ids",o,a),g=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` - ${p.registerUniforms(g).declareVariables(m,f,b)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let total_sequence_length = u32(${f.getByOffset("0")}); - let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; - let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; - let batch_idx = global_idx / uniforms.sequence_length; - let sequence_idx = i32(global_idx % uniforms.sequence_length); - var pos_id: i32 = 0; - let seqlen = ${m.getByOffset("batch_idx")}; - let total_seqlen = seqlen + 1; - if (is_first_prompt) { - if (sequence_idx < total_seqlen) { - pos_id = sequence_idx; - } else { - pos_id = 1; - } - ${b.setByOffset("global_idx","pos_id")} - } else if (is_subsequent_prompt) { - let past_seqlen = total_seqlen - i32(uniforms.sequence_length); - if (past_seqlen + sequence_idx < total_seqlen) { - pos_id = past_seqlen + sequence_idx; - } else { - pos_id = 1; - } - ${b.setByOffset("global_idx","pos_id")} - } else if (global_idx < uniforms.batch_size) { - ${b.setByOffset("global_idx","seqlen")} - }; - } - `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:d}),getShaderSource:c}},Hd=(e,t)=>{let r=uh(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,i=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,u=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=r.kvNumHeads?r.kvNumHeads:r.numHeads,m=J({axis:2,numOutputs:3,splitSizes:[r.numHeads*r.headSize,p*r.headSize,p*r.headSize]}),[f,b,g]=!o&&!i?e.compute(xo([n],m),{inputs:[n],outputs:[-1,-1,-1]}):[n,o,i],_,S;if(t.doRotary){let T=e.compute(lh(r.batchSize,r.sequenceLength,d,c),{inputs:[d,c],outputs:[-1]})[0],E=e.inputs[7],I=e.inputs[8],z=J({interleaved:t.rotaryInterleaved!==0,numHeads:r.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),O=[f,T,E,I],D=[-1];_=e.compute(tn(O,z),{inputs:O,outputs:D})[0],O.splice(0,1,b);let L=J({interleaved:t.rotaryInterleaved!==0,numHeads:r.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});S=e.compute(tn(O,L),{inputs:O,outputs:D})[0]}let $=er(e,r.batchSize,r.numHeads,r.sequenceLength,r.headSize,t.doRotary?_:f,void 0,0),v=Gd(e,t.doRotary?S:b,r),x=Gd(e,g,r);Rt(e,$,v,x,void 0,void 0,a,u,void 0,r,d,c)}});var qd,ch,ph,jd,Kd=U(()=>{"use strict";ee();ne();st();ie();qd=(e,t,r,n,o,i,a,u)=>{let d=ce(i),c=d===1?"f32":`vec${d}f`,p=d===1?"vec2f":`mat2x${d}f`,m=o*a,f=64;m===1&&(f=256);let b=[o,a,i/d],g=[o,a,2],_=["rank","type","type"],S=[];S.push(...N(b,g));let $=v=>{let x=P("x",t.dataType,3,d),T=P("scale",r.dataType,r.dims),E=P("bias",n.dataType,n.dims),I=M("output",1,3,2),z=[x,T,E,I];return` - var workgroup_shared : array<${p}, ${f}>; - const workgroup_size = ${f}u; - ${v.declareVariables(...z)} - ${v.mainStart(f)} - let batch = workgroup_index / uniforms.x_shape[1]; - let channel = workgroup_index % uniforms.x_shape[1]; - let hight = uniforms.x_shape[2]; - // initialize workgroup memory - var sum = ${c}(0); - var squared_sum = ${c}(0); - for (var h = local_idx; h < hight; h += workgroup_size) { - let value = ${c}(${x.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 = ${He("workgroup_shared[0][0]",d)} / f32(hight * ${d}); - let squared_sum_final = ${He("workgroup_shared[0][1]",d)} / f32(hight * ${d}); - - let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${u})); - let channel_scale = inv_std_dev * f32(scale[channel]); - let channel_shift = f32(bias[channel]) - sum_final * channel_scale; - output[workgroup_index] = vec2f(channel_scale, channel_shift); - } - }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${d};${u};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:g,dataType:1}],dispatchGroup:{x:m},programUniforms:S}),getShaderSource:$},{inputs:[t,r,n],outputs:[-1]})[0]},ch=(e,t,r)=>{let n=t[0].dims,o=n,i=2,a=n[0],u=n[1],d=k.sizeFromDimension(n,i),c=ce(d),p=k.size(o)/c,m=qd(e,t[0],t[1],t[2],a,d,u,r.epsilon),f=[a,u,d/c],b=[a,u],g=["type","none"],_=S=>{let $=P("x",t[0].dataType,f.length,c),v=P("scale_shift",1,b.length,2),x=M("output",t[0].dataType,f.length,c),T=[$,v,x];return` - ${S.registerUniform("output_size","u32").declareVariables(...T)} - ${S.mainStart()} - ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let outputIndices = ${x.offsetToIndices("global_idx")}; - let batch = outputIndices[0]; - let channel = outputIndices[1]; - let scale_shift = ${v.getByIndices("vec2(batch, channel)")}; - let value = ${$.getByOffset("global_idx")} * ${x.type.value}(scale_shift.x) + ${x.type.value}(scale_shift.y); - ${x.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...N(f,b,f)]}),getShaderSource:_},{inputs:[t[0],m]})},ph=(e,t,r)=>{let n=t[0].dims,o=n,i=n[0],a=n[n.length-1],u=k.sizeFromDimension(n,1)/a,d=ce(a),c=k.size(o)/d,p=[{type:12,data:u},{type:12,data:Math.floor(a/d)}],m=["type","type"],f=!1,b=[0,n.length-1];for(let $=0;$n[b[v]])),_=qd(e,g,t[1],t[2],i,u,a,r.epsilon),S=$=>{let v=be(t[0].dataType),x=d===1?"vec2f":`mat${d}x2f`,T=z=>{let O=z===0?"x":"y",D=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${v}(${D}(scale.${O}))`;case 2:return`vec2<${v}>(${D}(scale[0].${O}, scale[1].${O}))`;case 4:return`vec4<${v}>(${D}(scale[0].${O}, scale[1].${O}, scale[2].${O}, scale[3].${O}))`;default:throw new Error(`Not supported compoents ${d}`)}},E=P("input",t[0].dataType,t[0].dims,d),I=M("output",t[0].dataType,o,d);return` - @group(0) @binding(0) var input : array<${E.type.storage}>; - @group(0) @binding(1) var scale_input : array<${x}>; - @group(0) @binding(2) var output : array<${I.type.storage}>; - struct Uniforms {H: u32, C : u32}; - @group(0) @binding(3) var uniforms: Uniforms; - - ${$.mainStart()} - let current_image_number = global_idx / (uniforms.C * uniforms.H); - let current_channel_number = global_idx % uniforms.C; - - let scale_offset = current_image_number * uniforms.C + current_channel_number; - let scale = scale_input[scale_offset]; - output[global_idx] = fma(input[global_idx], ${T(0)}, ${T(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:o,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:S},{inputs:[t[0],_]})},jd=(e,t)=>{t.format==="NHWC"?ph(e,e.inputs,t):ch(e,e.inputs,t)}});var mh,fh,Zd,Qd=U(()=>{"use strict";ee();ne();ie();mh=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},fh=(e,t,r)=>{let n=t.simplified,o=e[0].dims,i=e[1],a=!n&&e[2],u=o,d=k.normalizeAxis(t.axis,o.length),c=k.sizeToDimension(o,d),p=k.sizeFromDimension(o,d),m=k.size(i.dims),f=a?k.size(a.dims):0;if(m!==p||a&&f!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. - Size of scale and bias (if provided) must match this. - Got scale size of ${m} and bias size of ${f}`);let b=[];for(let E=0;E1,v=r>2,x=E=>{let I=be(e[0].dataType),z=[P("x",e[0].dataType,e[0].dims,g),P("scale",i.dataType,i.dims,g)];a&&z.push(P("bias",a.dataType,a.dims,g)),z.push(M("output",e[0].dataType,u,g)),$&&z.push(M("mean_data_output",1,b)),v&&z.push(M("inv_std_output",1,b));let O=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` - ${E.registerUniforms(O).declareVariables(...z)} - ${E.mainStart()} - ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} - let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${ao("f32",g)}; - var mean_square_vector = ${ao("f32",g)}; - - for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { - let value = ${Ct(I,g,"x[h + offset]")}; - mean_vector += value; - mean_square_vector += value * value; - } - let mean = ${He("mean_vector",g)} / uniforms.norm_size; - let inv_std_dev = inverseSqrt(${He("mean_square_vector",g)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); - - for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { - let f32input = ${Ct(I,g,"x[j + offset]")}; - let f32scale = ${Ct(I,g,"scale[j]")}; - output[j + offset] = ${z[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale - ${a?`+ ${Ct(I,g,"bias[j]")}`:""} - ); - } - - ${$?"mean_data_output[global_idx] = mean":""}; - ${v?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},T=[{dims:u,dataType:e[0].dataType}];return $&&T.push({dims:b,dataType:1}),v&&T.push({dims:b,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${g};${r};${n}`,inputDependencies:_},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:S}),getShaderSource:x}},Zd=(e,t)=>{mh(e.inputs),e.compute(fh(e.inputs,t,e.outputCount))}});var hh,Yd,Xd=U(()=>{"use strict";ne();Yr();Xr();hh=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.")},Yd=e=>{hh(e.inputs);let t=Je.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let r=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(r<8&&n<8)e.compute(Qr(e.inputs,{activation:""},t));else{let o=t[t.length-2],i=k.size(e.inputs[0].dims.slice(0,-2)),a=k.size(e.inputs[1].dims.slice(0,-2));if(i!==1&&o===1&&a===1){let u=e.inputs[0].reshape([1,i,n]),d=e.inputs[1].reshape([1,n,r]),c=[1,i,r],p=[u,d];e.compute(Jt(p,{activation:""},t,c),{inputs:p})}else e.compute(Jt(e.inputs,{activation:""},t))}}});var gh,bh,yh,Jd,el,tl=U(()=>{"use strict";ee();ne();Se();ie();gh=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let r=e[0],n=r.dims.length;if(r.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((t.k+t.blockSize-1)/t.blockSize),i=t.blockSize/8*t.bits,a=e[1];if(!k.areEqual(a.dims,[t.n,o,i]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let d=e[2].dims;if(k.size(d)!==t.n*o)throw new Error("scales input size error.");if(e.length===4){let p=e[3].dims,m=t.bits>4?t.n*o:t.n*Math.floor((o+1)/2);if(k.size(p)!==m)throw new Error("zeroPoints input size error.")}},bh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,u=r.slice(0,n-2),d=k.size(u),p=e[1].dims[2]/4,m=e[0].dataType,f=ce(t.k),b=ce(p),g=ce(a),_=u.concat([o,a]),S=o>1&&a/g%2===0?2:1,$=k.size(_)/g/S,v=64,x=[],T=[d,o,i/f],E=k.convertShape(e[1].dims).slice();E.splice(-1,1,p/b),x.push(...N(T)),x.push(...N(E)),x.push(...N(e[2].dims)),e.length===4&&x.push(...N(k.convertShape(e[3].dims)));let I=[d,o,a/g];x.push(...N(I));let z=O=>{let D=T.length,L=P("a",e[0].dataType,D,f),q=P("b",12,E.length,b),Q=P("scales",e[2].dataType,e[2].dims.length),W=[L,q,Q],Z=e.length===4?P("zero_points",12,e[3].dims.length):void 0;Z&&W.push(Z);let we=I.length,H=M("output",e[0].dataType,we,g),j=be(e[0].dataType),te=(()=>{switch(f){case 1:return`array<${j}, 8>`;case 2:return`mat4x2<${j}>`;case 4:return`mat2x4<${j}>`;default:throw new Error(`${f}-component is not supported.`)}})(),X=()=>{let ye=` - // reuse a data - var input_offset = ${L.indicesToOffset(`${L.type.indices}(batch, row, word_offset)`)}; - var a_data: ${te}; - for (var j: u32 = 0; j < ${8/f}; j++) { - a_data[j] = ${L.getByOffset("input_offset")}; - input_offset++; - } - `;for(let re=0;re> 4) & b_mask); - b_quantized_values = ${te}(${Array.from({length:4},(C,V)=>`${j}(b_value_lower[${V}]), ${j}(b_value_upper[${V}])`).join(", ")}); - b_dequantized_values = ${f===1?`${te}(${Array.from({length:8},(C,V)=>`(b_quantized_values[${V}] - ${Z?`zero_point${re}`:"zero_point"}) * scale${re}`).join(", ")});`:`(b_quantized_values - ${te}(${Array(8).fill(`${Z?`zero_point${re}`:"zero_point"}`).join(",")})) * scale${re};`}; - workgroup_shared[local_id.x * ${S} + ${Math.floor(re/g)}]${g>1?`[${re%g}]`:""} += ${Array.from({length:8/f},(C,V)=>`${f===1?`a_data[${V}] * b_dequantized_values[${V}]`:`dot(a_data[${V}], b_dequantized_values[${V}])`}`).join(" + ")}; - `;return ye},ue=()=>{let ye=` - var col_index = col * ${g}; - ${Z?` - let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; - var zero_point_byte_count: u32; - var zero_point_word_index: u32; - var zero_point_byte_offset: u32; - let zero_point_nibble_offset: u32 = block & 0x1u; - var zero_point_bits_offset: u32; - var zero_point_word: u32;`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${j}(8);`} - `;for(let re=0;re> 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 = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point${re} = ${j}((zero_point_word) & 0xFu);`:""} - col_index += 1;`;return ye},he=()=>{let ye=`col_index = col * ${g};`;for(let re=0;re; - var b_value_upper: vec4; - var b_quantized_values: ${te}; - var b_dequantized_values: ${te};`,ye};return` - var workgroup_shared: array<${H.type.value}, ${S*v}>; - ${O.declareVariables(...W,H)} - ${O.mainStart([v,1,1])} - let output_indices = ${H.offsetToIndices(`(global_idx / ${v}) * ${S}`)}; - 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 * ${t.blockSize/f}; - ${ue()} - for (var word: u32 = 0; word < ${p}; word += ${b}) { - ${he()} - for (var i: u32 = 0; i < ${b}; i++) { - ${X()} - word_offset += ${8/f}; - } - } - } - workgroupBarrier(); - - if (local_id.x < ${S}) { - 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 += ${S}; - } - ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; - } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${f};${b};${g};${S};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:m}],dispatchGroup:{x:$},programUniforms:x}),getShaderSource:z}},yh=(e,t)=>{let r=e[0].dims,n=r.length,o=r[n-2],i=t.k,a=t.n,u=r.slice(0,n-2),d=k.size(u),p=e[1].dims[2]/4,m=e[0].dataType,f=ce(t.k),b=ce(p),g=u.concat([o,a]),_=128,S=a%8===0?8:a%4===0?4:1,$=_/S,v=$*b*8,x=v/f,T=v/t.blockSize,E=k.size(g)/S,I=[],z=[d,o,i/f],O=k.convertShape(e[1].dims).slice();O.splice(-1,1,p/b),I.push(...N(z)),I.push(...N(O)),I.push(...N(e[2].dims)),e.length===4&&I.push(...N(k.convertShape(e[3].dims)));let D=[d,o,a];I.push(...N(D));let L=q=>{let Q=z.length,W=P("a",e[0].dataType,Q,f),Z=P("b",12,O.length,b),we=P("scales",e[2].dataType,e[2].dims.length),H=[W,Z,we],j=e.length===4?P("zero_points",12,e[3].dims.length):void 0;j&&H.push(j);let te=D.length,X=M("output",e[0].dataType,te),ue=be(e[0].dataType),he=()=>{switch(f){case 1:return` - let a_data0 = vec4<${ue}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); - let a_data1 = vec4<${ue}>(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<${ue}>(sub_a[word_offset], sub_a[word_offset + 1]); - let a_data1 = vec4<${ue}>(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(`${f}-component is not supported.`)}};return` - var sub_a: array<${W.type.value}, ${x}>; - var inter_results: array, ${S}>; - ${q.declareVariables(...H,X)} - ${q.mainStart([$,S,1])} - let output_indices = ${X.offsetToIndices(`workgroup_index * ${S}`)}; - 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) / ${T} + 1; - - // Loop over shared dimension. - for (var tile: u32 = 0; tile < num_tiles; tile += 1) { - let a_col_start = tile * ${x}; - // load one tile A data into shared memory. - for (var a_offset = local_idx; a_offset < ${x}; a_offset += ${_}) - { - let a_col = a_col_start + a_offset; - if (a_col < uniforms.a_shape[2]) - { - sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)}; - } else { - sub_a[a_offset] = ${W.type.value}(0); - } - } - workgroupBarrier(); - - // each thread process one block - let b_row = col + local_id.y; - let block = tile * ${T} + local_id.x; - ${j?` - let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; - let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); - let zero_point_word_index = zero_point_byte_count >> 0x2u; - let zero_point_byte_offset = zero_point_byte_count & 0x3u; - let zero_point_nibble_offset: u32 = block & 0x1u; - let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); - let zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; - let zero_point = ${ue}((zero_point_word) & 0xFu);`:` - // The default zero point is 8 for unsigned 4-bit quantization. - let zero_point = ${ue}(8);`} - let scale = ${we.getByOffset("b_row * n_blocks_per_col + block")}; - let b_data = ${Z.getByIndices(`${Z.type.indices}(b_row, block, 0)`)}; - var word_offset = local_id.x * ${t.blockSize/f}; - for (var i: u32 = 0; i < ${b}; i++) { - ${he()} - let b_value = ${b===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<${ue}>(${Array.from({length:4},(ye,re)=>`${ue}(b_value_lower[${re}]), ${ue}(b_value_upper[${re}])`).join(", ")}); - let b_dequantized_values = (b_quantized_values - mat2x4<${ue}>(${Array(8).fill("zero_point").join(",")})) * scale; - inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(ye,re)=>`${`dot(a_data${re}, b_dequantized_values[${re}])`}`).join(" + ")}; - word_offset += ${8/f}; - } - workgroupBarrier(); - } - - if (local_idx < ${S}) { - var output_value: ${X.type.value} = ${X.type.value}(0); - for (var b = 0u; b < ${$}; b++) { - output_value += inter_results[local_idx][b]; - } - if (col + local_idx < uniforms.output_shape[2]) - { - ${X.setByIndices(`${X.type.indices}(batch, row, col + local_idx)`,"output_value")} - } - } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${f};${b};${$};${S}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:g,dataType:m}],dispatchGroup:{x:E},programUniforms:I}),getShaderSource:L}},Jd=(e,t)=>{gh(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(yh(e.inputs,t)):e.compute(bh(e.inputs,t))},el=e=>J(e)});var _h,wh,vh,$h,xh,Sh,Th,Ih,rl,nl=U(()=>{"use strict";ee();ne();ie();_h=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},wh=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${F("uniforms.pads",o,r)}; - if (k < 0) { - break; - } - if (k >= i32(${F("uniforms.x_shape",o,t)})) { - break; - } - offset += k * i32(${F("uniforms.x_strides",o,t)}); - `;return` - value = ${e.type.value}(uniforms.constant_value); - for (var i = 0; i < 1; i++) { - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - } - `},vh=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${F("uniforms.pads",o,r)}; - if (k < 0) { - k = -k; - } - { - let _2n_1 = 2 * (i32(${F("uniforms.x_shape",o,t)}) - 1); - k = k % _2n_1; - if(k >= i32(${F("uniforms.x_shape",o,t)})) { - k = _2n_1 - k; - } - } - offset += k * i32(${F("uniforms.x_strides",o,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},$h=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${F("uniforms.pads",o,r)}; - if (k < 0) { - k = 0; - } - if (k >= i32(${F("uniforms.x_shape",o,t)})) { - k = i32(${F("uniforms.x_shape",o,t)}) - 1; - } - offset += k * i32(${F("uniforms.x_strides",o,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},xh=(e,t,r)=>{let n="";for(let o=t-1;o>=0;--o)n+=` - k = i32(${e.indicesGet("indices",o)}) - ${F("uniforms.pads",o,r)}; - if (k < 0) { - k += i32(${F("uniforms.x_shape",o,t)}]); - } - if (k >= i32(${F("uniforms.x_shape",o,t)})) { - k -= i32(${F("uniforms.x_shape",o,t)}); - } - offset += k * i32(${F("uniforms.x_strides",o,t)}); - `;return` - var offset = 0; - var k = 0; - ${n} - value = x[offset]; - `},Sh=(e,t,r)=>{switch(r.mode){case 0:return wh(e,t,r.pads.length);case 1:return vh(e,t,r.pads.length);case 2:return $h(e,t,r.pads.length);case 3:return xh(e,t,r.pads.length);default:throw new Error("Invalid mode")}},Th=(e,t)=>{let r=k.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,o=k.size(r),i=[{type:12,data:o},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&i.push({type:a?e[2].dataType:1,data:t.value}),i.push(...N(e[0].dims,r));let u=["rank"],d=c=>{let p=M("output",e[0].dataType,r.length),m=P("x",e[0].dataType,n.length),f=m.type.value,b=Sh(p,n.length,t),g=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&g.push({name:"constant_value",type:a?f:"f32"}),` - ${c.registerUniforms(g).declareVariables(m,p)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - - let indices = ${p.offsetToIndices("global_idx")}; - - var value = ${f}(0); - ${b} - output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(k.size(r)/64)},programUniforms:i}),getShaderSource:d}},Ih=(e,t)=>{if(e.length>1){let r=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,i=new Int32Array(2*o).fill(0);if(e.length>=4){let u=e[3].getBigInt64Array();for(let d=0;di[Number(d)]=Number(u));let a=[];return i.forEach(u=>a.push(u)),{mode:t.mode,value:n,pads:a}}else return t},rl=(e,t)=>{_h(e.inputs);let r=Ih(e.inputs,t);e.compute(Th(e.inputs,r),{inputs:[0]})}});var rn,ol,il,al,sl,Ch,Ah,ul,dl,ll,cl,pl,ml,fl,hl,gl,bl,yl,_l,wl=U(()=>{"use strict";We();ee();ne();ie();rn=e=>{if(ge.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ol=(e,t,r)=>{let n=t.format==="NHWC",o=e.dims.slice();n&&o.splice(1,0,o.pop());let i=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),u=t.strides.slice(),d=i?t.dilations.slice():[],c=t.pads.slice();Tt.adjustPoolAttributes(r,o,a,u,d,c);let p=Tt.computePoolOutputShape(r,o,u,d,a,c,t.autoPad),m=Object.assign({},t);i?Object.assign(m,{kernelShape:a,strides:u,pads:c,dilations:d,cacheKey:t.cacheKey}):Object.assign(m,{kernelShape:a,strides:u,pads:c,cacheKey:t.cacheKey});let f=p.slice();return f.push(f.splice(1,1)[0]),[m,n?f:p]},il=(e,t)=>{let r=t.format==="NHWC",n=k.size(e),o=k.size(t.kernelShape),i=[{type:12,data:n},{type:12,data:o}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let u=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],c=t.pads[t.pads.length/2-1],p=t.pads[t.pads.length-1],m=!!(c+p);i.push({type:12,data:u},{type:12,data:d},{type:12,data:c},{type:12,data:p}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let f=!1;if(t.kernelShape.length===2){let b=t.kernelShape[t.kernelShape.length-2],g=t.strides[t.strides.length-2],_=t.pads[t.pads.length/2-2],S=t.pads[t.pads.length-2];f=!!(_+S),i.push({type:12,data:b},{type:12,data:g},{type:12,data:_},{type:12,data:S}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[i,a,!0,m,f]}else{if(r)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let u=k.computeStrides(t.kernelShape);i.push({type:12,data:u},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:u.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((c,p)=>c+p);return[i,a,!!d,!1,!1]}},al=(e,t,r,n,o,i,a,u,d,c,p,m)=>{let f=o.format==="NHWC",b=t.type.value,g=M("output",t.type.tensor,n);if(o.kernelShape.length<=2){let _="",S="",$="",v=r-(f?2:1);if(p?_=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; - if (xIndices[${v}] < 0 || xIndices[${v}] - >= uniforms.x_shape[${v}]) { - pad++; - continue; - } - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${i} - }`:_=` - for (var i: u32 = 0u; i < uniforms.kw; i++) { - xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${i} - }`,o.kernelShape.length===2){let T=r-(f?3:2);m?S=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j; - if (xIndices[${T}] < 0 || xIndices[${T}] >= uniforms.x_shape[${T}]) { - pad += i32(uniforms.kw); - continue; - } - `:S=` - for (var j: u32 = 0u; j < uniforms.kh; j++) { - xIndices[${T}] = indices[${T}] * uniforms.sh - uniforms.phStart + j; - `,$=` - } - `}return` - ${e.registerUniforms(d).declareVariables(t,g)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - - let indices = ${g.offsetToIndices("global_idx")}; - var xIndices = ${g.offsetToIndices("global_idx")}; - - var value = ${b}(${u}); - var pad = 0; - ${S} - ${_} - ${$} - ${a} - - output[global_idx] = value; - }`}else{if(f)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let _=o.kernelShape.length,S=o.pads.length,$="";return c?$=` - if (xIndices[j] >= uniforms.x_shape[j]) { - pad++; - isPad = true; - break; - } - } - if (!isPad) { - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${i} - }`:$=` - } - let x_val = x[${t.indicesToOffset("xIndices")}]; - ${i} - `,` - ${e.registerUniforms(d).declareVariables(t,g)} - - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let indices = ${g.offsetToIndices("global_idx")}; - var xIndices = ${g.offsetToIndices("global_idx")}; - - var offsets: array; - - var value = ${b}(${u}); - var pad = 0; - var isPad = false; - - for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { - var offset = i; - for (var j = 0u; j < ${_-1}u; j++) { - offsets[j] = offset / ${F("uniforms.kernelStrides","j",_)}; - offset -= offsets[j] * ${F("uniforms.kernelStrides","j",_)}; - } - offsets[${_-1}] = offset; - - isPad = false; - for (var j = ${r-_}u; j < ${r}u; j++) { - xIndices[j] = indices[j] * ${F("uniforms.strides",`j - ${r-_}u`,_)} - + offsets[j - ${r-_}u] - ${F("uniforms.pads","j - 2u",S)}; - ${$} - } - ${a} - - output[global_idx] = value; - }`}},sl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Ch=e=>`${sl(e)};${e.countIncludePad}`,Ah=e=>`${sl(e)};${e.storageOrder};${e.dilations}`,ul=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),dl=(e,t,r,n)=>{let[o,i]=ol(t,n,r),a=P("x",t.dataType,t.dims.length),u=a.type.value,d="value += x_val;",c="";o.countIncludePad?c+=`value /= ${u}(uniforms.kernelSize);`:c+=`value /= ${u}(i32(uniforms.kernelSize) - pad);`;let[p,m,f,b,g]=il(i,o);p.push(...N(t.dims,i));let _=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${f};${b};${g}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:p}),getShaderSource:S=>al(S,a,t.dims.length,i.length,o,d,c,0,m,f,b,g)}},ll=e=>{let t=e.count_include_pad!==0,r=ul(e);if(r.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...r,cacheKey:""};return{...n,cacheKey:Ch(n)}},cl=(e,t)=>{rn(e.inputs),e.compute(dl("AveragePool",e.inputs[0],!1,t))},pl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},ml=e=>{let t=e.format;return{format:t,...pl,cacheKey:t}},fl=(e,t)=>{rn(e.inputs),e.compute(dl("GlobalAveragePool",e.inputs[0],!0,t))},hl=(e,t,r,n)=>{let[o,i]=ol(t,n,r),a=` - value = max(x_val, value); - `,u="",d=P("x",t.dataType,t.dims.length),c=["rank"],[p,m,f,b,g]=il(i,o);return p.push(...N(t.dims,i)),{name:e,shaderCache:{hint:`${n.cacheKey};${f};${b};${g}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:i,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(k.size(i)/64)},programUniforms:p}),getShaderSource:_=>al(_,d,t.dims.length,i.length,o,a,u,t.dataType===10?-65504:-1e5,m,f,b,g)}},gl=(e,t)=>{rn(e.inputs),e.compute(hl("MaxPool",e.inputs[0],!1,t))},bl=e=>{let t=e.storage_order,r=e.dilations,n=ul(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:t,dilations:r,...n,cacheKey:""};return{...o,cacheKey:Ah(o)}},yl=e=>{let t=e.format;return{format:t,...pl,cacheKey:t}},_l=(e,t)=>{rn(e.inputs),e.compute(hl("GlobalMaxPool",e.inputs[0],!0,t))}});var kh,Ph,vl,$l,xl=U(()=>{"use strict";ee();ne();Se();ie();kh=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((r,n)=>r===e[2].dims[n]).reduce((r,n)=>r&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,i)=>i===t.axis||o===e[0].dims[i]).reduce((o,i)=>o&&i,!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 r=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(r/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Ph=(e,t)=>{let r=k.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,o=n===3,i=e[0].dims,a=e[1].dataType,u=k.size(i),d=n===3||n===2,c=d?[Math.ceil(k.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,m=e.length>2?e[2]:void 0,f=m?d?[Math.ceil(k.size(m.dims)/4)]:m.dims:void 0,b=p.length===0||p.length===1&&p[0]===1,g=b===!1&&p.length===1,_=ce(u),S=b&&(!d||_===4),$=S?_:1,v=S&&!d?_:1,x=P("input",d?12:n,c.length,v),T=P("scale",a,p.length),E=m?P("zero_point",d?12:n,f.length):void 0,I=M("output",a,i.length,$),z=[x,T];E&&z.push(E);let O=[c,p];m&&O.push(f);let D=[{type:12,data:u/$},{type:12,data:r},{type:12,data:t.blockSize},...N(...O,i)],L=q=>{let Q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${q.registerUniforms(Q).declareVariables(...z,I)} - ${q.mainStart()} - ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${I.offsetToIndices("global_idx")}; - - // Set input x - ${d?` - let input = ${x.getByOffset("global_idx / 4")}; - let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; - let x_value = ${$===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${x.getByOffset("global_idx")};`}; - - // Set scale input - ${b?`let scale_value= ${T.getByOffset("0")}`:g?` - let scale_index = ${I.indicesGet("output_indices","uniforms.axis")}; - let scale_value= ${T.getByOffset("scale_index")};`:` - var scale_indices: ${T.type.indices} = output_indices; - let index = ${T.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; - ${T.indicesSet("scale_indices","uniforms.axis","index")}; - let scale_value= ${T.getByIndices("scale_indices")};`}; - - // Set zero-point input - ${E?b?d?` - let zero_point_input = ${E.getByOffset("0")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${E.getByOffset("0")}`:g?d?` - let zero_point_index = ${I.indicesGet("output_indices","uniforms.axis")}; - let zero_point_input = ${E.getByOffset("zero_point_index / 4")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_index % 4]`:` - let zero_point_index = ${I.indicesGet("output_indices","uniforms.axis")}; - let zero_point_value = ${E.getByOffset("zero_point_index")};`:d?` - let zero_point_offset = ${T.indicesToOffset("scale_indices")}; - let zero_point_input = ${E.getByOffset("zero_point_offset / 4")}; - let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; - let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${E.getByIndices("scale_indices")};`:`let zero_point_value = ${d?o?"i32":"u32":x.type.value}(0);`}; - // Compute and write output - ${I.setByOffset("global_idx",`${I.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:E?["rank","rank","rank"]:["rank","rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:i,dataType:a}],dispatchGroup:{x:Math.ceil(u/$/64),y:1,z:1},programUniforms:D})}},vl=(e,t)=>{kh(e.inputs,t),e.compute(Ph(e.inputs,t))},$l=e=>J({axis:e.axis,blockSize:e.blockSize})});var zh,Oh,Sl,Tl=U(()=>{"use strict";We();ee();ie();zh=(e,t,r)=>{let n=e===t,o=et&&r>0;if(n||o||i)throw new Error("Range these inputs' contents are invalid.")},Oh=(e,t,r,n)=>{let o=Math.abs(Math.ceil((t-e)/r)),i=[o],a=o,u=[{type:12,data:a},{type:n,data:e},{type:n,data:r},...N(i)],d=c=>{let p=M("output",n,i.length),m=p.type.value,f=[{name:"outputSize",type:"u32"},{name:"start",type:m},{name:"delta",type:m}];return` - ${c.registerUniforms(f).declareVariables(p)} - ${c.mainStart()} - ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - output[global_idx] = uniforms.start + ${m}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u})}},Sl=e=>{let t=0,r=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],r=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],r=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),ge.webgpu.validateInputContent&&zh(t,r,n),e.compute(Oh(t,r,n,e.inputs[0].dataType),{inputs:[]})}});var Bh,Il,Cl,Dh,Al,El,kl=U(()=>{"use strict";ee();ne();Se();ie();Bh=(e,t,r,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let o=`{ - var oldValue = 0; - loop { - let newValueF32 =`,i=`; - let newValue = bitcast(newValueF32); - let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); - if res.exchanged { - break; - } - oldValue = res.old_value; - } - }`;switch(e){case"none":return`${t}=${r};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${r}));`:` - ${o}bitcast<${n}>(oldValue) + (${r})${i}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${r}));`:` - ${o}max(bitcast(oldValue), (${r}))${i}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${r}));`:`${o}min(bitcast<${n}>(oldValue), (${r}))${i}`;case"mul":return`${o}(bitcast<${n}>(oldValue) * (${r}))${i}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Il=(e,t)=>`${e===1?` - let element_count_dim = uniforms.output_strides; - let dim_value = uniforms.output_shape;`:` - let element_count_dim = uniforms.output_strides[${t?"i - indices_start":"i"}]; - let dim_value = uniforms.output_shape[${t?"i - indices_start":"i"} + uniforms.last_index_dimension];`} - - if (index >= 0) { - if (index >= i32(dim_value)) { - index = i32(dim_value - 1); - } - } else { - if (index < -i32(dim_value)) { - index = 0; - } else { - index += i32(dim_value); - } - } - data_offset += u32((u32(index) * element_count_dim));`,Cl=(e,t,r)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { - let value = updates[uniforms.num_updates_elements * ${r?"global_idx":"idx"} + i]; - ${Bh(e.reduction,"output[data_offset + i]","value",t)} - }`,Dh=(e,t)=>{let r=e[0].dims,n=e[1].dims,o=r,i=1,a=Math.ceil(k.size(n)/i),u=n[n.length-1],d=k.sizeFromDimension(r,u),c=k.sizeFromDimension(n,0)/u,p=[{type:12,data:a},{type:12,data:u},{type:12,data:d},...N(e[1].dims,e[2].dims,o)],m=f=>{let b=P("indices",e[1].dataType,e[1].dims.length),g=P("updates",e[2].dataType,e[2].dims.length,i),_=t.reduction!=="none"&&t.reduction!==""?es("output",e[0].dataType,o.length):M("output",e[0].dataType,o.length,i);return` - ${f.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(b,g,_)} - ${f.mainStart()} - ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - var hasDuplicates = false; - if (${t.reduction==="none"}) { - for (var i = 0; i < ${c}; i = i + 1) { - for (var j = i + 1; j < ${c}; j = j + 1) { - var index_i = i32(indices[i].x); - var index_j = i32(indices[j].x); - if (index_i == index_j) { - hasDuplicates = true; - break; - } - } - if (hasDuplicates) { - break; - } - } - } - - if (${t.reduction==="none"} && hasDuplicates) { - if (global_idx != 0u) { - return; - } - // Process each index-update pair individually when duplicates exist - for (var idx = 0u; idx < ${c}u; idx++) { - var data_offset = 0u; - for (var i = 0u; i < uniforms.last_index_dimension; i++) { - var index = i32(indices[idx * uniforms.last_index_dimension + i].x); - ${Il(r.length,!1)} - } - ${Cl(t,_.type.value,!1)} - } - return; - } - - var data_offset = 0u; - var indices_start = uniforms.last_index_dimension * global_idx; - var indices_end = indices_start + uniforms.last_index_dimension; - for (var i = indices_start; i < indices_end; i++) { - var index = i32(indices[i].x); - ${Il(r.length,!0)} - } - ${Cl(t,_.type.value,!0)} - }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:p}),getShaderSource:m}},Al=e=>J({reduction:e.reduction}),El=(e,t)=>{e.compute(Dh(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}});var Mh,Rh,Uh,Pl,Nh,Vh,Wh,Lh,Gh,Hh,Fh,qh,zl,jh,Kh,Zh,Qh,Yh,Ol,Bl,Dl=U(()=>{"use strict";ee();ne();Se();ie();Mh=(e,t)=>{if(e.every(r=>r>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and - one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Rh=(e,t,r)=>{t.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(r).fill(1);return t.forEach((o,i)=>n[o]=e[i]),n},Uh=(e,t,r,n,o,i)=>{let[a,u,d]=r>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(p=>i.push(p));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(u>0&&e.length>u&&e[u].dims.length===1&&e[u].dims[0]>0){if(e[u].getFloat32Array().forEach(p=>n.push(p)),n.length!==0&&n.length!==c&&r>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Mh(n,t),t.axes.length>0&&Rh(n,t.axes,c).forEach((p,m)=>n[m]=p)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==c&&r>=18&&o.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof o<"u"&&n.length>0&&o.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Pl=(e,t,r,n)=>` - // The whole part and the fractional part are calculated separately due to inaccuracy of floating - // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an - // offset-by-one error later in floor(). - let big = (${e}) * (${t}); - let whole = ${n}(big / (${r})); - let fract = ${n}(big % (${r})) / ${n}(${r}); - return whole + fract; -`,Nh=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, - lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return` - if (xScale < 1.0 || floor(xScale) != xScale) { - return ${t}(xResized) / ${t}(xScale); - } else { - ${Pl("xResized","lengthOriginal","lengthResized",t)} - } - `;case"pytorch_half_pixel":return`if (lengthResized > 1) { - return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; - } else { - return 0.0; - }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { - return 0.0; - } else { - ${Pl("xResized","lengthOriginal - 1","lengthResized - 1",t)} - }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { - return ${t}(roiStart) * ${t}(lengthOriginal - 1) + - (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / - ${t}(lengthResized - 1); - } else { - return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); - }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); - const adjustment = ${t}(lengthResized) / outputWidth; - const center = ${t}(lengthOriginal) / 2; - const offset = center * (1 - adjustment); - return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Vh=(e,t,r)=>`fn getNearestPixelFromOriginal(xOriginal: ${r}, isDownSample: bool) -> ${r} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Wh=(e,t,r)=>{let n=new Array(r).fill(0).concat(new Array(r).fill(1)),o=e.length===0?n:e.slice();return t.length>0?(t.forEach((i,a)=>{n[i]=o[a],n[a+r]=o[t.length+a]}),n):o},Lh=(e,t,r,n)=>{let o=[];if(r.length>0)if(n.length>0){if(e.forEach(i=>o.push(i)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((i,a)=>o[i]=r[a])}else r.forEach(i=>o.push(i));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((i,a)=>Math.round(i*t[a]))}return o},Gh=(e,t,r)=>{let n=(()=>{switch(r.keepAspectRatioPolicy){case"not_larger":return r.axes.length>0?Math.min(...r.axes.map(i=>t[i]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return r.axes.length>0?Math.max(...r.axes.map(i=>t[i]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${r.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let o=e.slice();return r.axes.length>0?(r.axes.forEach(i=>t[i]=n),r.axes.forEach(i=>o[i]=Math.round(e[i]*t[i]))):(t.fill(n,0,t.length),o.forEach((i,a)=>o[a]=Math.round(i*t[a]))),o},Hh=(e,t,r,n,o)=>` - fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${r.length}> { - var original_indices: array<${e.type.value}, ${r.length}>; - for (var i:u32 = 0; i < ${r.length}; i++) { - var output_index = ${e.indicesGet("output_indices","i")}; - var scale = ${F("uniforms.scales","i",n)}; - var roi_low = ${F("uniforms.roi","i",o)}; - var roi_hi = ${F("uniforms.roi",`i + ${t.length}`,o)}; - if (scale == 1.0) { - original_indices[i] = ${e.type.value}(output_index); - } else { - var input_shape_i = ${F("uniforms.input_shape","i",t.length)}; - var output_shape_i = ${F("uniforms.output_shape","i",r.length)}; - original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - } - } - return original_indices; - }`,Fh=(e,t,r,n,o,i,a)=>` - fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { - var input_indices: ${e.type.indices}; - for (var i:u32 = 0; i < ${n.length}; i++) { - var output_index = ${t.indicesGet("output_indices","i")}; - var input_index: u32; - var scale = ${F("uniforms.scales","i",o)}; - if (scale == 1.0) { - input_index = output_index; - } else { - var roi_low = ${F("uniforms.roi","i",i)}; - var roi_hi = ${F("uniforms.roi",`i + ${r.length}`,i)}; - var input_shape_i = ${F("uniforms.input_shape","i",r.length)}; - var output_shape_i = ${F("uniforms.output_shape","i",n.length)}; - var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, - input_shape_i, roi_low, roi_hi); - if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { - if (original_idx < 0) { - input_index = 0; - } else if (original_idx > ${t.type.value}(input_shape_i - 1)) { - input_index = input_shape_i - 1; - } else { - input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); - } - } else { - input_index = u32(original_idx); - } - } - ${e.indicesSet("input_indices","i","input_index")} - } - return input_indices; - }`,qh=(e,t)=>` - fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { - for (var i:u32 = 0; i < ${t.length}; i++) { - var input_index = ${e.indicesGet("input_indices","i")}; - if (input_index < 0 || input_index >= ${F("uniforms.input_shape","i",t.length)}) { - return false; - } - } - return true; - }`,zl=(e,t,r,n)=>e.rank>n?` - ${e.indicesSet("input_indices",t,"channel")}; - ${e.indicesSet("input_indices",r,"batch")}; -`:"",jh=(e,t,r,n,o)=>{let[a,u,d,c]=r.length===2?[-1,0,1,-1]:[0,2,3,1],p=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${p} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",u,`max(0, min(row, ${r[u]} - 1))`)}; - ${e.indicesSet("input_indices",d,`max(0, min(col, ${r[d]} - 1))`)}; - ${zl(e,c,a,2)} - return ${e.getByIndices("input_indices")}; - } - - fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${p} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var row:${p} = originalIndices[${u}]; - var col:${p} = originalIndices[${d}]; - ${n?`if (row < 0 || row > (${r[u]} - 1) || col < 0 || col > (${r[d]} - 1)) { - return ${o}; - }`:""}; - row = max(0, min(row, ${r[u]} - 1)); - col = max(0, min(col, ${r[d]} - 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 = ${r.length>2?`u32(originalIndices[${c}])`:"0"}; - var batch: u32 = ${r.length>2?`u32(originalIndices[${a}])`:"0"}; - var x11: ${p} = getInputValue(batch, channel, row1, col1); - var x12: ${p} = getInputValue(batch, channel, row1, col2); - var x21: ${p} = getInputValue(batch, channel, row2, col1); - var x22: ${p} = getInputValue(batch, channel, row2, col2); - var dx1: ${p} = abs(row - ${p}(row1)); - var dx2: ${p} = abs(${p}(row2) - row); - var dy1: ${p} = abs(col - ${p}(col1)); - var dy2: ${p} = abs(${p}(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); - }`},Kh=(e,t,r,n,o,i,a,u,d,c)=>{let p=r.length===2,m=!0,[f,b]=p?[0,1]:m?[2,3]:[1,2],g=e.type.value,_=S=>{let $=S===f?"row":"col";return` - fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${g} { - var output_index = ${t.indicesGet("output_indices",S)}; - var originalIdx: ${g} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[S]}, - ${n[S]}, ${r[S]}, ${i[S]}, ${i[S]} + ${r.length}); - var fractOriginalIdx: ${g} = originalIdx - floor(originalIdx); - var coefs = getCubicInterpolationCoefs(fractOriginalIdx); - - if (${u} && (originalIdx < 0 || originalIdx > (${r[S]} - 1))) { - return ${d}; - } - var data: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); - for (var i: i32 = -1; i < 3; i++) { - var ${$}: ${g} = originalIdx + ${g}(i); - if (${$} < 0 || ${$} >= ${r[S]}) { - ${c?`coefs[i + 1] = 0.0; - continue;`:u?`return ${d};`:`${$} = max(0, min(${$}, ${r[S]} - 1));`}; - } - var input_indices_copy: ${e.type.indices} = input_indices; - ${e.indicesSet("input_indices_copy",S,`u32(${$})`)}; - data[i + 1] = ${S===f?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; - } - return cubicInterpolation1D(data, coefs); - }`};return` - ${_(f)}; - ${_(b)}; - fn getCubicInterpolationCoefs(s: ${g}) -> array<${g}, 4> { - var absS = abs(s); - var coeffs: array<${g}, 4> = array<${g}, 4>(0.0, 0.0, 0.0, 0.0); - var oneMinusAbsS: ${g} = 1.0 - absS; - var twoMinusAbsS: ${g} = 2.0 - absS; - var onePlusAbsS: ${g} = 1.0 + absS; - coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; - coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; - coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; - coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; - return coeffs; - } - - fn cubicInterpolation1D(x: array<${g}, 4>, coefs: array<${g}, 4>) -> ${g} { - var coefsSum: ${g} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; - return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; - } - - fn bicubicInterpolation(output_indices: ${t.type.indices}) -> ${g} { - var input_indices: ${e.type.indices} = output_indices; - return colCubicInterpolation(input_indices, output_indices); - } - `},Zh=(e,t,r,n,o)=>{let[a,u,d,c,p]=r.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],m=e.type.value;return` - fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${m} { - var input_indices: ${e.type.indices}; - ${e.indicesSet("input_indices",u,`max(0, min(depth, ${r[u]} - 1))`)}; - ${e.indicesSet("input_indices",d,`max(0, min(height, ${r[d]} - 1))`)}; - ${e.indicesSet("input_indices",c,`max(0, min(width, ${r[c]} - 1))`)}; - ${zl(e,p,a,3)} - return ${e.getByIndices("input_indices")}; - } - - fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${m} { - var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); - var depth:${m} = originalIndices[${u}]; - var height:${m} = originalIndices[${d}]; - var width:${m} = originalIndices[${c}]; - ${n?`if (depth < 0 || depth > (${r[u]} - 1) || height < 0 || height > (${r[d]} - 1) || width < 0 || (width > ${r[c]} - 1)) { - return ${o}; - }`:""}; - - depth = max(0, min(depth, ${r[u]} - 1)); - height = max(0, min(height, ${r[d]} - 1)); - width = max(0, min(width, ${r[c]} - 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 = ${r.length>3?`u32(originalIndices[${p}])`:"0"}; - var batch: u32 = ${r.length>3?`u32(originalIndices[${a}])`:"0"}; - - var x111: ${m} = getInputValue(batch, channel, depth1, height1, width1); - var x112: ${m} = getInputValue(batch, channel, depth1, height1, width2); - var x121: ${m} = getInputValue(batch, channel, depth1, height2, width1); - var x122: ${m} = getInputValue(batch, channel, depth1, height2, width2); - var x211: ${m} = getInputValue(batch, channel, depth2, height1, width1); - var x212: ${m} = getInputValue(batch, channel, depth2, height1, width2); - var x221: ${m} = getInputValue(batch, channel, depth2, height2, width1); - var x222: ${m} = getInputValue(batch, channel, depth2, height2, width2); - var dx1: ${m} = abs(depth - ${m}(depth1)); - var dx2: ${m} = abs(${m}(depth2) - depth); - var dy1: ${m} = abs(height - ${m}(height1)); - var dy2: ${m} = abs(${m}(height2) - height); - var dz1: ${m} = abs(width - ${m}(width1)); - var dz2: ${m} = abs(${m}(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); - }`},Qh=(e,t,r,n,o,i)=>{let a=e.dims,u=Wh(i,t.axes,a.length),d=Lh(a,n,o,t.axes),c=n.slice();n.length===0&&(c=a.map((v,x)=>v===0?1:d[x]/v),t.keepAspectRatioPolicy!=="stretch"&&(d=Gh(a,c,t)));let p=M("output",e.dataType,d.length),m=P("input",e.dataType,a.length),f=k.size(d),b=a.length===d.length&&a.every((v,x)=>v===d[x]),g=t.coordinateTransformMode==="tf_crop_and_resize",_=t.extrapolationValue,S=m.type.value,$=v=>` - ${b?"":` - ${Nh(t.coordinateTransformMode,S)}; - ${(()=>{switch(t.mode){case"nearest":return` - ${qh(m,a)}; - ${Vh(t.nearestMode,r,S)}; - ${Fh(m,p,a,d,c.length,u.length,g)}; - `;case"linear":return` - ${Hh(p,a,d,c.length,u.length)}; - ${(()=>{if(a.length===2||a.length===4)return`${jh(m,p,a,g,_)}`;if(a.length===3||a.length===5)return`${Zh(m,p,a,g,_)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; - `;case"cubic":return` - ${(()=>{if(a.length===2||a.length===4)return`${Kh(m,p,a,d,c,u,t.cubicCoeffA,g,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; - `;default:throw Error("Invalid resize mode")}})()}; - `} - ${v.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",u.length).declareVariables(m,p)} - ${v.mainStart()} - ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - ${b?"output[global_idx] = input[global_idx];":` - let output_indices = ${p.offsetToIndices("global_idx")}; - var input_indices: ${m.type.indices}; - ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); - if (checkInputIndices(input_indices)) { - output[global_idx] = ${m.getByIndices("input_indices")}; - } else { - output[global_idx] = ${t.extrapolationValue}; - }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; -`} - }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${r}|${c.length>0?t.mode==="cubic"?c:c.length:""}|${o.length>0?o:""}|${u.length>0?u:""}|${b}|${t.mode==="nearest"?a.length:a}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},{type:1,data:c},{type:1,data:u},...N(a,d)]})}},Yh=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},Ol=(e,t)=>{let r=[],n=[],o=[],i=Yh(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Uh(e.inputs,t,i,r,n,o),e.compute(Qh(e.inputs[0],t,i,r,n,o),{inputs:[0]})},Bl=e=>{let t=e.antialias,r=e.axes,n=e.coordinateTransformMode,o=e.cubicCoeffA,i=e.excludeOutside!==0,a=e.extrapolationValue,u=e.keepAspectRatioPolicy,d=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return J({antialias:t,axes:r,coordinateTransformMode:n,cubicCoeffA:o,excludeOutside:i,extrapolationValue:a,keepAspectRatioPolicy:u,mode:d,nearestMode:c})}});var Xh,Jh,Ml,Rl=U(()=>{"use strict";ee();ne();ie();Xh=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],r=e[1],n=e[2];if(t.dataType!==r.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=t.dims[t.dims.length-1],i=t.dims[t.dims.length-2];if(r.dims[r.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(r.dims[r.dims.length-2]!==i)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Jh=(e,t,r,n)=>{let o=t.simplified,i=e[0].dims,a=k.size(i),u=i,d=a,c=i.slice(-1)[0],p=n?i.slice(0,-1).concat(1):[],m=!o&&e.length>3,f=e.length>4,b=n&&r>1,g=n&&r>2,_=r>3,S=64,$=ce(c),v=[{type:12,data:d},{type:12,data:$},{type:12,data:c},{type:1,data:t.epsilon}],x=E=>{let I=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],z=[P("x",e[0].dataType,e[0].dims,$),P("skip",e[1].dataType,e[1].dims,$),P("gamma",e[2].dataType,e[2].dims,$)];m&&z.push(P("beta",e[3].dataType,e[3].dims,$)),f&&z.push(P("bias",e[4].dataType,e[4].dims,$)),z.push(M("output",e[0].dataType,u,$)),b&&z.push(M("mean_output",1,p)),g&&z.push(M("inv_std_output",1,p)),_&&z.push(M("input_skip_bias_sum",e[0].dataType,u,$));let O=be(e[0].dataType),D=be(1,$);return` - - ${E.registerUniforms(I).declareVariables(...z)} - var sum_shared : array<${D}, ${S}>; - var sum_squared_shared : array<${D}, ${S}>; - - ${E.mainStart([S,1,1])} - let ix = local_id.x; - let iy = global_id.x / ${S}; - - let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; - var stride = hidden_size_vectorized / ${S}; - let offset = ix * stride + iy * hidden_size_vectorized; - let offset1d = stride * ix; - if (ix == ${S-1}) { - stride = hidden_size_vectorized - stride * ix; - } - for (var i: u32 = 0; i < stride; i++) { - let skip_value = skip[offset + i]; - let bias_value = ${f?"bias[offset1d + i]":O+"(0.0)"}; - let input_value = x[offset + i]; - let value = input_value + skip_value + bias_value; - ${_?"input_skip_bias_sum[offset + i] = value;":""} - output[offset + i] = value; - let f32_value = ${Ct(O,$,"value")}; - sum_shared[ix] += f32_value; - sum_squared_shared[ix] += f32_value * f32_value; - } - workgroupBarrier(); - - var reduce_size : u32 = ${S}; - 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 = ${He("sum",$)} / f32(uniforms.hidden_size); - let inv_std_dev = inverseSqrt(${He("square_sum",$)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); - ${b?"mean_output[global_idx] = mean;":""} - ${g?"inv_std_output[global_idx] = inv_std_dev;":""} - - for (var i: u32 = 0; i < stride; i++) { - output[offset + i] = (output[offset + i] ${o?"":`- ${O}(mean)`}) * - ${O}(inv_std_dev) * gamma[offset1d + i] - ${m?"+ beta[offset1d + i]":""}; - } - }`},T=[{dims:u,dataType:e[0].dataType}];return r>1&&T.push({dims:p,dataType:1}),r>2&&T.push({dims:p,dataType:1}),r>3&&T.push({dims:i,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${$};${b};${g};${_}`,inputDependencies:e.map((E,I)=>"type")},getShaderSource:x,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(d/c)},programUniforms:v})}},Ml=(e,t)=>{Xh(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Jh(e.inputs,t,e.outputCount,!1),{outputs:n})}});var eg,nn,tg,Ul,rg,ng,Nl,Vl,Wl=U(()=>{"use strict";ee();ne();Se();ie();eg=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((r,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},nn=(e,t)=>{let r=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>r.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>r.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return r},tg=(e,t)=>{if(e.length>1){let r=nn(e,1),n=nn(e,2),o=nn(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),J({starts:r,ends:n,axes:o})}else return t},Ul=(e,t,r,n,o)=>{let i=e;return e<0&&(i+=r[n[t]]),o[t]<0?Math.max(0,Math.min(i,r[n[t]]-1)):Math.max(0,Math.min(i,r[n[t]]))},rg=(e,t,r)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { - var input_indices: ${e.type.indices}; - var carry = 0u; - for (var i = ${r.length}; i >= 0; i--) { - let input_shape_i = ${F("uniforms.input_shape","i",r.length)}; - let steps_i = ${F("uniforms.steps","i",r.length)}; - let signs_i = ${F("uniforms.signs","i",r.length)}; - let starts_i = ${F("uniforms.starts","i",r.length)}; - var output_index = ${t.indicesGet("output_indices","i")}; - var input_index = output_index * steps_i + starts_i + carry; - carry = input_index / input_shape_i; - input_index = input_index % input_shape_i; - if (signs_i < 0) { - input_index = input_shape_i - input_index - 1u + starts_i; - } - ${e.indicesSet("input_indices","i","input_index")}; - } - return input_indices; - }`,ng=(e,t)=>{let r=e[0].dims,n=k.size(r),o=t.axes.length>0?k.normalizeAxes(t.axes,r.length):[...Array(r.length).keys()],i=nn(e,4);i.forEach($=>$!==0||(()=>{throw new Error("step cannot be 0")})),i.length===0&&(i=Array(o.length).fill(1));let a=t.starts.map(($,v)=>Ul($,v,r,o,i)),u=t.ends.map(($,v)=>Ul($,v,r,o,i));if(o.length!==a.length||o.length!==u.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==r.length)for(let $=0;$Math.sign($));i.forEach(($,v,x)=>{if($<0){let T=(u[v]-a[v])/$,E=a[v],I=E+T*i[v];a[v]=I,u[v]=E,x[v]=-$}});let c=r.slice(0);o.forEach(($,v)=>{c[$]=Math.ceil((u[$]-a[$])/i[$])});let p={dims:c,dataType:e[0].dataType},m=M("output",e[0].dataType,c.length),f=P("input",e[0].dataType,e[0].dims.length),b=k.size(c),g=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:i.length}],_=[{type:12,data:b},{type:12,data:a},{type:6,data:d},{type:12,data:i},...N(e[0].dims,c)],S=$=>` - ${$.registerUniforms(g).declareVariables(f,m)} - ${rg(f,m,r)} - ${$.mainStart()} - ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} - let output_indices = ${m.offsetToIndices("global_idx")}; - let input_indices = calculateInputIndices(output_indices); - ${m.setByOffset("global_idx",f.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${a.length}_${i.length}`,inputDependencies:["rank"]},getShaderSource:S,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:_})}},Nl=(e,t)=>{eg(e.inputs,t);let r=tg(e.inputs,t);e.compute(ng(e.inputs,r),{inputs:[0]})},Vl=e=>{let t=e.starts,r=e.ends,n=e.axes;return J({starts:t,ends:r,axes:n})}});var og,ig,Ll,Gl,Hl=U(()=>{"use strict";ee();ne();Se();st();ie();og=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ig=(e,t)=>{let r=e.inputs[0],n=r.dims,o=k.size(n),i=n.length,a=k.normalizeAxis(t.axis,i),u=aO),c[a]=i-1,c[i-1]=a,d=e.compute(Ee(r,c),{inputs:[r],outputs:[-1]})[0]):d=r;let p=d.dims,m=p[i-1],f=o/m,b=ce(m),g=m/b,_=64;f===1&&(_=256);let S=(z,O)=>O===4?`max(max(${z}.x, ${z}.y), max(${z}.z, ${z}.w))`:O===2?`max(${z}.x, ${z}.y)`:O===3?`max(max(${z}.x, ${z}.y), ${z}.z)`:z,$=P("x",d.dataType,d.dims,b),v=M("result",d.dataType,d.dims,b),x=$.type.value,T=be(d.dataType)==="f32"?`var threadMax = ${x}(-3.402823e+38f);`:`var threadMax = ${x}(-65504.0h);`,E=z=>` - var rowMaxShared : ${x}; - var rowSumShared : ${x}; - var threadShared : array<${x}, ${_}>; - - fn getValue(row: i32, col: i32, row_stride: i32) -> ${x} { - let index = row * row_stride + col; - return x[index]; - } - - fn setValue(row: i32, col: i32, row_stride: i32, value: ${x}) { - let index = row * row_stride + col; - result[index] = value; - } - ${z.registerUniform("packedCols","i32").declareVariables($,v)} - ${z.mainStart(_)} - let gindex = i32(global_idx); - let lindex = i32(local_idx); - const wg = ${_}; - let row = gindex / wg; - let cols = uniforms.packedCols; - let row_stride : i32 = uniforms.packedCols; - - // find the rows max - ${T} - for (var col = lindex; col < cols; col += wg) { - let value = getValue(row, col, row_stride); - threadMax = max(threadMax, value); - } - if (lindex < cols) { - threadShared[lindex] = threadMax; - } - workgroupBarrier(); - - var reduceSize = min(cols, wg); - for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { - reduceSize = currSize + (reduceSize & 1); - if (lindex < currSize) { - threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); - } - workgroupBarrier(); - } - if (lindex == 0) { - rowMaxShared = ${x}(${S("threadShared[0]",b)}); - } - workgroupBarrier(); - - // find the rows sum - var threadSum = ${x}(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 = ${x}(${He("threadShared[0]",b)}); - } - 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); - } - }`,I=e.compute({name:"Softmax",shaderCache:{hint:`${b};${_}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:d.dataType}],dispatchGroup:{x:f},programUniforms:[{type:6,data:g}]}),getShaderSource:E},{inputs:[d],outputs:[u?-1:0]})[0];u&&e.compute(Ee(I,c),{inputs:[I]})},Ll=(e,t)=>{og(e.inputs),ig(e,t)},Gl=e=>J({axis:e.axis})});var Fl,ag,sg,ug,ql,jl=U(()=>{"use strict";ee();ne();ie();Fl=e=>Array.from(e.getBigInt64Array(),Number),ag=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(Fl(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")},sg=(e,t)=>{let r=[];for(let n=0;n{let r=e[0].dims,n=t??Fl(e[1]),o=sg(r,n),i=k.size(o),a=e[0].dataType,u=P("input",a,r.length),d=M("output",a,o.length),c=p=>` - const inputShape = ${u.indices(...r)}; - ${p.registerUniform("output_size","u32").declareVariables(u,d)} - ${p.mainStart()} - ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let output_indices = ${d.offsetToIndices("global_idx")}; - var input_indices: ${u.type.indices}; - for (var i = 0; i < ${r.length}; i++) { - let input_dim_i = ${u.indicesGet("uniforms.input_shape","i")}; - let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; - - ${u.indicesSet("input_indices","i","input_dim_value")} - } - ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},...N(e[0].dims,o)]}),getShaderSource:c}},ql=e=>{ag(e.inputs),e.compute(ug(e.inputs),{inputs:[0]})}});var dg,lg,Kl,Zl=U(()=>{"use strict";ee();ne();ie();dg=(e,t,r,n,o)=>{let i=M("output_data",o,r.length,4),a=P("a_data",t[1].dataType,t[1].dims.length,4),u=P("b_data",t[2].dataType,t[2].dims.length,4),d=P("c_data",t[0].dataType,t[0].dims.length,4),c,p=(m,f,b)=>`select(${f}, ${m}, ${b})`;if(!n)c=i.setByOffset("global_idx",p(a.getByOffset("global_idx"),u.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let m=(f,b,g="")=>{let _=`a_data[index_a${b}][component_a${b}]`,S=`b_data[index_b${b}][component_b${b}]`,$=`bool(c_data[index_c${b}] & (0xffu << (component_c${b} * 8)))`;return` - let output_indices${b} = ${i.offsetToIndices(`global_idx * 4u + ${b}u`)}; - let offset_a${b} = ${a.broadcastedIndicesToOffset(`output_indices${b}`,i)}; - let offset_b${b} = ${u.broadcastedIndicesToOffset(`output_indices${b}`,i)}; - let offset_c${b} = ${d.broadcastedIndicesToOffset(`output_indices${b}`,i)}; - let index_a${b} = offset_a${b} / 4u; - let index_b${b} = offset_b${b} / 4u; - let index_c${b} = offset_c${b} / 4u; - let component_a${b} = offset_a${b} % 4u; - let component_b${b} = offset_b${b} % 4u; - let component_c${b} = offset_c${b} % 4u; - ${f}[${b}] = ${g}(${p(_,S,$)}); - `};o===9?c=` - var data = vec4(0); - ${m("data",0,"u32")} - ${m("data",1,"u32")} - ${m("data",2,"u32")} - ${m("data",3,"u32")} - output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` - ${m("output_data[global_idx]",0)} - ${m("output_data[global_idx]",1)} - ${m("output_data[global_idx]",2)} - ${m("output_data[global_idx]",3)} - `}return` - ${e.registerUniform("vec_size","u32").declareVariables(d,a,u,i)} - ${e.mainStart()} - ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${c} - }`},lg=e=>{let t=e[1].dims,r=e[2].dims,n=e[0].dims,o=e[1].dataType,i=!(k.areEqual(t,r)&&k.areEqual(r,n)),a=t,u=k.size(t);if(i){let c=Je.calcShape(Je.calcShape(t,r,!1),n,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,u=k.size(a)}let d=Math.ceil(u/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>dg(c,e,a,i,o),getRunData:()=>({outputs:[{dims:a,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:d},...N(n,t,r,a)]})}},Kl=e=>{e.compute(lg(e.inputs))}});var Ql,Yl=U(()=>{"use strict";Es();Fr();zs();Bs();_u();ku();Ou();Zu();rd();id();ud();md();gd();yd();vd();Sd();Cd();kd();Od();Md();Fd();Kd();Qd();Xd();tl();$o();nl();wl();xl();Tl();kl();Gr();Dl();To();Rl();Wl();Hl();So();jl();st();jr();Zl();Ql=new Map([["Abs",[Ds]],["Acos",[Ms]],["Acosh",[Rs]],["Add",[wu]],["ArgMax",[As,uo]],["ArgMin",[Cs,uo]],["Asin",[Us]],["Asinh",[Ns]],["Atan",[Vs]],["Atanh",[Ws]],["Attention",[ks]],["AveragePool",[cl,ll]],["BatchNormalization",[Ps]],["BiasAdd",[Os]],["BiasSplitGelu",[yu]],["Cast",[Gs,Ls]],["Ceil",[Fs]],["Clip",[Hs]],["Concat",[Pu,zu]],["Conv",[yo,bo]],["ConvTranspose",[td,Ju]],["Cos",[qs]],["Cosh",[js]],["CumSum",[nd,od]],["DepthToSpace",[ad,sd]],["DequantizeLinear",[vl,$l]],["Div",[vu]],["Einsum",[cd,pd]],["Elu",[Ks,Yt]],["Equal",[$u]],["Erf",[Zs]],["Exp",[Qs]],["Expand",[hd]],["FastGelu",[bd]],["Floor",[Ys]],["FusedConv",[yo,bo]],["Gather",[wd,_d]],["GatherElements",[Ed,Ad]],["GatherBlockQuantized",[Td,Id]],["GatherND",[$d,xd]],["Gelu",[Xs]],["Gemm",[zd,Pd]],["GlobalAveragePool",[fl,ml]],["GlobalMaxPool",[_l,yl]],["Greater",[Iu]],["GreaterOrEqual",[Au]],["GridSample",[Bd,Dd]],["GroupQueryAttention",[Hd]],["HardSigmoid",[au,iu]],["InstanceNormalization",[jd]],["LayerNormalization",[Zd]],["LeakyRelu",[Js,Yt]],["Less",[Cu]],["LessOrEqual",[Eu]],["Log",[hu]],["MatMul",[Yd]],["MatMulNBits",[Jd,el]],["MaxPool",[gl,bl]],["Mul",[xu]],["MultiHeadAttention",[Nd,Ud]],["Neg",[tu]],["Not",[eu]],["Pad",[rl]],["Pow",[Su]],["QuickGelu",[gu,Yt]],["Range",[Sl]],["Reciprocal",[ru]],["ReduceMin",[vs]],["ReduceMean",[gs]],["ReduceMax",[ws]],["ReduceSum",[xs]],["ReduceProd",[$s]],["ReduceL1",[bs]],["ReduceL2",[ys]],["ReduceLogSum",[Ts]],["ReduceLogSumExp",[_s]],["ReduceSumSquare",[Ss]],["Relu",[nu]],["Resize",[Ol,Bl]],["RotaryEmbedding",[Ld]],["ScatterND",[El,Al]],["Sigmoid",[ou]],["Sin",[su]],["Sinh",[uu]],["Slice",[Nl,Vl]],["SkipLayerNormalization",[Ml]],["Split",[Vd,Wd]],["Sqrt",[du]],["Softmax",[Ll,Gl]],["Sub",[Tu]],["Tan",[lu]],["Tanh",[pu]],["ThresholdedRelu",[fu,Yt]],["Tile",[ql]],["Transpose",[ns,os]],["Where",[Kl]]])});var on,Xl=U(()=>{"use strict";We();Xe();ie();on=class{constructor(t){this.backend=t;this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,r){this.repo.set(t,r)}run(t,r,n,o,i){Re(t.programInfo.name);let a=this.backend.device,u=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let d=[];for(let p of r)d.push({binding:d.length,resource:{buffer:p.buffer}});for(let p of n)d.push({binding:d.length,resource:{buffer:p.buffer}});i&&d.push({binding:d.length,resource:i});let c=a.createBindGroup({layout:t.computePipeline.getBindGroupLayout(0),entries:d,label:t.programInfo.name});if(this.backend.sessionStatus==="capturing"){let p={kernelId:this.backend.currentKernelId,computePipeline:t.computePipeline,bindGroup:c,dispatchGroup:o};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(p)}u.setPipeline(t.computePipeline),u.setBindGroup(0,c),u.dispatchWorkgroups(...o),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(),Oe(t.programInfo.name)}dispose(){}build(t,r){Re(t.name);let n=this.backend.device,o=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(m=>{n.features.has(m.feature)&&o.push(`enable ${m.extension};`)});let a=ts(r,this.backend.device.limits),u=t.getShaderSource(a),d=`${o.join(` -`)} -${a.additionalImplementations} -${u}`,c=n.createShaderModule({code:d,label:t.name});se("verbose",()=>`[WebGPU] ${t.name} shader code: ${d}`);let p=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:t.name});return Oe(t.name),{programInfo:t,computePipeline:p,uniformVariablesInfo:a.variablesInfo}}normalizeDispatchGroupSize(t){let r=typeof t=="number"?t:t.x,n=typeof t=="number"?1:t.y||1,o=typeof t=="number"?1:t.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&n<=i&&o<=i)return[r,n,o];let a=r*n*o,u=Math.ceil(Math.sqrt(a));if(u>i){if(u=Math.ceil(Math.cbrt(a)),u>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[u,u,u]}else return[u,u,1]}}});var Jl={};Dt(Jl,{WebGpuBackend:()=>Co});var cg,pg,Io,Co,ec=U(()=>{"use strict";We();ee();Xe();Zn();Ja();Yl();Xl();cg=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let r=[];for(let n=0;n{let n=e.name;return e.shaderCache?.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+r+`:${cg(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,n},Io=class{constructor(t){t&&(this.architecture=t.architecture,this.vendor=t.vendor)}isArchitecture(t){return this.architecture===t}isVendor(t){return this.vendor===t}},Co=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 t=this.kernelCustomData.get(this.currentKernelId);return t||(t={},this.kernelCustomData.set(this.currentKernelId,t)),t}async initialize(t,r){this.env=t;let n=[],o={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:n},i=a=>r.features.has(a)&&n.push(a)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await r.requestDevice(o),this.adapterInfo=new Io(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Xa(this),this.programManager=new on(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Br(t.logLevel,!!t.debug),this.device.onuncapturederror=a=>{a.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${a.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 t=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=t.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Re(),this.endComputePass();let t;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),t=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(t,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,t,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&t.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(t.getMappedRange()),n=this.pendingQueries.get(t);for(let o=0;o"u"&&(this.queryTimeBase=b);let _=Number(b-this.queryTimeBase),S=Number(g-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(S))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:m.map($=>({dims:$.dims,dataType:Ye($.dataType)})),outputsMetadata:f.map($=>({dims:$.dims,dataType:Ye($.dataType)})),kernelId:a,kernelType:d,kernelName:c,programName:p,startTime:_,endTime:S});else{let $="";m.forEach((x,T)=>{$+=`input[${T}]: [${x.dims}] | ${Ye(x.dataType)}, `});let v="";f.forEach((x,T)=>{v+=`output[${T}]: [${x.dims}] | ${Ye(x.dataType)}, `}),console.log(`[profiling] kernel "${a}|${d}|${c}|${p}" ${$}${v}execution time: ${S-_} ns`)}gr("GPU",`${p}::${b}::${g}`)}t.unmap(),this.pendingQueries.delete(t)}),Oe()}run(t,r,n,o,i,a){Re(t.name);let u=[];for(let x=0;xT):n;if(m.length!==d.length)throw new Error(`Output size ${m.length} must be equal to ${d.length}.`);let f=[],b=[];for(let x=0;x=a)throw new Error(`Invalid output index: ${m[x]}`);if(m[x]===-3)continue;let T=m[x]===-1,E=m[x]===-2,I=T||E?i(d[x].dataType,d[x].dims):o(m[x],d[x].dataType,d[x].dims);if(f.push(I),I.data===0)continue;let z=this.gpuDataManager.get(I.data);if(!z)throw new Error(`no GPU data for output: ${I.data}`);if(T&&this.temporaryData.push(z),E){let O=this.kernelPersistentData.get(this.currentKernelId);O||(O=[],this.kernelPersistentData.set(this.currentKernelId,O)),O.push(z)}b.push(z)}if(u.length!==r.length||b.length!==f.length){if(b.length===0)return Oe(t.name),f;throw new Error(`Program ${t.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let g;if(p){let x=0,T=[];p.forEach(O=>{let D=typeof O.data=="number"?[O.data]:O.data;if(D.length===0)return;let L=O.type===10?2:4,q,Q;O.type===10?(Q=D.length>4?16:D.length>2?8:D.length*L,q=D.length>4?16:L*D.length):(Q=D.length<=2?D.length*L:16,q=16),x=Math.ceil(x/Q)*Q,T.push(x);let W=O.type===10?8:4;x+=D.length>4?Math.ceil(D.length/W)*q:D.length*L});let E=16;x=Math.ceil(x/E)*E;let I=new ArrayBuffer(x);p.forEach((O,D)=>{let L=T[D],q=typeof O.data=="number"?[O.data]:O.data;if(O.type===6)new Int32Array(I,L,q.length).set(q);else if(O.type===12)new Uint32Array(I,L,q.length).set(q);else if(O.type===10)new Uint16Array(I,L,q.length).set(q);else if(O.type===1)new Float32Array(I,L,q.length).set(q);else throw new Error(`Unsupported uniform type: ${Ye(O.type)}`)});let z=this.gpuDataManager.create(x,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(z.buffer,0,I,0,x),this.gpuDataManager.release(z.id),g={offset:0,size:x,buffer:z.buffer}}let _=this.programManager.normalizeDispatchGroupSize(c),S=_[1]===1&&_[2]===1,$=pg(t,r,S),v=this.programManager.getArtifact($);if(v||(v=this.programManager.build(t,_),this.programManager.setArtifact($,v),se("info",()=>`[artifact] key: ${$}, programName: ${t.name}`)),p&&v.uniformVariablesInfo){if(p.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${p.length} in program "${v.programInfo.name}".`);for(let x=0;x`[ProgramManager] run "${t.name}" (key=${$}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let x={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:f};this.pendingKernels.push(x),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(x)}return this.programManager.run(v,u,b,_,g),Oe(t.name),f}upload(t,r){this.gpuDataManager.upload(t,r)}memcpy(t,r){this.gpuDataManager.memcpy(t,r)}async download(t,r){await this.gpuDataManager.download(t,r)}alloc(t){return this.gpuDataManager.create(t).id}free(t){return this.gpuDataManager.release(t)}createKernel(t,r,n,o){let i=Ql.get(t);if(!i)throw new Error(`kernel not implemented: ${t}`);let a={kernelType:t,kernelName:o,kernelEntry:i[0],attributes:[i[1],n]};this.kernels.set(r,a)}releaseKernel(t){let r=this.kernelPersistentData.get(t);if(r){for(let n of r)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(t)}this.kernelCustomData.delete(t),this.kernels.delete(t)}computeKernel(t,r,n){let o=this.kernels.get(t);if(!o)throw new Error(`kernel not created: ${t}`);let i=o.kernelType,a=o.kernelName,u=o.kernelEntry,d=o.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${a}" is not allowed to be called recursively`);this.currentKernelId=t,d[0]&&(d[1]=d[0](d[1]),d[0]=void 0),se("info",()=>`[WebGPU] Start to run kernel "[${i}] ${a}"...`);let c=this.env.debug;this.temporaryData=[];try{return c&&this.device.pushErrorScope("validation"),u(r,d[1]),0}catch(p){return n.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${a}" failed. ${p}`)),1}finally{c&&n.push(this.device.popErrorScope().then(p=>p?`GPU validation error for kernel "[${i}] ${a}": ${p.message}`:null));for(let p of this.temporaryData)this.gpuDataManager.release(p.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(t,r,n,o){let i=this.sessionExternalDataMapping.get(t);i||(i=new Map,this.sessionExternalDataMapping.set(t,i));let a=i.get(r),u=this.gpuDataManager.registerExternalBuffer(n,o,a);return i.set(r,[u,n]),u}unregisterBuffers(t){let r=this.sessionExternalDataMapping.get(t);r&&(r.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(t))}getBuffer(t){let r=this.gpuDataManager.get(t);if(!r)throw new Error(`no GPU data for buffer: ${t}`);return r.buffer}createDownloader(t,r,n){return async()=>{let o=await ro(this,t,r);return Mr(o.buffer,n)}}writeTimestamp(t){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,t)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){se("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(){se("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){se("info","replay"),this.sessionStatus="replaying";let t=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),n=t.length;this.pendingKernels=[];for(let o=0;o=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(t){this.unregisterBuffers(t),this.capturedCommandList.has(t)&&this.capturedCommandList.delete(t),this.capturedPendingKernels.has(t)&&this.capturedPendingKernels.delete(t),this.gpuDataManager.onReleaseSession(t)}onRunStart(t){this.currentSessionId=t,this.setQueryType()}}});var tc={};Dt(tc,{init:()=>mg});var tr,Ao,mg,rc=U(()=>{"use strict";ee();Xe();ne();Ka();tr=class e{constructor(t,r,n,o){this.module=t;this.dataType=r;this.data=n;this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=k.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(k.size(t)!==k.size(this.dims))throw new Error("Invalid new shape");return new e(this.module,this.dataType,this.data,t)}},Ao=class{constructor(t,r,n){this.module=t;this.backend=r;this.customDataOffset=0;this.customDataSize=0;this.adapterInfo=r.adapterInfo;let o=t.PTR_SIZE,i=n/t.PTR_SIZE,a=o===4?"i32":"i64";this.opKernelContext=Number(t.getValue(o*i++,a));let u=Number(t.getValue(o*i++,a));this.outputCount=Number(t.getValue(o*i++,a)),this.customDataOffset=Number(t.getValue(o*i++,"*")),this.customDataSize=Number(t.getValue(o*i++,a));let d=[];for(let c=0;ctypeof u=="number"?this.inputs[u]:u)??this.inputs,o=r?.outputs??[],i=(u,d,c)=>new tr(this.module,d,this.output(u,c),c),a=(u,d)=>{let c=gt(u,d);if(!c)throw new Error(`Unsupported data type: ${u}`);let p=c>0?this.backend.gpuDataManager.create(c).id:0;return new tr(this.module,u,p,d)};return this.backend.run(t,n,o,i,a,this.outputCount)}output(t,r){let n=this.module.stackSave();try{let o=this.module.PTR_SIZE,i=o===4?"i32":"i64",a=this.module.stackAlloc((1+r.length)*o);this.module.setValue(a,r.length,i);for(let u=0;u{let o=t.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let i=(ec(),Ft(Jl)).WebGpuBackend,a=new i;await a.initialize(r,n),o("webgpu",[a,u=>a.alloc(Number(u)),u=>a.free(u),(u,d,c,p=!1)=>{if(p)se("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(u)}, dst=${Number(d)}, size=${Number(c)}`),a.memcpy(Number(u),Number(d));else{se("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(u)}, gpuDataId=${Number(d)}, size=${Number(c)}`);let m=t.HEAPU8.subarray(Number(u>>>0),Number(u>>>0)+Number(c));a.upload(Number(d),m)}},async(u,d,c)=>{se("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${u}, dataOffset=${d}, size=${c}`),await a.download(Number(u),()=>t.HEAPU8.subarray(Number(d)>>>0,Number(d+c)>>>0))},(u,d,c)=>a.createKernel(u,Number(d),c,t.UTF8ToString(t._JsepGetNodeName(Number(d)))),u=>a.releaseKernel(u),(u,d,c,p)=>{se("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${u}, contextDataOffset=${d}`);let m=new Ao(t,a,Number(d));return a.computeKernel(Number(u),m,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let i=new Nr(r);o("webnn",[i,()=>i.reserveTensorId(),a=>i.releaseTensorId(a),async(a,u,d,c,p)=>i.ensureTensor(a,u,d,c,p),(a,u)=>{i.uploadTensor(a,u)},async(a,u)=>i.downloadTensor(a,u)])}}});var fg,vr,$r,At,hg,nc,jt,xr,Sr,oc,Tr,Ir,Cr,Vn=U(()=>{"use strict";Ma();Ua();ee();ht();Er();jn();fg=(e,t)=>{fe()._OrtInit(e,t)!==0&&pe("Can't initialize onnxruntime.")},vr=async e=>{fg(e.wasm.numThreads,Zt(e.logLevel))},$r=async(e,t)=>{fe().asyncInit?.();{let r=(rc(),Ft(tc)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let o=e.webgpu.powerPreference;if(o!==void 0&&o!=="low-power"&&o!=="high-performance")throw new Error(`Invalid powerPreference setting: "${o}"`);let i=e.webgpu.forceFallbackAdapter;if(i!==void 0&&typeof i!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:o,forceFallbackAdapter:i}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await r("webgpu",fe(),e,n)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await r("webnn",fe(),e)}}},At=new Map,hg=e=>{let t=fe(),r=t.stackSave();try{let n=t.PTR_SIZE,o=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,o,o+n)!==0&&pe("Can't get session input/output count.");let a=n===4?"i32":"i64";return[Number(t.getValue(o,a)),Number(t.getValue(o+n,a))]}finally{t.stackRestore(r)}},nc=(e,t)=>{let r=fe(),n=r.stackSave(),o=0;try{let i=r.PTR_SIZE,a=r.stackAlloc(2*i);r._OrtGetInputOutputMetadata(e,t,a,a+i)!==0&&pe("Can't get session input/output metadata.");let d=Number(r.getValue(a,"*"));o=Number(r.getValue(a+i,"*"));let c=r.HEAP32[o/4];if(c===0)return[d,0];let p=r.HEAPU32[o/4+1],m=[];for(let f=0;f{let t=fe(),r=t._malloc(e.byteLength);if(r===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,r),[r,e.byteLength]},xr=async(e,t)=>{let r,n,o=fe();Array.isArray(e)?[r,n]=e:e.buffer===o.HEAPU8.buffer?[r,n]=[e.byteOffset,e.byteLength]:[r,n]=jt(e);let i=0,a=0,u=0,d=[],c=[],p=[];try{if([a,d]=await Ra(t),t?.externalData&&o.mountExternalData){let T=[];for(let E of t.externalData){let I=typeof E=="string"?E:E.path;T.push(Qt(typeof E=="string"?E:E.data).then(z=>{o.mountExternalData(I,z)}))}await Promise.all(T)}for(let T of t?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof T!="string"){let I=T,z=I?.context,O=I?.gpuDevice,D=I?.deviceType,L=I?.powerPreference;z?o.currentContext=z:O?o.currentContext=await o.webnnCreateMLContext(O):o.currentContext=await o.webnnCreateMLContext({deviceType:D,powerPreference:L})}else o.currentContext=await o.webnnCreateMLContext();break}i=await o._OrtCreateSession(r,n,a),o.webgpuOnCreateSession?.(i),i===0&&pe("Can't create a session."),o.jsepOnCreateSession?.(),o.currentContext&&(o.webnnRegisterMLContext(i,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[m,f]=hg(i),b=!!t?.enableGraphCapture,g=[],_=[],S=[],$=[],v=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor")&&(u=o._OrtCreateBinding(i),u===0&&pe("Can't create IO binding."),x={handle:u,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(T=>qn(T))}),At.set(i,[i,c,p,x,b,!1]),[i,g,_,S,$]}catch(m){throw c.forEach(f=>o._OrtFree(f)),p.forEach(f=>o._OrtFree(f)),u!==0&&o._OrtReleaseBinding(u)!==0&&pe("Can't release IO binding."),i!==0&&o._OrtReleaseSession(i)!==0&&pe("Can't release session."),m}finally{o._free(r),a!==0&&o._OrtReleaseSessionOptions(a)!==0&&pe("Can't release session options."),d.forEach(m=>o._free(m)),o.unmountExternalData?.()}},Sr=e=>{let t=fe(),r=At.get(e);if(!r)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,o,i,a,u]=r;a&&(u&&t._OrtClearBoundOutputs(a.handle)!==0&&pe("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&pe("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),o.forEach(d=>t._OrtFree(d)),i.forEach(d=>t._OrtFree(d)),t._OrtReleaseSession(n)!==0&&pe("Can't release session."),At.delete(e)},oc=async(e,t,r,n,o,i,a=!1)=>{if(!e){t.push(0);return}let u=fe(),d=u.PTR_SIZE,c=e[0],p=e[1],m=e[3],f=m,b,g;if(c==="string"&&(m==="gpu-buffer"||m==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&m!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(m==="gpu-buffer"){let $=e[2].gpuBuffer;g=gt(Mt(c),p);{let v=u.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');b=v(n,i,$,g)}}else if(m==="ml-tensor"){let $=e[2].mlTensor;g=gt(Mt(c),p);let v=u.webnnRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');b=v(n,$,Mt(c),p)}else{let $=e[2];if(Array.isArray($)){g=d*$.length,b=u._malloc(g),r.push(b);for(let v=0;v<$.length;v++){if(typeof $[v]!="string")throw new TypeError(`tensor data at index ${v} is not a string`);u.setValue(b+v*d,Ne($[v],r),"*")}}else{let v=u.webnnIsGraphInput;if(c!=="string"&&v){let x=u.UTF8ToString(o);if(v(n,x)){let T=Mt(c);g=gt(T,p),f="ml-tensor";let E=u.webnnCreateTemporaryTensor,I=u.webnnUploadTensor;if(!E||!I)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let z=await E(n,T,p);I(z,new Uint8Array($.buffer,$.byteOffset,$.byteLength)),b=z}else g=$.byteLength,b=u._malloc(g),r.push(b),u.HEAPU8.set(new Uint8Array($.buffer,$.byteOffset,g),b)}else g=$.byteLength,b=u._malloc(g),r.push(b),u.HEAPU8.set(new Uint8Array($.buffer,$.byteOffset,g),b)}}let _=u.stackSave(),S=u.stackAlloc(4*p.length);try{p.forEach((v,x)=>u.setValue(S+x*d,v,d===4?"i32":"i64"));let $=u._OrtCreateTensor(Mt(c),b,g,S,p.length,qn(f));$===0&&pe(`Can't create tensor for input/output. session=${n}, index=${i}.`),t.push($)}finally{u.stackRestore(_)}},Tr=async(e,t,r,n,o,i)=>{let a=fe(),u=a.PTR_SIZE,d=At.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=d[0],p=d[1],m=d[2],f=d[3],b=d[4],g=d[5],_=t.length,S=n.length,$=0,v=[],x=[],T=[],E=[],I=a.stackSave(),z=a.stackAlloc(_*u),O=a.stackAlloc(_*u),D=a.stackAlloc(S*u),L=a.stackAlloc(S*u);try{[$,v]=Da(i);for(let W=0;W<_;W++)await oc(r[W],x,E,e,p[t[W]],t[W],b);for(let W=0;Wve*$e,1);te=Ye(ye);let ze=f?.outputPreferredLocations[n[W]];if(te==="string"){if(ze==="gpu-buffer"||ze==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ve=[];for(let $e=0;$e0){let ve=a.jsepGetBuffer;if(!ve)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let $e=ve(X),Ce=gt(ye,de);if(Ce===void 0||!zr(te))throw new Error(`Unsupported data type: ${te}`);j=!0,Q.push([te,V,{gpuBuffer:$e,download:a.jsepCreateDownloader($e,Ce,te),dispose:()=>{a._OrtReleaseTensor(Z)!==0&&pe("Can't release tensor.")}},"gpu-buffer"])}else if(ze==="ml-tensor"&&de>0){let ve=a.webnnEnsureTensor,$e=a.webnnIsInt64Supported;if(!ve||!$e)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(gt(ye,de)===void 0||!Or(te))throw new Error(`Unsupported data type: ${te}`);if(te==="int64"&&!$e(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let _t=await ve(e,X,ye,V,!1);j=!0,Q.push([te,V,{mlTensor:_t,download:a.webnnCreateMLTensorDownloader(X,te),dispose:()=>{a.webnnReleaseTensorId(X),a._OrtReleaseTensor(Z)}},"ml-tensor"])}else{let ve=Pr(te),$e=new ve(de);new Uint8Array($e.buffer,$e.byteOffset,$e.byteLength).set(a.HEAPU8.subarray(X,X+$e.byteLength)),Q.push([te,V,$e,"cpu"])}}finally{a.stackRestore(we),te==="string"&&X&&a._free(X),j||a._OrtReleaseTensor(Z),a.webnnOnRunEnd?.(c)}}return f&&!b&&(a._OrtClearBoundOutputs(f.handle)!==0&&pe("Can't clear bound outputs."),At.set(e,[c,p,m,f,b,!1])),Q}finally{a.stackRestore(I),x.forEach(q=>a._OrtReleaseTensor(q)),T.forEach(q=>a._OrtReleaseTensor(q)),E.forEach(q=>a._free(q)),$!==0&&a._OrtReleaseRunOptions($),v.forEach(q=>a._free(q))}},Ir=e=>{let t=fe(),r=At.get(e);if(!r)throw new Error("invalid session id");let n=r[0],o=t._OrtEndProfiling(n);o===0&&pe("Can't get an profile file name."),t._OrtFree(o)},Cr=e=>{let t=[];for(let r of e){let n=r[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}});var Et,Le,rr,sn,un,an,Eo,ko,Vt,Wt,bg,ic,ac,sc,uc,dc,lc,cc,Po=U(()=>{"use strict";We();Vn();ht();_r();Et=()=>!!ge.wasm.proxy&&typeof document<"u",rr=!1,sn=!1,un=!1,ko=new Map,Vt=(e,t)=>{let r=ko.get(e);r?r.push(t):ko.set(e,[t])},Wt=()=>{if(rr||!sn||un||!Le)throw new Error("worker not ready")},bg=e=>{switch(e.data.type){case"init-wasm":rr=!1,e.data.err?(un=!0,Eo[1](e.data.err)):(sn=!0,Eo[0]()),an&&(URL.revokeObjectURL(an),an=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=ko.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},ic=async()=>{if(!sn){if(rr)throw new Error("multiple calls to 'initWasm()' detected.");if(un)throw new Error("previous call to 'initWasm()' failed.");if(rr=!0,Et())return new Promise((e,t)=>{Le?.terminate(),za().then(([r,n])=>{try{Le=n,Le.onerror=i=>t(i),Le.onmessage=bg,Eo=[e,t];let o={type:"init-wasm",in:ge};!o.in.wasm.wasmPaths&&(r||Gn)&&(o.in.wasm.wasmPaths={wasm:new URL(/* asset import */ __webpack_require__(/*! ort-wasm-simd-threaded.jsep.wasm */ "./node_modules/onnxruntime-web/dist/ort-wasm-simd-threaded.jsep.wasm"), __webpack_require__.b).href}),Le.postMessage(o),an=r}catch(o){t(o)}},t)});try{await wr(ge.wasm),await vr(ge),sn=!0}catch(e){throw un=!0,e}finally{rr=!1}}},ac=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt("init-ep",[t,r]);let n={type:"init-ep",in:{epName:e,env:ge}};Le.postMessage(n)});await $r(ge,e)},sc=async e=>Et()?(Wt(),new Promise((t,r)=>{Vt("copy-from",[t,r]);let n={type:"copy-from",in:{buffer:e}};Le.postMessage(n,[e.buffer])})):jt(e),uc=async(e,t)=>{if(Et()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Wt(),new Promise((r,n)=>{Vt("create",[r,n]);let o={type:"create",in:{model:e,options:{...t}}},i=[];e instanceof Uint8Array&&i.push(e.buffer),Le.postMessage(o,i)})}else return xr(e,t)},dc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt("release",[t,r]);let n={type:"release",in:e};Le.postMessage(n)});Sr(e)},lc=async(e,t,r,n,o,i)=>{if(Et()){if(r.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Wt(),new Promise((a,u)=>{Vt("run",[a,u]);let d=r,c={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:i}};Le.postMessage(c,Cr(d))})}else return Tr(e,t,r,n,o,i)},cc=async e=>{if(Et())return Wt(),new Promise((t,r)=>{Vt("end-profiling",[t,r]);let n={type:"end-profiling",in:e};Le.postMessage(n)});Ir(e)}});var pc,yg,dn,mc=U(()=>{"use strict";We();Po();ee();yr();jn();pc=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},yg=e=>{switch(e[3]){case"cpu":return new Ge(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!zr(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:r,download:n,dispose:o}=e[2];return Ge.fromGpuBuffer(r,{dataType:t,dims:e[1],download:n,dispose:o})}case"ml-tensor":{let t=e[0];if(!Or(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:r,download:n,dispose:o}=e[2];return Ge.fromMLTensor(r,{dataType:t,dims:e[1],download:n,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},dn=class{async fetchModelAndCopyToWasmMemory(t){return sc(await Qt(t))}async loadModel(t,r){Re();let n;typeof t=="string"?n=await this.fetchModelAndCopyToWasmMemory(t):n=t,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await uc(n,r),Oe()}async dispose(){return dc(this.sessionId)}async run(t,r,n){Re();let o=[],i=[];Object.entries(t).forEach(f=>{let b=f[0],g=f[1],_=this.inputNames.indexOf(b);if(_===-1)throw new Error(`invalid input '${b}'`);o.push(g),i.push(_)});let a=[],u=[];Object.entries(r).forEach(f=>{let b=f[0],g=f[1],_=this.outputNames.indexOf(b);if(_===-1)throw new Error(`invalid output '${b}'`);a.push(g),u.push(_)});let d=o.map((f,b)=>pc(f,()=>`input "${this.inputNames[i[b]]}"`)),c=a.map((f,b)=>f?pc(f,()=>`output "${this.outputNames[u[b]]}"`):null),p=await lc(this.sessionId,i,d,u,c,n),m={};for(let f=0;fln,initializeFlags:()=>fc,wasmBackend:()=>_g});var fc,ln,_g,gc=U(()=>{"use strict";We();Po();mc();fc=()=>{(typeof ge.wasm.initTimeout!="number"||ge.wasm.initTimeout<0)&&(ge.wasm.initTimeout=0);let e=ge.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),ge.wasm.simd=!1),typeof ge.wasm.proxy!="boolean"&&(ge.wasm.proxy=!1),typeof ge.wasm.trace!="boolean"&&(ge.wasm.trace=!1),typeof ge.wasm.numThreads!="number"||!Number.isInteger(ge.wasm.numThreads)||ge.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)ge.wasm.numThreads=1;else{let t=typeof navigator>"u"?On("node:os").cpus().length:navigator.hardwareConcurrency;ge.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ln=class{async init(t){fc(),await ic(),await ac(t)}async createInferenceSessionHandler(t,r){let n=new dn;return await n.loadModel(t,r),n}},_g=new ln});We();We();We();var _a="1.22.0-dev.20250409-89f8206ba4";var IS=Nn;{let e=(gc(),Ft(hc)).wasmBackend;$t("webgpu",e,5),$t("webnn",e,5),$t("cpu",e,10),$t("wasm",e,10)}Object.defineProperty(ge.versions,"web",{value:_a,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. - * ============================================================================= - */ -//# sourceMappingURL=ort.bundle.min.mjs.map - - -/***/ }), - -/***/ "./src/backends/onnx.js": -/*!******************************!*\ - !*** ./src/backends/onnx.js ***! - \******************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -var onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Tensor: () => (/* reexport safe */ onnxruntime_common__WEBPACK_IMPORTED_MODULE_3__.Tensor), -/* harmony export */ createInferenceSession: () => (/* binding */ createInferenceSession), -/* harmony export */ deviceToExecutionProviders: () => (/* binding */ deviceToExecutionProviders), -/* harmony export */ isONNXProxy: () => (/* binding */ isONNXProxy), -/* harmony export */ isONNXTensor: () => (/* binding */ isONNXTensor) -/* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); -/* harmony import */ var onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! onnxruntime-node */ "?2ce3"); -/* harmony import */ var onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! onnxruntime-web */ "./node_modules/onnxruntime-web/dist/ort.bundle.min.mjs?3a96"); -/* harmony import */ var onnxruntime_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! onnxruntime-common */ "./node_modules/onnxruntime-common/dist/esm/index.js"); -/** - * @file Handler file for choosing the correct version of ONNX Runtime, based on the environment. - * Ideally, we could import the `onnxruntime-web` and `onnxruntime-node` packages only when needed, - * but dynamic imports don't seem to work with the current webpack version and/or configuration. - * This is possibly due to the experimental nature of top-level await statements. - * So, we just import both packages, and use the appropriate one based on the environment: - * - When running in node, we use `onnxruntime-node`. - * - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled). - * - * This module is not directly exported, but can be accessed through the environment variables: - * ```javascript - * import { env } from '@huggingface/transformers'; - * console.log(env.backends.onnx); - * ``` - * - * @module backends/onnx - */ - - - -// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`. -// In either case, we select the default export if it exists, otherwise we use the named export. - - - - - -/** - * @typedef {import('onnxruntime-common').InferenceSession.ExecutionProviderConfig} ONNXExecutionProviders - */ - -/** @type {Record} */ -const DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({ - auto: null, // Auto-detect based on device and environment - gpu: null, // Auto-detect GPU - cpu: 'cpu', // CPU - wasm: 'wasm', // WebAssembly - webgpu: 'webgpu', // WebGPU - cuda: 'cuda', // CUDA - dml: 'dml', // DirectML - - webnn: { name: 'webnn', deviceType: 'cpu' }, // WebNN (default) - 'webnn-npu': { name: 'webnn', deviceType: 'npu' }, // WebNN NPU - 'webnn-gpu': { name: 'webnn', deviceType: 'gpu' }, // WebNN GPU - 'webnn-cpu': { name: 'webnn', deviceType: 'cpu' }, // WebNN CPU -}); - -/** - * The list of supported devices, sorted by priority/performance. - * @type {import("../utils/devices.js").DeviceType[]} - */ -const supportedDevices = []; - -/** @type {ONNXExecutionProviders[]} */ -let defaultDevices; -let ONNX; -const ORT_SYMBOL = Symbol.for('onnxruntime'); - -if (ORT_SYMBOL in globalThis) { - // If the JS runtime exposes their own ONNX runtime, use it - ONNX = globalThis[ORT_SYMBOL]; - -} else if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_NODE_ENV) { - ONNX = onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__ ?? /*#__PURE__*/ (onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache || (onnxruntime_node__WEBPACK_IMPORTED_MODULE_1___namespace_cache = __webpack_require__.t(onnxruntime_node__WEBPACK_IMPORTED_MODULE_1__, 2))); - - // Updated as of ONNX Runtime 1.20.1 - // The following table lists the supported versions of ONNX Runtime Node.js binding provided with pre-built binaries. - // | EPs/Platforms | Windows x64 | Windows arm64 | Linux x64 | Linux arm64 | MacOS x64 | MacOS arm64 | - // | ------------- | ----------- | ------------- | ----------------- | ----------- | --------- | ----------- | - // | CPU | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | - // | DirectML | ✔️ | ✔️ | ❌ | ❌ | ❌ | ❌ | - // | CUDA | ❌ | ❌ | ✔️ (CUDA v11.8) | ❌ | ❌ | ❌ | - switch (process.platform) { - case 'win32': // Windows x64 and Windows arm64 - supportedDevices.push('dml'); - break; - case 'linux': // Linux x64 and Linux arm64 - if (process.arch === 'x64') { - supportedDevices.push('cuda'); - } - break; - case 'darwin': // MacOS x64 and MacOS arm64 - break; - } - - supportedDevices.push('cpu'); - defaultDevices = ['cpu']; -} else { - ONNX = onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__; - - if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBNN_AVAILABLE) { - // TODO: Only push supported providers (depending on available hardware) - supportedDevices.push('webnn-npu', 'webnn-gpu', 'webnn-cpu', 'webnn'); - } - - if (_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBGPU_AVAILABLE) { - supportedDevices.push('webgpu'); - } - - supportedDevices.push('wasm'); - defaultDevices = ['wasm']; -} - -// @ts-ignore -const InferenceSession = ONNX.InferenceSession; - -/** - * Map a device to the execution providers to use for the given device. - * @param {import("../utils/devices.js").DeviceType|"auto"|null} [device=null] (Optional) The device to run the inference on. - * @returns {ONNXExecutionProviders[]} The execution providers to use for the given device. - */ -function deviceToExecutionProviders(device = null) { - // Use the default execution providers if the user hasn't specified anything - if (!device) return defaultDevices; - - // Handle overloaded cases - switch (device) { - case "auto": - return supportedDevices; - case "gpu": - return supportedDevices.filter(x => - ["webgpu", "cuda", "dml", "webnn-gpu"].includes(x), - ); - } - - if (supportedDevices.includes(device)) { - return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device]; - } - - throw new Error(`Unsupported device: "${device}". Should be one of: ${supportedDevices.join(', ')}.`) -} - - -/** - * To prevent multiple calls to `initWasm()`, we store the first call in a Promise - * that is resolved when the first InferenceSession is created. Subsequent calls - * will wait for this Promise to resolve before creating their own InferenceSession. - * @type {Promise|null} - */ -let wasmInitPromise = null; - -/** - * Create an ONNX inference session. - * @param {Uint8Array|string} buffer_or_path The ONNX model buffer or path. - * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options ONNX inference session options. - * @param {Object} session_config ONNX inference session configuration. - * @returns {Promise} The ONNX inference session. - */ -async function createInferenceSession(buffer_or_path, session_options, session_config) { - if (wasmInitPromise) { - // A previous session has already initialized the WASM runtime - // so we wait for it to resolve before creating this new session. - await wasmInitPromise; - } - - const sessionPromise = InferenceSession.create(buffer_or_path, session_options); - wasmInitPromise ??= sessionPromise; - const session = await sessionPromise; - session.config = session_config; - return session; -} - -/** - * Check if an object is an ONNX tensor. - * @param {any} x The object to check - * @returns {boolean} Whether the object is an ONNX tensor. - */ -function isONNXTensor(x) { - return x instanceof ONNX.Tensor; -} - -/** @type {import('onnxruntime-common').Env} */ -// @ts-ignore -const ONNX_ENV = ONNX?.env; -if (ONNX_ENV?.wasm) { - // Initialize wasm backend with suitable default settings. - - // (Optional) Set path to wasm files. This will override the default path search behavior of onnxruntime-web. - // By default, we only do this if we are not in a service worker and the wasmPaths are not already set. - if ( - // @ts-ignore Cannot find name 'ServiceWorkerGlobalScope'.ts(2304) - !(typeof ServiceWorkerGlobalScope !== 'undefined' && self instanceof ServiceWorkerGlobalScope) - && !ONNX_ENV.wasm.wasmPaths - ) { - ONNX_ENV.wasm.wasmPaths = `https://cdn.jsdelivr.net/npm/@huggingface/transformers@${_env_js__WEBPACK_IMPORTED_MODULE_0__.env.version}/dist/`; - } - - // TODO: Add support for loading WASM files from cached buffer when we upgrade to onnxruntime-web@1.19.0 - // https://github.com/microsoft/onnxruntime/pull/21534 - - // Users may wish to proxy the WASM backend to prevent the UI from freezing, - // However, this is not necessary when using WebGPU, so we default to false. - ONNX_ENV.wasm.proxy = false; -} - -if (ONNX_ENV?.webgpu) { - ONNX_ENV.webgpu.powerPreference = 'high-performance'; -} - -/** - * Check if ONNX's WASM backend is being proxied. - * @returns {boolean} Whether ONNX's WASM backend is being proxied. - */ -function isONNXProxy() { - // TODO: Update this when allowing non-WASM backends. - return ONNX_ENV?.wasm?.proxy; -} - -// Expose ONNX environment variables to `env.backends.onnx` -_env_js__WEBPACK_IMPORTED_MODULE_0__.env.backends.onnx = ONNX_ENV; - - -/***/ }), - -/***/ "./src/base/feature_extraction_utils.js": -/*!**********************************************!*\ - !*** ./src/base/feature_extraction_utils.js ***! - \**********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ FeatureExtractor: () => (/* binding */ FeatureExtractor), -/* harmony export */ validate_audio_inputs: () => (/* binding */ validate_audio_inputs) -/* harmony export */ }); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/constants.js */ "./src/utils/constants.js"); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/hub.js */ "./src/utils/hub.js"); - - - - -/** - * Base class for feature extractors. - */ -class FeatureExtractor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__.Callable { - /** - * Constructs a new FeatureExtractor instance. - * - * @param {Object} config The configuration for the feature extractor. - */ - constructor(config) { - super(); - this.config = config - } - - /** - * Instantiate one of the feature extractor classes of the library from a pretrained model. - * - * The feature extractor class to instantiate is selected based on the `feature_extractor_type` property of - * the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing feature_extractor files, e.g., `./my_model_directory/`. - * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the feature_extractor. - * - * @returns {Promise} A new instance of the Feature Extractor class. - */ - static async from_pretrained(pretrained_model_name_or_path, options={}) { - const config = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.FEATURE_EXTRACTOR_NAME, true, options); - return new this(config); - } -} - - -/** - * Helper function to validate audio inputs. - * @param {any} audio The audio data. - * @param {string} feature_extractor The name of the feature extractor. - * @private - */ -function validate_audio_inputs(audio, feature_extractor) { - if (!(audio instanceof Float32Array || audio instanceof Float64Array)) { - throw new Error( - `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} 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": -/*!********************************************!*\ - !*** ./src/base/image_processors_utils.js ***! - \********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ImageProcessor: () => (/* binding */ ImageProcessor), -/* harmony export */ center_to_corners_format: () => (/* binding */ center_to_corners_format), -/* harmony export */ post_process_instance_segmentation: () => (/* binding */ post_process_instance_segmentation), -/* harmony export */ post_process_object_detection: () => (/* binding */ post_process_object_detection), -/* harmony export */ post_process_panoptic_segmentation: () => (/* binding */ post_process_panoptic_segmentation), -/* harmony export */ post_process_semantic_segmentation: () => (/* binding */ post_process_semantic_segmentation) -/* harmony export */ }); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/image.js */ "./src/utils/image.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/constants.js */ "./src/utils/constants.js"); - - - - - - - - -/** - * Named tuple to indicate the order we are using is (height x width), - * even though the Graphics' industry standard is (width x height). - * @typedef {[height: number, width: number]} HeightWidth - */ - - -/** - * @typedef {object} ImageProcessorResult - * @property {Tensor} pixel_values The pixel values of the batched preprocessed images. - * @property {HeightWidth[]} original_sizes Array of two-dimensional tuples like [[480, 640]]. - * @property {HeightWidth[]} reshaped_input_sizes Array of two-dimensional tuples like [[1000, 1330]]. - */ - - - -/** - * Helper function to constrain a value to be a multiple of a number. - * @param {number} val The value to constrain. - * @param {number} multiple The number to constrain to. - * @param {number} [minVal=0] The minimum value to constrain to. - * @param {number} [maxVal=null] The maximum value to constrain to. - * @returns {number} The constrained value. - * @private - */ -function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) { - const a = val / multiple; - let x = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.bankers_round)(a) * multiple; - - if (maxVal !== null && x > maxVal) { - x = Math.floor(a) * multiple; - } - - if (x < minVal) { - x = Math.ceil(a) * multiple; - } - - return x; -} - -/** - * Rounds the height and width down to the closest multiple of size_divisibility - * @param {[number, number]} size The size of the image - * @param {number} divisor The divisor to use. - * @returns {[number, number]} The rounded size. - */ -function enforce_size_divisibility([width, height], divisor) { - return [ - Math.max(Math.floor(width / divisor), 1) * divisor, - Math.max(Math.floor(height / divisor), 1) * divisor - ]; -} - - -// Helper functions - -/** - * Converts bounding boxes from center format to corners format. - * - * @param {number[]} arr The coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height) - * @returns {number[]} The coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y) - */ -function center_to_corners_format([centerX, centerY, width, height]) { - return [ - centerX - width / 2, - centerY - height / 2, - centerX + width / 2, - centerY + height / 2 - ]; -} - -/** - * Post-processes the outputs of the model (for object detection). - * @param {Object} outputs The outputs of the model that must be post-processed - * @param {Tensor} outputs.logits The logits - * @param {Tensor} outputs.pred_boxes The predicted boxes. - * @param {number} [threshold=0.5] The threshold to use for the scores. - * @param {[number, number][]} [target_sizes=null] The sizes of the original images. - * @param {boolean} [is_zero_shot=false] Whether zero-shot object detection was performed. - * @return {Object[]} An array of objects containing the post-processed outputs. - */ -function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) { - const out_logits = outputs.logits; - const out_bbox = outputs.pred_boxes; - const [batch_size, num_boxes, num_classes] = out_logits.dims; - - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") - } - let toReturn = []; - for (let i = 0; i < batch_size; ++i) { - let target_size = target_sizes !== null ? target_sizes[i] : null; - let info = { - boxes: [], - classes: [], - scores: [] - } - let logits = out_logits[i]; - let bbox = out_bbox[i]; - - for (let j = 0; j < num_boxes; ++j) { - let logit = logits[j]; - - let indices = []; - let probs; - if (is_zero_shot) { - // Get indices of classes with high enough probability - probs = logit.sigmoid().data; - for (let k = 0; k < probs.length; ++k) { - if (probs[k] > threshold) { - indices.push(k); - } - } - - } else { - // Get most probable class - let maxIndex = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logit.data)[1]; - - if (maxIndex === num_classes - 1) { - // This is the background class, skip it - continue; - } - // Compute softmax over classes - probs = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(logit.data); - - if (probs[maxIndex] < threshold) { - continue; - } - indices.push(maxIndex); - } - - for (const index of indices) { - - // Some class has a high enough probability - /** @type {number[]} */ - let box = bbox[j].data; - - // convert to [x0, y0, x1, y1] format - box = center_to_corners_format(box) - if (target_size !== null) { - box = box.map((x, i) => x * target_size[(i + 1) % 2]) - } - - info.boxes.push(box); - info.classes.push(index); - info.scores.push(probs[index]); - } - } - toReturn.push(info); - } - return toReturn; -} - - -/** - * Post-processes the outputs of the model (for semantic segmentation). - * @param {*} outputs Raw outputs of the model. - * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size - * (height, width) of each prediction. If unset, predictions will not be resized. - * @returns {{segmentation: Tensor; labels: number[]}[]} The semantic segmentation maps. - */ -function post_process_semantic_segmentation(outputs, target_sizes = null) { - - const logits = outputs.logits; - const batch_size = logits.dims[0]; - - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") - } - - const toReturn = []; - for (let i = 0; i < batch_size; ++i) { - const target_size = target_sizes !== null ? target_sizes[i] : null; - - let data = logits[i]; - - // 1. If target_size is not null, we need to resize the masks to the target size - if (target_size !== null) { - // resize the masks to the target size - data = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate)(data, target_size, 'bilinear', false); - } - const [height, width] = target_size ?? data.dims.slice(-2); - - const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - 'int32', - new Int32Array(height * width), - [height, width] - ); - - // Buffer to store current largest value - const buffer = data[0].data; - const segmentation_data = segmentation.data; - for (let j = 1; j < data.dims[0]; ++j) { - const row = data[j].data; - for (let k = 0; k < row.length; ++k) { - if (row[k] > buffer[k]) { - buffer[k] = row[k]; - segmentation_data[k] = j; - } - } - } - - // Store which objects have labels - // This is much more efficient that creating a set of the final values - const hasLabel = new Array(data.dims[0]); - for (let j = 0; j < segmentation_data.length; ++j) { - const index = segmentation_data[j]; - hasLabel[index] = index; - } - /** @type {number[]} The unique list of labels that were detected */ - const labels = hasLabel.filter(x => x !== undefined); - - toReturn.push({ segmentation, labels }); - } - return toReturn; -} - - -/** - * Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and `labels`. - * @param {Tensor} class_logits The class logits. - * @param {Tensor} mask_logits The mask logits. - * @param {number} object_mask_threshold A number between 0 and 1 used to binarize the masks. - * @param {number} num_labels The number of labels. - * @returns {[Tensor[], number[], number[]]} The binarized masks, the scores, and the labels. - * @private - */ -function remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) { - - const mask_probs_item = []; - const pred_scores_item = []; - const pred_labels_item = []; - - for (let j = 0; j < class_logits.dims[0]; ++j) { - const cls = class_logits[j]; - const mask = mask_logits[j]; - - const pred_label = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(cls.data)[1]; - if (pred_label === num_labels) { - // Is the background, so we ignore it - continue; - } - - const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(cls.data); - const pred_score = scores[pred_label]; - if (pred_score > object_mask_threshold) { - mask_probs_item.push(mask); - pred_scores_item.push(pred_score); - pred_labels_item.push(pred_label); - } - } - - return [mask_probs_item, pred_scores_item, pred_labels_item]; -} - -/** - * Checks whether the segment is valid or not. - * @param {Int32Array} mask_labels Labels for each pixel in the mask. - * @param {Tensor[]} mask_probs Probabilities for each pixel in the masks. - * @param {number} k The class id of the segment. - * @param {number} mask_threshold The mask threshold. - * @param {number} overlap_mask_area_threshold The overlap mask area threshold. - * @returns {[boolean, number[]]} Whether the segment is valid or not, and the indices of the valid labels. - * @private - */ -function check_segment_validity( - mask_labels, - mask_probs, - k, - mask_threshold = 0.5, - overlap_mask_area_threshold = 0.8 -) { - // mask_k is a 1D array of indices, indicating where the mask is equal to k - const mask_k = []; - let mask_k_area = 0; - let original_area = 0; - - const mask_probs_k_data = mask_probs[k].data; - - // Compute the area of all the stuff in query k - for (let i = 0; i < mask_labels.length; ++i) { - if (mask_labels[i] === k) { - mask_k.push(i); - ++mask_k_area; - } - - if (mask_probs_k_data[i] >= mask_threshold) { - ++original_area; - } - } - let mask_exists = mask_k_area > 0 && original_area > 0; - - // Eliminate disconnected tiny segments - if (mask_exists) { - // Perform additional check - let area_ratio = mask_k_area / original_area; - mask_exists = area_ratio > overlap_mask_area_threshold; - } - - return [mask_exists, mask_k] -} - -/** - * Computes the segments. - * @param {Tensor[]} mask_probs The mask probabilities. - * @param {number[]} pred_scores The predicted scores. - * @param {number[]} pred_labels The predicted labels. - * @param {number} mask_threshold The mask threshold. - * @param {number} overlap_mask_area_threshold The overlap mask area threshold. - * @param {Set} label_ids_to_fuse The label ids to fuse. - * @param {number[]} target_size The target size of the image. - * @returns {[Tensor, Array<{id: number, label_id: number, score: number}>]} The computed segments. - * @private - */ -function compute_segments( - mask_probs, - pred_scores, - pred_labels, - mask_threshold, - overlap_mask_area_threshold, - label_ids_to_fuse = null, - target_size = null, -) { - const [height, width] = target_size ?? mask_probs[0].dims; - - const segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - 'int32', - new Int32Array(height * width), - [height, width] - ); - const segments = []; - - // 1. If target_size is not null, we need to resize the masks to the target size - if (target_size !== null) { - // resize the masks to the target size - for (let i = 0; i < mask_probs.length; ++i) { - mask_probs[i] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate)(mask_probs[i], target_size, 'bilinear', false); - } - } - - // 2. Weigh each mask by its prediction score - // NOTE: `mask_probs` is updated in-place - // - // Temporary storage for the best label/scores for each pixel ([height, width]): - const mask_labels = new Int32Array(mask_probs[0].data.length); - const bestScores = new Float32Array(mask_probs[0].data.length); - - for (let i = 0; i < mask_probs.length; ++i) { - let score = pred_scores[i]; - - const mask_probs_i_data = mask_probs[i].data; - - for (let j = 0; j < mask_probs_i_data.length; ++j) { - mask_probs_i_data[j] *= score - if (mask_probs_i_data[j] > bestScores[j]) { - mask_labels[j] = i; - bestScores[j] = mask_probs_i_data[j]; - } - } - } - - let current_segment_id = 0; - - // let stuff_memory_list = {} - const segmentation_data = segmentation.data; - for (let k = 0; k < pred_labels.length; ++k) { - const pred_class = pred_labels[k]; - - // TODO add `should_fuse` - // let should_fuse = pred_class in label_ids_to_fuse - - // Check if mask exists and large enough to be a segment - const [mask_exists, mask_k] = check_segment_validity( - mask_labels, - mask_probs, - k, - mask_threshold, - overlap_mask_area_threshold - ) - - if (!mask_exists) { - // Nothing to see here - continue; - } - - // TODO - // if (pred_class in stuff_memory_list) { - // current_segment_id = stuff_memory_list[pred_class] - // } else { - // current_segment_id += 1; - // } - ++current_segment_id; - - - // Add current object segment to final segmentation map - for (const index of mask_k) { - segmentation_data[index] = current_segment_id; - } - - segments.push({ - id: current_segment_id, - label_id: pred_class, - // was_fused: should_fuse, TODO - score: pred_scores[k], - }) - - // TODO - // if(should_fuse){ - // stuff_memory_list[pred_class] = current_segment_id - // } - } - - return [segmentation, segments]; -} - -/** - * Rescales the image so that the following conditions are met: - * - * 1. Both dimensions (height and width) are divisible by 'factor'. - * 2. The total number of pixels is within the range ['min_pixels', 'max_pixels']. - * 3. The aspect ratio of the image is maintained as closely as possible. - * - * @param {number} height The height of the image. - * @param {number} width The width of the image. - * @param {number} [factor=28] The factor to use for resizing. - * @param {number} [min_pixels=56*56] The minimum number of pixels. - * @param {number} [max_pixels=14*14*4*1280] The maximum number of pixels. - * @returns {[number, number]} The new height and width of the image. - * @throws {Error} If the height or width is smaller than the factor. - */ -function smart_resize(height, width, factor = 28, min_pixels = 56 * 56, max_pixels = 14 * 14 * 4 * 1280) { - - if (height < factor || width < factor) { - throw new Error(`height:${height} or width:${width} must be larger than factor:${factor}`); - } else if (Math.max(height, width) / Math.min(height, width) > 200) { - throw new Error( - `absolute aspect ratio must be smaller than 200, got ${Math.max(height, width) / Math.min(height, width)}` - ); - } - - let h_bar = Math.round(height / factor) * factor; - let w_bar = Math.round(width / factor) * factor; - - if (h_bar * w_bar > max_pixels) { - const beta = Math.sqrt((height * width) / max_pixels); - h_bar = Math.floor((height / beta) / factor) * factor; - w_bar = Math.floor((width / beta) / factor) * factor; - } else if (h_bar * w_bar < min_pixels) { - const beta = Math.sqrt(min_pixels / (height * width)); - h_bar = Math.ceil((height * beta) / factor) * factor; - w_bar = Math.ceil((width * beta) / factor) * factor; - } - - return [h_bar, w_bar]; -} - - -/** - * Post-process the model output to generate the final panoptic segmentation. - * @param {*} outputs The model output to post process - * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks. - * @param {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. - * @param {number} [overlap_mask_area_threshold=0.8] The overlap mask area threshold to merge or discard small disconnected parts within each binary instance mask. - * @param {Set} [label_ids_to_fuse=null] The labels in this state will have all their instances be fused together. - * @param {[number, number][]} [target_sizes=null] The target sizes to resize the masks to. - * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>} - */ -function post_process_panoptic_segmentation( - outputs, - threshold = 0.5, - mask_threshold = 0.5, - overlap_mask_area_threshold = 0.8, - label_ids_to_fuse = null, - target_sizes = null, -) { - if (label_ids_to_fuse === null) { - console.warn("`label_ids_to_fuse` unset. No instance will be fused.") - label_ids_to_fuse = new Set(); - } - - const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; // [batch_size, num_queries, num_classes+1] - const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; // [batch_size, num_queries, height, width] - - const mask_probs = masks_queries_logits.sigmoid() // [batch_size, num_queries, height, width] - - let [batch_size, num_queries, num_labels] = class_queries_logits.dims; - num_labels -= 1; // Remove last class (background) - - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") - } - - let toReturn = []; - for (let i = 0; i < batch_size; ++i) { - let target_size = target_sizes !== null ? target_sizes[i] : null; - - let class_logits = class_queries_logits[i]; - let mask_logits = mask_probs[i]; - - let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects(class_logits, mask_logits, threshold, num_labels); - - if (pred_labels_item.length === 0) { - // No mask found - let [height, width] = target_size ?? mask_logits.dims.slice(-2); - - let segmentation = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - 'int32', - new Int32Array(height * width).fill(-1), - [height, width] - ) - toReturn.push({ - segmentation: segmentation, - segments_info: [] - }); - continue; - } - - - // Get segmentation map and segment information of batch item - let [segmentation, segments] = compute_segments( - mask_probs_item, - pred_scores_item, - pred_labels_item, - mask_threshold, - overlap_mask_area_threshold, - label_ids_to_fuse, - target_size, - ) - - toReturn.push({ - segmentation: segmentation, - segments_info: segments - }) - } - - return toReturn; -} - - -/** - * Post-processes the outputs of the model (for instance segmentation). - * @param {*} outputs Raw outputs of the model. - * @param {number} [threshold=0.5] The probability score threshold to keep predicted instance masks. - * @param {[number, number][]} [target_sizes=null] List of tuples corresponding to the requested final size - * (height, width) of each prediction. If unset, predictions will not be resized. - * @returns {Array<{ segmentation: Tensor, segments_info: Array<{id: number, label_id: number, score: number}>}>} - */ -function post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) { - throw new Error('`post_process_instance_segmentation` is not yet implemented.'); -} - - -/** - * @typedef {Object} ImageProcessorConfig A configuration object used to create an image processor. - * @property {function} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates. - * @property {number[]} [image_mean] The mean values for image normalization. - * @property {number[]} [image_std] The standard deviation values for image normalization. - * @property {boolean} [do_rescale] Whether to rescale the image pixel values to the [0,1] range. - * @property {number} [rescale_factor] The factor to use for rescaling the image pixel values. - * @property {boolean} [do_normalize] Whether to normalize the image pixel values. - * @property {boolean} [do_resize] Whether to resize the image. - * @property {number} [resample] What method to use for resampling. - * @property {number|Object} [size] The size to resize the image to. - * @property {number|Object} [image_size] The size to resize the image to (same as `size`). - * @property {boolean} [do_flip_channel_order=false] Whether to flip the color channels from RGB to BGR. - * Can be overridden by the `do_flip_channel_order` parameter in the `preprocess` method. - * @property {boolean} [do_center_crop] Whether to center crop the image to the specified `crop_size`. - * Can be overridden by `do_center_crop` in the `preprocess` method. - * @property {boolean} [do_thumbnail] Whether to resize the image using thumbnail method. - * @property {boolean} [keep_aspect_ratio] If `true`, the image is resized to the largest possible size such that the aspect ratio is preserved. - * Can be overidden by `keep_aspect_ratio` in `preprocess`. - * @property {number} [ensure_multiple_of] If `do_resize` is `true`, the image is resized to a size that is a multiple of this value. - * Can be overidden by `ensure_multiple_of` in `preprocess`. - * - * @property {number[]} [mean] The mean values for image normalization (same as `image_mean`). - * @property {number[]} [std] The standard deviation values for image normalization (same as `image_std`). - */ - -class ImageProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - - /** - * Constructs a new `ImageProcessor`. - * @param {ImageProcessorConfig} config The configuration object. - */ - constructor(config) { - super(); - - this.image_mean = config.image_mean ?? config.mean; - this.image_std = config.image_std ?? config.std; - - this.resample = config.resample ?? 2; // 2 => bilinear - this.do_rescale = config.do_rescale ?? true; - this.rescale_factor = config.rescale_factor ?? (1 / 255); - this.do_normalize = config.do_normalize; - - this.do_thumbnail = config.do_thumbnail; - this.size = config.size ?? config.image_size; - this.do_resize = config.do_resize ?? (this.size !== undefined); - // @ts-expect-error TS2339 - this.size_divisibility = config.size_divisibility ?? config.size_divisor; - - this.do_center_crop = config.do_center_crop; - // @ts-expect-error TS2339 - this.crop_size = config.crop_size; - // @ts-expect-error TS2339 - this.do_convert_rgb = config.do_convert_rgb ?? true; - // @ts-expect-error TS2339 - this.do_crop_margin = config.do_crop_margin; - - // @ts-expect-error TS2339 - this.pad_size = config.pad_size; - // @ts-expect-error TS2339 - this.do_pad = config.do_pad; - // @ts-expect-error TS2339 - this.min_pixels = config.min_pixels; - // @ts-expect-error TS2339 - this.max_pixels = config.max_pixels; - - if (this.do_pad && !this.pad_size && this.size && this.size.width !== undefined && this.size.height !== undefined) { - // Should pad, but no pad size specified - // We infer the pad size from the resize size - this.pad_size = this.size - } - - this.do_flip_channel_order = config.do_flip_channel_order ?? false; - - this.config = config; - } - - /** - * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any - * corresponding dimension of the specified size. - * @param {RawImage} image The image to be resized. - * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. - * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. - * @returns {Promise} The resized image. - */ - async thumbnail(image, size, resample = 2) { - const input_height = image.height; - const input_width = image.width; - - const output_height = size.height; - const output_width = size.width; - - // We always resize to the smallest of either the input or output size. - let height = Math.min(input_height, output_height) - let width = Math.min(input_width, output_width) - - if (height === input_height && width === input_width) { - return image; - } - if (input_height > input_width) { - width = Math.floor(input_width * height / input_height); - } else if (input_width > input_height) { - height = Math.floor(input_height * width / input_width); - } - return await image.resize(width, height, { resample }); - } - - - /** - * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). - * @param {RawImage} image The image to be cropped. - * @param {number} gray_threshold Value below which pixels are considered to be gray. - * @returns {Promise} The cropped image. - */ - async crop_margin(image, gray_threshold = 200) { - - const gray_image = image.clone().grayscale(); - - const minValue = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.min)(gray_image.data)[0]; - const maxValue = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(gray_image.data)[0]; - const diff = maxValue - minValue; - - if (diff === 0) { - return image; - } - - const threshold = gray_threshold / 255; - - let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0; - const gray_image_data = gray_image.data; - for (let j = 0; j < gray_image.height; ++j) { - const row = j * gray_image.width; - for (let i = 0; i < gray_image.width; ++i) { - if ((gray_image_data[row + i] - minValue) / diff < threshold) { - // We have a non-zero pixel, so we update the min/max values accordingly - x_min = Math.min(x_min, i); - y_min = Math.min(y_min, j); - x_max = Math.max(x_max, i); - y_max = Math.max(y_max, j); - } - } - } - - image = await image.crop([x_min, y_min, x_max, y_max]); - return image; - } - - /** - * Pad the image by a certain amount. - * @param {Float32Array} pixelData The pixel data to pad. - * @param {number[]} imgDims The dimensions of the image (height, width, channels). - * @param {{width:number; height:number}|number|'square'} padSize The dimensions of the padded image. - * @param {Object} options The options for padding. - * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. - * @param {boolean} [options.center=false] Whether to center the image. - * @param {number|number[]} [options.constant_values=0] The constant value to use for padding. - * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. - */ - pad_image(pixelData, imgDims, padSize, { - mode = 'constant', - center = false, - constant_values = 0, - } = {}) { - const [imageHeight, imageWidth, imageChannels] = imgDims; - - let paddedImageWidth, paddedImageHeight; - if (typeof padSize === 'number') { - paddedImageWidth = padSize; - paddedImageHeight = padSize; - } else if (padSize === 'square') { - paddedImageWidth = paddedImageHeight = Math.max(imageHeight, imageWidth); - } else { - paddedImageWidth = padSize.width; - paddedImageHeight = padSize.height; - } - - // Only add padding if there is a difference in size - if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) { - const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels); - if (Array.isArray(constant_values)) { - // Fill with constant values, cycling through the array - for (let i = 0; i < paddedPixelData.length; ++i) { - paddedPixelData[i] = constant_values[i % imageChannels]; - } - } else if (constant_values !== 0) { - paddedPixelData.fill(constant_values); - } - - const [left, top] = center - ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] - : [0, 0]; - - // Copy the original image into the padded image - for (let i = 0; i < imageHeight; ++i) { - const a = (i + top) * paddedImageWidth; - const b = i * imageWidth; - for (let j = 0; j < imageWidth; ++j) { - const c = (a + j + left) * imageChannels; - const d = (b + j) * imageChannels; - for (let k = 0; k < imageChannels; ++k) { - paddedPixelData[c + k] = pixelData[d + k]; - } - } - } - - if (mode === 'symmetric') { - if (center) { - throw new Error('`center` padding is not supported when `mode` is set to `symmetric`.'); - // TODO: Implement this - } - const h1 = imageHeight - 1; - const w1 = imageWidth - 1; - for (let i = 0; i < paddedImageHeight; ++i) { - const a = i * paddedImageWidth; - const b = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.calculateReflectOffset)(i, h1) * imageWidth; - - for (let j = 0; j < paddedImageWidth; ++j) { - if (i < imageHeight && j < imageWidth) continue; // Do not overwrite original image - const c = (a + j) * imageChannels; - const d = (b + (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.calculateReflectOffset)(j, w1)) * imageChannels; - - // Copy channel-wise - for (let k = 0; k < imageChannels; ++k) { - paddedPixelData[c + k] = pixelData[d + k]; - } - } - } - } - - - // Update pixel data and image dimensions - pixelData = paddedPixelData; - imgDims = [paddedImageHeight, paddedImageWidth, imageChannels] - } - return [pixelData, imgDims]; - } - - /** - * Rescale the image' pixel values by `this.rescale_factor`. - * @param {Float32Array} pixelData The pixel data to rescale. - * @returns {void} - */ - rescale(pixelData) { - for (let i = 0; i < pixelData.length; ++i) { - pixelData[i] = this.rescale_factor * pixelData[i]; - } - } - - /** - * Find the target (width, height) dimension of the output image after - * resizing given the input image and the desired size. - * @param {RawImage} image The image to resize. - * @param {any} size The size to use for resizing the image. - * @returns {[number, number]} The target (width, height) dimension of the output image after resizing. - */ - get_resize_output_image_size(image, size) { - // `size` comes in many forms, so we need to handle them all here: - // 1. `size` is an integer, in which case we resize the image to be a square - - const [srcWidth, srcHeight] = image.size; - - let shortest_edge; - let longest_edge; - - if (this.do_thumbnail) { - // NOTE: custom logic for `Donut` models - const { height, width } = size; - shortest_edge = Math.min(height, width) - } - // Support both formats for backwards compatibility - else if (Number.isInteger(size)) { - shortest_edge = size; - // @ts-expect-error TS2339 - longest_edge = this.config.max_size ?? shortest_edge; - - } else if (size !== undefined) { - // Extract known properties from `size` - shortest_edge = size.shortest_edge; - longest_edge = size.longest_edge; - } - - // If `longest_edge` and `shortest_edge` are set, maintain aspect ratio and resize to `shortest_edge` - // while keeping the largest dimension <= `longest_edge` - if (shortest_edge !== undefined || longest_edge !== undefined) { - // http://opensourcehacker.com/2011/12/01/calculate-aspect-ratio-conserving-resize-for-images-in-javascript/ - // Try resize so that shortest edge is `shortest_edge` (target) - const shortResizeFactor = shortest_edge === undefined - ? 1 // If `shortest_edge` is not set, don't upscale - : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight); - - const newWidth = srcWidth * shortResizeFactor; - const newHeight = srcHeight * shortResizeFactor; - - // The new width and height might be greater than `longest_edge`, so - // we downscale again to ensure the largest dimension is `longest_edge` - const longResizeFactor = longest_edge === undefined - ? 1 // If `longest_edge` is not set, don't downscale - : Math.min(longest_edge / newWidth, longest_edge / newHeight); - - // To avoid certain floating point precision issues, we round to 2 decimal places - let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2))); - let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2))); - - if (this.size_divisibility !== undefined) { - [finalWidth, finalHeight] = enforce_size_divisibility([finalWidth, finalHeight], this.size_divisibility) - } - return [finalWidth, finalHeight]; - - } else if (size !== undefined && size.width !== undefined && size.height !== undefined) { - // If `width` and `height` are set, resize to those dimensions - - let newWidth = size.width; - let newHeight = size.height; - - // Custom for DPT models - if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) { - - // determine new height and width - let scale_height = newHeight / srcHeight; - let scale_width = newWidth / srcWidth; - - // scale as little as possible - if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) { - // fit width - scale_height = scale_width; - } else { - // fit height - scale_width = scale_height; - } - - newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of); - newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of); - } - - return [newWidth, newHeight]; - - } else if (this.size_divisibility !== undefined) { - return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility); - } else if (this.min_pixels !== undefined && this.max_pixels !== undefined) { - // Custom resize logic for Qwen2-VL models - // @ts-expect-error TS2339 - const factor = this.config.patch_size * this.config.merge_size; - return smart_resize(srcHeight, srcWidth, factor, this.min_pixels, this.max_pixels); - } else { - throw new Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}`); - } - } - - /** - * Resizes the image. - * @param {RawImage} image The image to resize. - * @returns {Promise} The resized image. - */ - async resize(image) { - const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size); - return await image.resize(newWidth, newHeight, { - // @ts-expect-error TS2322 - resample: this.resample, - }); - } - - /** - * @typedef {object} PreprocessedImage - * @property {HeightWidth} original_size The original size of the image. - * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. - * @property {Tensor} pixel_values The pixel values of the preprocessed image. - */ - - /** - * Preprocesses the given image. - * - * @param {RawImage} image The image to preprocess. - * @param {Object} overrides The overrides for the preprocessing options. - * @returns {Promise} The preprocessed image. - */ - async preprocess(image, { - do_normalize = null, - do_pad = null, - do_convert_rgb = null, - do_convert_grayscale = null, - do_flip_channel_order = null, - } = {}) { - if (this.do_crop_margin) { - // NOTE: Specific to nougat processors. This is done before resizing, - // and can be interpreted as a pre-preprocessing step. - image = await this.crop_margin(image); - } - - const [srcWidth, srcHeight] = image.size; // original image size - - // Convert image to RGB if specified in config. - if (do_convert_rgb ?? this.do_convert_rgb) { - image = image.rgb(); - } else if (do_convert_grayscale) { - image = image.grayscale(); - } - - // TODO: - // For efficiency reasons, it might be best to merge the resize and center crop operations into one. - - // Resize all images - if (this.do_resize) { - image = await this.resize(image); - } - - // Resize the image using thumbnail method. - if (this.do_thumbnail) { - // @ts-expect-error TS2345 - image = await this.thumbnail(image, this.size, this.resample); - } - - if (this.do_center_crop) { - - let crop_width; - let crop_height; - if (Number.isInteger(this.crop_size)) { - crop_width = this.crop_size; - crop_height = this.crop_size; - } else { - crop_width = this.crop_size.width; - crop_height = this.crop_size.height; - } - - image = await image.center_crop(crop_width, crop_height); - } - - /** @type {HeightWidth} */ - const reshaped_input_size = [image.height, image.width]; - - // NOTE: All pixel-level manipulation (i.e., modifying `pixelData`) - // occurs with data in the hwc format (height, width, channels), - // to emulate the behavior of the original Python code (w/ numpy). - /** @type {Float32Array} */ - let pixelData = Float32Array.from(image.data); - let imgDims = [image.height, image.width, image.channels]; - - if (this.do_rescale) { - this.rescale(pixelData); - } - - if (do_normalize ?? this.do_normalize) { - let image_mean = this.image_mean; - if (!Array.isArray(this.image_mean)) { - image_mean = new Array(image.channels).fill(image_mean); - } - - let image_std = this.image_std; - if (!Array.isArray(this.image_std)) { - image_std = new Array(image.channels).fill(image_mean); - } - - if (image_mean.length !== image.channels || image_std.length !== image.channels) { - throw new Error(`When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).`); - } - - for (let i = 0; i < pixelData.length; i += image.channels) { - for (let j = 0; j < image.channels; ++j) { - pixelData[i + j] = (pixelData[i + j] - image_mean[j]) / image_std[j]; - } - } - } - - // do padding after rescaling/normalizing - if (do_pad ?? this.do_pad) { - if (this.pad_size) { - const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size); - [pixelData, imgDims] = padded; // Update pixel data and image dimensions - } else if (this.size_divisibility) { - const [paddedWidth, paddedHeight] = enforce_size_divisibility([imgDims[1], imgDims[0]], this.size_divisibility); - [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight }); - } - } - - if (do_flip_channel_order ?? this.do_flip_channel_order) { - if (imgDims[2] !== 3) { - throw new Error('Flipping channel order is only supported for RGB images.'); - } - // Convert RGB to BGR - for (let i = 0; i < pixelData.length; i += 3) { - const temp = pixelData[i]; - pixelData[i] = pixelData[i + 2]; - pixelData[i + 2] = temp; - } - } - - const pixel_values = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('float32', pixelData, imgDims) - .permute(2, 0, 1); // convert to channel dimension format (hwc -> chw) - - return { - original_size: [srcHeight, srcWidth], - reshaped_input_size: reshaped_input_size, - pixel_values, - } - } - - /** - * Calls the feature extraction process on an array of images, - * preprocesses each image, and concatenates the resulting - * features into a single Tensor. - * @param {RawImage[]} images The image(s) to extract features from. - * @param {...any} args Additional arguments. - * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. - */ - async _call(images, ...args) { - if (!Array.isArray(images)) { - images = [images]; - } - /** @type {PreprocessedImage[]} */ - const imageData = await Promise.all(images.map(x => this.preprocess(x))); - - // Stack pixel values - const pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(imageData.map(x => x.pixel_values), 0); - - return { - pixel_values, - - // Original sizes of images - original_sizes: imageData.map(x => x.original_size), - - // Reshaped sizes of images, before padding or cropping - reshaped_input_sizes: imageData.map(x => x.reshaped_input_size), - } - } - - - /** - * Instantiate one of the processor classes of the library from a pretrained model. - * - * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) - * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. - * @param {import('../utils/hub.js').PretrainedOptions} options Additional options for loading the processor. - * - * @returns {Promise} A new instance of the Processor class. - */ - static async from_pretrained(pretrained_model_name_or_path, options={}) { - const preprocessorConfig = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__.IMAGE_PROCESSOR_NAME, true, options); - return new this(preprocessorConfig); - } -} - - -/***/ }), - -/***/ "./src/base/processing_utils.js": -/*!**************************************!*\ - !*** ./src/base/processing_utils.js ***! - \**************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Processor: () => (/* binding */ Processor) -/* harmony export */ }); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/constants.js */ "./src/utils/constants.js"); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/hub.js */ "./src/utils/hub.js"); - -/** - * @file Processors are used to prepare inputs (e.g., text, image or audio) for a model. - * - * **Example:** Using a `WhisperProcessor` to prepare an audio input for a model. - * ```javascript - * import { AutoProcessor, read_audio } from '@huggingface/transformers'; - * - * const processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en'); - * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000); - * const { input_features } = await processor(audio); - * // Tensor { - * // data: Float32Array(240000) [0.4752984642982483, 0.5597258806228638, 0.56434166431427, ...], - * // dims: [1, 80, 3000], - * // type: 'float32', - * // size: 240000, - * // } - * ``` - * - * @module processors - */ - - - - -/** - * @typedef {Object} ProcessorProperties Additional processor-specific properties. - * @typedef {import('../utils/hub.js').PretrainedOptions & ProcessorProperties} PretrainedProcessorOptions - * @typedef {import('../tokenizers.js').PreTrainedTokenizer} PreTrainedTokenizer - */ - - -/** - * Represents a Processor that extracts features from an input. - */ -class Processor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_1__.Callable { - static classes = [ - 'image_processor_class', - 'tokenizer_class', - 'feature_extractor_class', - ] - static uses_processor_config = false; - static uses_chat_template_file = false; - - /** - * Creates a new Processor with the given components - * @param {Object} config - * @param {Record} components - * @param {string} chat_template - */ - constructor(config, components, chat_template) { - super(); - this.config = config; - this.components = components; - this.chat_template = chat_template; - } - - /** - * @returns {import('./image_processors_utils.js').ImageProcessor|undefined} The image processor of the processor, if it exists. - */ - get image_processor() { - return this.components.image_processor; - } - - /** - * @returns {PreTrainedTokenizer|undefined} The tokenizer of the processor, if it exists. - */ - get tokenizer() { - return this.components.tokenizer; - } - - /** - * @returns {import('./feature_extraction_utils.js').FeatureExtractor|undefined} The feature extractor of the processor, if it exists. - */ - get feature_extractor() { - return this.components.feature_extractor; - } - - /** - * @param {Parameters[0]} messages - * @param {Parameters[1]} options - * @returns {ReturnType} - */ - apply_chat_template(messages, options = {}) { - if (!this.tokenizer) { - throw new Error('Unable to apply chat template without a tokenizer.'); - } - return this.tokenizer.apply_chat_template(messages, { - tokenize: false, // default to false - chat_template: this.chat_template ?? undefined, - ...options, - }); - } - - /** - * @param {Parameters} args - * @returns {ReturnType} - */ - batch_decode(...args) { - if (!this.tokenizer) { - throw new Error('Unable to decode without a tokenizer.'); - } - return this.tokenizer.batch_decode(...args); - } - - /** - * @param {Parameters} args - * @returns {ReturnType} - */ - decode(...args) { - if (!this.tokenizer) { - throw new Error('Unable to decode without a tokenizer.'); - } - return this.tokenizer.decode(...args); - } - - - /** - * Calls the feature_extractor function with the given input. - * @param {any} input The input to extract features from. - * @param {...any} args Additional arguments. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(input, ...args) { - for (const item of [this.image_processor, this.feature_extractor, this.tokenizer]) { - if (item) { - return item(input, ...args); - } - } - throw new Error('No image processor, feature extractor, or tokenizer found.'); - } - - - /** - * Instantiate one of the processor classes of the library from a pretrained model. - * - * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) - * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. - * @param {PretrainedProcessorOptions} options Additional options for loading the processor. - * - * @returns {Promise} A new instance of the Processor class. - */ - static async from_pretrained(pretrained_model_name_or_path, options={}) { - - const [config, components, chat_template] = await Promise.all([ - // TODO: - this.uses_processor_config - ? (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.PROCESSOR_NAME, true, options) - : {}, - Promise.all( - this.classes - .filter((cls) => cls in this) - .map(async (cls) => { - const component = await this[cls].from_pretrained(pretrained_model_name_or_path, options); - return [cls.replace(/_class$/, ''), component]; - }) - ).then(Object.fromEntries), - this.uses_chat_template_file - ? (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelText)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.CHAT_TEMPLATE_NAME, true, options) - : null, - ]); - - return new this(config, components, chat_template); - } -} - - -/***/ }), - -/***/ "./src/configs.js": -/*!************************!*\ - !*** ./src/configs.js ***! - \************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AutoConfig: () => (/* binding */ AutoConfig), -/* harmony export */ PretrainedConfig: () => (/* binding */ PretrainedConfig), -/* harmony export */ getCacheShapes: () => (/* binding */ getCacheShapes) -/* harmony export */ }); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js"); - -/** - * @file Helper module for using model configs. For more information, see the corresponding - * [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig). - * - * **Example:** Load an `AutoConfig`. - * - * ```javascript - * import { AutoConfig } from '@huggingface/transformers'; - * const config = await AutoConfig.from_pretrained('bert-base-uncased'); - * console.log(config); - * // PretrainedConfig { - * // "model_type": "bert", - * // "is_encoder_decoder": false, - * // "architectures": [ - * // "BertForMaskedLM" - * // ], - * // "vocab_size": 30522 - * // "num_attention_heads": 12, - * // "num_hidden_layers": 12, - * // "hidden_size": 768, - * // "max_position_embeddings": 512, - * // ... - * // } - * ``` - * - * @module configs - */ - - - - -/** - * @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions - */ - -/** - * @typedef {import('./utils/core.js').ProgressCallback} ProgressCallback - */ - -/** - * @typedef {import('./utils/core.js').ProgressInfo} ProgressInfo - */ - -/** - * Loads a config from the specified path. - * @param {string} pretrained_model_name_or_path The path to the config directory. - * @param {PretrainedOptions} options Additional options for loading the config. - * @returns {Promise} A promise that resolves with information about the loaded config. - */ -async function loadConfig(pretrained_model_name_or_path, options) { - return await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, 'config.json', true, options); -} - -/** - * - * @param {PretrainedConfig} config - * @returns {Object} The normalized configuration. - */ -function getNormalizedConfig(config) { - const mapping = {}; - - let init_normalized_config = {}; - switch (config.model_type) { - // Sub-configs - case 'llava': - case 'paligemma': - case 'gemma3': - case 'florence2': - case 'llava_onevision': - case 'idefics3': - case 'ultravox': - case 'voxtral': - case 'smolvlm': - case 'gemma3n': - // @ts-expect-error TS2339 - init_normalized_config = getNormalizedConfig(config.text_config); - break; - case 'moondream1': - // @ts-expect-error TS2339 - init_normalized_config = getNormalizedConfig(config.phi_config); - break; - case 'musicgen': - // @ts-expect-error TS2339 - init_normalized_config = getNormalizedConfig(config.decoder); - break; - case 'multi_modality': - // @ts-expect-error TS2339 - init_normalized_config = getNormalizedConfig(config.language_config); - break; - - // Decoder-only models - case 'gpt2': - case 'gptj': - case 'jais': - case 'codegen': - case 'gpt_bigcode': - mapping['num_heads'] = 'n_head'; - mapping['num_layers'] = 'n_layer'; - mapping['hidden_size'] = 'n_embd'; - break; - case 'gpt_neox': - case 'stablelm': - case 'opt': - case 'falcon': - case 'modernbert-decoder': - mapping['num_heads'] = 'num_attention_heads'; - mapping['num_layers'] = 'num_hidden_layers'; - mapping['hidden_size'] = 'hidden_size'; - break; - case 'llama': - case 'arcee': - case 'lfm2': - case 'smollm3': - case 'olmo': - case 'olmo2': - case 'mobilellm': - case 'granite': - case 'cohere': - case 'mistral': - case 'starcoder2': - case 'qwen2': - case 'qwen2_vl': - case 'phi': - case 'phi3': - case 'phi3_v': - case 'llava_qwen2': - mapping['num_heads'] = 'num_key_value_heads'; - mapping['num_layers'] = 'num_hidden_layers'; - mapping['hidden_size'] = 'hidden_size'; - mapping['num_attention_heads'] = 'num_attention_heads'; - mapping['dim_kv'] = 'head_dim'; - break; - case 'qwen3': - case 'gemma': - case 'gemma2': - case 'gemma3_text': - case 'gemma3n_text': - case 'glm': - case 'helium': - case 'ernie4_5': - mapping['num_heads'] = 'num_key_value_heads'; - mapping['num_layers'] = 'num_hidden_layers'; - mapping['dim_kv'] = 'head_dim'; - break; - case 'openelm': - mapping['num_heads'] = 'num_kv_heads'; - mapping['num_layers'] = 'num_transformer_layers'; - mapping['dim_kv'] = 'head_dim'; - break; - case 'gpt_neo': - case 'donut-swin': - mapping['num_heads'] = 'num_heads'; - mapping['num_layers'] = 'num_layers'; - mapping['hidden_size'] = 'hidden_size'; - break; - case 'bloom': - mapping['num_heads'] = 'n_head'; - mapping['num_layers'] = 'n_layer'; - mapping['hidden_size'] = 'hidden_size'; - break; - case 'mpt': - mapping['num_heads'] = 'n_heads'; - mapping['num_layers'] = 'n_layers'; - mapping['hidden_size'] = 'd_model'; - break; - case 'exaone': - mapping['num_heads'] = 'num_key_value_heads'; - mapping['num_layers'] = 'num_layers'; - mapping['dim_kv'] = 'head_dim'; - mapping['num_attention_heads'] = 'num_attention_heads'; - break; - - // Encoder-decoder models - case 't5': - case 'mt5': - case 'longt5': - mapping['num_decoder_layers'] = 'num_decoder_layers'; - mapping['num_decoder_heads'] = 'num_heads'; - mapping['decoder_dim_kv'] = 'd_kv'; - mapping['num_encoder_layers'] = 'num_layers'; - mapping['num_encoder_heads'] = 'num_heads'; - mapping['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': - mapping['num_decoder_layers'] = 'decoder_layers'; - mapping['num_decoder_heads'] = 'decoder_attention_heads'; - mapping['decoder_hidden_size'] = 'd_model'; - mapping['num_encoder_layers'] = 'encoder_layers'; - mapping['num_encoder_heads'] = 'encoder_attention_heads'; - mapping['encoder_hidden_size'] = 'd_model'; - break; - case 'speecht5': - mapping['num_decoder_layers'] = 'decoder_layers'; - mapping['num_decoder_heads'] = 'decoder_attention_heads'; - mapping['decoder_hidden_size'] = 'hidden_size'; - mapping['num_encoder_layers'] = 'encoder_layers'; - mapping['num_encoder_heads'] = 'encoder_attention_heads'; - mapping['encoder_hidden_size'] = 'hidden_size'; - break; - case 'trocr': - mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'decoder_layers'; - mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'decoder_attention_heads'; - mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'd_model'; - break; - case 'musicgen_decoder': - mapping['num_encoder_layers'] = mapping['num_decoder_layers'] = 'num_hidden_layers'; - mapping['num_encoder_heads'] = mapping['num_decoder_heads'] = 'num_attention_heads'; - mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'hidden_size'; - break; - case 'moonshine': - mapping['num_decoder_layers'] = 'decoder_num_hidden_layers'; - mapping['num_decoder_heads'] = 'decoder_num_key_value_heads'; - mapping['num_encoder_layers'] = 'encoder_num_hidden_layers'; - mapping['num_encoder_heads'] = 'encoder_num_key_value_heads'; - mapping['encoder_hidden_size'] = mapping['decoder_hidden_size'] = 'hidden_size'; - break; - case 'vision-encoder-decoder': - // @ts-expect-error TS2339 - const decoderConfig = getNormalizedConfig(config.decoder); - - const add_encoder_pkv = 'num_decoder_layers' in decoderConfig; - const result = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, ['model_type', 'is_encoder_decoder']); - if (add_encoder_pkv) { - // Decoder is part of an encoder-decoder model - result.num_decoder_layers = decoderConfig.num_decoder_layers; - result.num_decoder_heads = decoderConfig.num_decoder_heads; - result.decoder_hidden_size = decoderConfig.decoder_hidden_size; - - result.num_encoder_layers = decoderConfig.num_encoder_layers; - result.num_encoder_heads = decoderConfig.num_encoder_heads; - result.encoder_hidden_size = decoderConfig.encoder_hidden_size; - } else { - // Decoder is a decoder-only model - result.num_layers = decoderConfig.num_layers; - result.num_heads = decoderConfig.num_heads; - result.hidden_size = decoderConfig.hidden_size; - } - return result; - - } - - // NOTE: If `num_attention_heads` is not set, it is assumed to be equal to `num_heads` - const normalized_config = { - ...init_normalized_config, - ...(0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, ['model_type', 'multi_query', 'is_encoder_decoder']), - }; - for (const key in mapping) { - normalized_config[key] = config[mapping[key]]; - } - return normalized_config; -} - -/** - * - * @param {PretrainedConfig} config - * @returns {Record} - */ -function getCacheShapes(config, options) { - if (config.model_type === 'lfm2') { - const pkv_prefix = options?.prefix ?? 'past_key_values'; - const conv_prefix = pkv_prefix === 'present' ? 'present' : 'past'; - - // Custom caching mechanism for LFM2 - /** @type {Record} */ - const cache_values = {}; - // @ts-expect-error TS2339 - const { layer_types, num_attention_heads, num_key_value_heads, hidden_size, conv_L_cache } = config; - const head_dim = hidden_size / num_attention_heads; - const batch_size = options?.batch_size ?? 1; - for (let i = 0; i < layer_types.length; ++i) { - if (layer_types[i] === 'full_attention') { - for (const kv of ['key', 'value']) { - cache_values[`${pkv_prefix}.${i}.${kv}`] = [batch_size, num_key_value_heads, 0, head_dim]; - } - } else if (layer_types[i] === 'conv') { - cache_values[`${conv_prefix}_conv.${i}`] = [batch_size, hidden_size, conv_L_cache]; - } else { - throw new Error(`Unsupported layer type: ${layer_types[i]}`); - } - } - return cache_values; - } - return getKeyValueShapes(config, options); -} - -/** @type {typeof getKeyValueShapes} */ -function getKeyValueShapes(config, { - prefix = 'past_key_values', - batch_size = 1, -} = {}) { - /** @type {Record} */ - const decoderFeeds = {}; - const normalized_config = config.normalized_config; - - if (normalized_config.is_encoder_decoder && ( - 'num_encoder_heads' in normalized_config && 'num_decoder_heads' in normalized_config - )) { - const encoder_dim_kv = normalized_config.encoder_dim_kv ?? ( - normalized_config.encoder_hidden_size / normalized_config.num_encoder_heads - ); - const decoder_dim_kv = normalized_config.decoder_dim_kv ?? ( - normalized_config.decoder_hidden_size / normalized_config.num_decoder_heads - ); - - const encoder_dims = [batch_size, normalized_config.num_encoder_heads, 0, encoder_dim_kv]; - const decoder_dims = [batch_size, normalized_config.num_decoder_heads, 0, decoder_dim_kv]; - for (let i = 0; i < normalized_config.num_decoder_layers; ++i) { - decoderFeeds[`${prefix}.${i}.encoder.key`] = encoder_dims; - decoderFeeds[`${prefix}.${i}.encoder.value`] = encoder_dims; - decoderFeeds[`${prefix}.${i}.decoder.key`] = decoder_dims; - decoderFeeds[`${prefix}.${i}.decoder.value`] = decoder_dims; - } - } else { // Decoders - const num_heads = normalized_config.num_heads; - const num_layers = normalized_config.num_layers; - const dim_kv = normalized_config.dim_kv ?? ( - normalized_config.hidden_size / - (normalized_config.num_attention_heads ?? num_heads) - ); - - if (normalized_config.model_type === 'falcon') { - // NOTE: Custom implementation for Falcon - const dims = [batch_size * num_heads, 0, dim_kv] - for (let i = 0; i < num_layers; ++i) { - decoderFeeds[`${prefix}.${i}.key`] = dims; - decoderFeeds[`${prefix}.${i}.value`] = dims; - } - } else if (normalized_config.multi_query) { // e.g., for `gpt_bigcode` - const dims = [batch_size * num_heads, 0, 2 * dim_kv] - - for (let i = 0; i < num_layers; ++i) { - decoderFeeds[`${prefix}.${i}.key_value`] = dims; - } - } else if (normalized_config.model_type === 'bloom') { - // NOTE: Custom implementation for Bloom - - const keyDims = [batch_size * num_heads, dim_kv, 0] // [batch_size x num_heads,64,past_sequence_length] - const valueDims = [batch_size * num_heads, 0, dim_kv] // [batch_size x num_heads,past_sequence_length,64] - for (let i = 0; i < num_layers; ++i) { - decoderFeeds[`${prefix}.${i}.key`] = keyDims; - decoderFeeds[`${prefix}.${i}.value`] = valueDims; - } - } else if (normalized_config.model_type === 'openelm') { - for (let i = 0; i < num_layers; ++i) { - const dims = [batch_size, num_heads[i], 0, dim_kv] - - decoderFeeds[`${prefix}.${i}.key`] = dims; - decoderFeeds[`${prefix}.${i}.value`] = dims; - } - } else { // Decoder-only - const dims = [batch_size, num_heads, 0, dim_kv] - for (let i = 0; i < num_layers; ++i) { - decoderFeeds[`${prefix}.${i}.key`] = dims; - decoderFeeds[`${prefix}.${i}.value`] = dims; - } - } - } - - return decoderFeeds; -} -/** - * Base class for all configuration classes. For more information, see the corresponding - * [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig). - */ -class PretrainedConfig { - // NOTE: Typo in original - - /** @type {string|null} */ - model_type = null; - - /** @type {boolean} */ - is_encoder_decoder = false; - - /** @type {number} */ - max_position_embeddings; - - /** @type {TransformersJSConfig} */ - 'transformers.js_config'; - - /** - * Create a new PreTrainedTokenizer instance. - * @param {Object} configJSON The JSON of the config. - */ - constructor(configJSON) { - Object.assign(this, configJSON); - this.normalized_config = getNormalizedConfig(this); - } - - /** - * Loads a pre-trained config from the given `pretrained_model_name_or_path`. - * - * @param {string} pretrained_model_name_or_path The path to the pre-trained config. - * @param {PretrainedOptions} options Additional options for loading the config. - * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. - * - * @returns {Promise} A new instance of the `PretrainedConfig` class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = 'main', - } = {}) { - if (config && !(config instanceof PretrainedConfig)) { - config = new PretrainedConfig(config); - } - - const data = config ?? await loadConfig(pretrained_model_name_or_path, { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - }) - return new this(data); - } -} - -/** - * Helper class which is used to instantiate pretrained configs with the `from_pretrained` function. - * - * @example - * const config = await AutoConfig.from_pretrained('Xenova/bert-base-uncased'); - */ -class AutoConfig { - /** @type {typeof PretrainedConfig.from_pretrained} */ - static async from_pretrained(...args) { - return PretrainedConfig.from_pretrained(...args); - } -} - -/** - * Transformers.js-specific configuration, possibly present in config.json under the key `transformers.js_config`. - * @typedef {Object} TransformersJSConfig - * @property {Record} [device_config] Device-specific configurations. - * @property {import('./utils/tensor.js').DataType|Record} [kv_cache_dtype] The data type of the key-value cache. - * @property {Record} [free_dimension_overrides] Override the free dimensions of the model. - * See https://onnxruntime.ai/docs/tutorials/web/env-flags-and-session-options.html#freedimensionoverrides - * for more information. - * @property {import('./utils/devices.js').DeviceType} [device] The default device to use for the model. - * @property {import('./utils/dtypes.js').DataType|Record} [dtype] The default data type to use for the model. - * @property {import('./utils/hub.js').ExternalData|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size). - */ - -/** - * Device-specific configuration options. - * @typedef {Omit} DeviceConfig - */ - - -/***/ }), - -/***/ "./src/env.js": -/*!********************!*\ - !*** ./src/env.js ***! - \********************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ apis: () => (/* binding */ apis), -/* harmony export */ env: () => (/* binding */ env) -/* harmony export */ }); -/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! node:fs */ "?db59"); -/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! node:path */ "?383f"); -/* harmony import */ var node_url__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! node:url */ "?fa4b"); -/** - * @file Module used to configure Transformers.js. - * - * **Example:** Disable remote models. - * ```javascript - * import { env } from '@huggingface/transformers'; - * env.allowRemoteModels = false; - * ``` - * - * **Example:** Set local model path. - * ```javascript - * import { env } from '@huggingface/transformers'; - * env.localModelPath = '/path/to/local/models/'; - * ``` - * - * **Example:** Set cache directory. - * ```javascript - * import { env } from '@huggingface/transformers'; - * env.cacheDir = '/path/to/cache/directory/'; - * ``` - * - * @module env - */ - - - - - -const VERSION = '3.7.2'; - -// Check if various APIs are available (depends on environment) -const IS_BROWSER_ENV = typeof window !== "undefined" && typeof window.document !== "undefined"; -const IS_WEBWORKER_ENV = typeof self !== "undefined" && (['DedicatedWorkerGlobalScope', 'ServiceWorkerGlobalScope', 'SharedWorkerGlobalScope'].includes(self.constructor?.name)); -const IS_WEB_CACHE_AVAILABLE = typeof self !== "undefined" && 'caches' in self; -const IS_WEBGPU_AVAILABLE = typeof navigator !== 'undefined' && 'gpu' in navigator; -const IS_WEBNN_AVAILABLE = typeof navigator !== 'undefined' && 'ml' in navigator; - -const IS_PROCESS_AVAILABLE = typeof process !== 'undefined'; -const IS_NODE_ENV = IS_PROCESS_AVAILABLE && process?.release?.name === 'node'; -const IS_FS_AVAILABLE = !isEmpty(node_fs__WEBPACK_IMPORTED_MODULE_0__); -const IS_PATH_AVAILABLE = !isEmpty(node_path__WEBPACK_IMPORTED_MODULE_1__); - -// Runtime detection -const IS_DENO_RUNTIME = typeof globalThis.Deno !== 'undefined'; -const IS_BUN_RUNTIME = typeof globalThis.Bun !== 'undefined'; - -/** - * A read-only object containing information about the APIs available in the current environment. - */ -const apis = Object.freeze({ - /** Whether we are running in a browser environment (and not a web worker) */ - IS_BROWSER_ENV, - - /** Whether we are running in a web worker environment */ - IS_WEBWORKER_ENV, - - /** Whether the Cache API is available */ - IS_WEB_CACHE_AVAILABLE, - - /** Whether the WebGPU API is available */ - IS_WEBGPU_AVAILABLE, - - /** Whether the WebNN API is available */ - IS_WEBNN_AVAILABLE, - - /** Whether the Node.js process API is available */ - IS_PROCESS_AVAILABLE, - - /** Whether we are running in a Node.js-like environment (node, deno, bun) */ - IS_NODE_ENV, - - /** Whether the filesystem API is available */ - IS_FS_AVAILABLE, - - /** Whether the path API is available */ - IS_PATH_AVAILABLE, -}); - -const RUNNING_LOCALLY = IS_FS_AVAILABLE && IS_PATH_AVAILABLE; - -let dirname__ = './'; -if (RUNNING_LOCALLY) { - // NOTE: We wrap `import.meta` in a call to `Object` to prevent Webpack from trying to bundle it in CommonJS. - // Although we get the warning: "Accessing import.meta directly is unsupported (only property access or destructuring is supported)", - // it is safe to ignore since the bundled value (`{}`) isn't used for CommonJS environments (we use __dirname instead). - const _import_meta_url = Object(import.meta).url; - - if (_import_meta_url) { - dirname__ = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(node_url__WEBPACK_IMPORTED_MODULE_2__.fileURLToPath(_import_meta_url))) // ESM - } else if (typeof __dirname !== 'undefined') { - dirname__ = node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(__dirname) // CommonJS - } -} - -// Only used for environments with access to file system -const DEFAULT_CACHE_DIR = RUNNING_LOCALLY - ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(dirname__, '/.cache/') - : null; - -// Set local model path, based on available APIs -const DEFAULT_LOCAL_MODEL_PATH = '/models/'; -const localModelPath = RUNNING_LOCALLY - ? node_path__WEBPACK_IMPORTED_MODULE_1__.join(dirname__, DEFAULT_LOCAL_MODEL_PATH) - : DEFAULT_LOCAL_MODEL_PATH; - -/** - * Global variable given visible to users to control execution. This provides users a simple way to configure Transformers.js. - * @typedef {Object} TransformersEnvironment - * @property {string} version This version of Transformers.js. - * @property {{onnx: Partial}} backends Expose environment variables of different backends, - * allowing users to set these variables if they want to. - * @property {boolean} allowRemoteModels Whether to allow loading of remote files, defaults to `true`. - * If set to `false`, it will have the same effect as setting `local_files_only=true` when loading pipelines, models, tokenizers, processors, etc. - * @property {string} remoteHost Host URL to load models from. Defaults to the Hugging Face Hub. - * @property {string} remotePathTemplate Path template to fill in and append to `remoteHost` when loading models. - * @property {boolean} allowLocalModels Whether to allow loading of local files, defaults to `false` if running in-browser, and `true` otherwise. - * If set to `false`, it will skip the local file check and try to load the model from the remote host. - * @property {string} localModelPath Path to load local models from. Defaults to `/models/`. - * @property {boolean} useFS Whether to use the file system to load files. By default, it is `true` if available. - * @property {boolean} useBrowserCache Whether to use Cache API to cache models. By default, it is `true` if available. - * @property {boolean} useFSCache Whether to use the file system to cache files. By default, it is `true` if available. - * @property {string} cacheDir The directory to use for caching files with the file system. By default, it is `./.cache`. - * @property {boolean} useCustomCache Whether to use a custom cache system (defined by `customCache`), defaults to `false`. - * @property {Object} customCache The custom cache to use. Defaults to `null`. Note: this 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. - * If you wish, you may also return a `Promise` from the `match` function if you'd like to use a file path instead of `Promise`. - */ - -/** @type {TransformersEnvironment} */ -const env = { - version: VERSION, - - /////////////////// Backends settings /////////////////// - // NOTE: These will be populated later by the backends themselves. - backends: { - // onnxruntime-web/onnxruntime-node - onnx: {}, - }, - - /////////////////// Model settings /////////////////// - allowRemoteModels: true, - remoteHost: 'https://huggingface.co/', - remotePathTemplate: '{model}/resolve/{revision}/', - - allowLocalModels: !(IS_BROWSER_ENV || IS_WEBWORKER_ENV), - localModelPath: localModelPath, - useFS: IS_FS_AVAILABLE, - - /////////////////// Cache settings /////////////////// - useBrowserCache: IS_WEB_CACHE_AVAILABLE && !IS_DENO_RUNTIME, - - useFSCache: IS_FS_AVAILABLE, - cacheDir: DEFAULT_CACHE_DIR, - - useCustomCache: false, - customCache: null, - ////////////////////////////////////////////////////// -} - - -/** - * @param {Object} obj - * @private - */ -function isEmpty(obj) { - return Object.keys(obj).length === 0; -} - - -/***/ }), - -/***/ "./src/generation/configuration_utils.js": -/*!***********************************************!*\ - !*** ./src/generation/configuration_utils.js ***! - \***********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ GenerationConfig: () => (/* binding */ GenerationConfig) -/* harmony export */ }); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/core.js */ "./src/utils/core.js"); - -/** - * @module generation/configuration_utils - */ - - - -/** - * Class that holds a configuration for a generation task. - */ -class GenerationConfig { - // Parameters that control the length of the output - /** - * The maximum length the generated tokens can have. - * Corresponds to the length of the input prompt + `max_new_tokens`. - * Its effect is overridden by `max_new_tokens`, if also set. - * @type {number} - * @default 20 - */ - max_length = 20; - - /** - * The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt. - * @type {number} - * @default null - */ - max_new_tokens = null; - - /** - * The minimum length of the sequence to be generated. - * Corresponds to the length of the input prompt + `min_new_tokens`. - * Its effect is overridden by `min_new_tokens`, if also set. - * @type {number} - * @default 0 - */ - min_length = 0; - - /** - * The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt. - * @type {number} - * @default null - */ - min_new_tokens = null; - - /** - * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: - * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; - * - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates; - * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). - * @type {boolean|"never"} - * @default false - */ - early_stopping = false; - - /** - * The maximum amount of time you allow the computation to run for in seconds. - * Generation will still finish the current pass after allocated time has been passed. - * @type {number} - * @default null - */ - max_time = null; - - // Parameters that control the generation strategy used - /** - * Whether or not to use sampling; use greedy decoding otherwise. - * @type {boolean} - * @default false - */ - do_sample = false; - - /** - * Number of beams for beam search. 1 means no beam search. - * @type {number} - * @default 1 - */ - num_beams = 1; - - /** - * Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. - * See [this paper](https://huggingface.co/papers/1610.02424) for more details. - * @type {number} - * @default 1 - */ - num_beam_groups = 1; - - /** - * The values balance the model confidence and the degeneration penalty in contrastive search decoding. - * @type {number} - * @default null - */ - penalty_alpha = null; - - /** - * Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding. - * @type {boolean} - * @default true - */ - use_cache = true; - - // Parameters for manipulation of the model output logits - /** - * The value used to modulate the next token probabilities. - * @type {number} - * @default 1.0 - */ - temperature = 1.0; - - /** - * The number of highest probability vocabulary tokens to keep for top-k-filtering. - * @type {number} - * @default 50 - */ - top_k = 50; - - /** - * If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. - * @type {number} - * @default 1.0 - */ - top_p = 1.0; - - /** - * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. - * If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. - * See [this paper](https://huggingface.co/papers/2202.00666) for more details. - * @type {number} - * @default 1.0 - */ - typical_p = 1.0; - - /** - * If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. - * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. - * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details. - * @type {number} - * @default 0.0 - */ - epsilon_cutoff = 0.0; - - /** - * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. - * If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. - * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. - * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details. - * @type {number} - * @default 0.0 - */ - eta_cutoff = 0.0; - - /** - * This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. - * Note that `diversity_penalty` is only effective if `group beam search` is enabled. - * @type {number} - * @default 0.0 - */ - diversity_penalty = 0.0; - - /** - * The parameter for repetition penalty. 1.0 means no penalty. - * See [this paper](https://huggingface.co/papers/1909.05858) for more details. - * @type {number} - * @default 1.0 - */ - repetition_penalty = 1.0; - - /** - * The paramater for encoder_repetition_penalty. - * An exponential penalty on sequences that are not in the original input. - * 1.0 means no penalty. - * @type {number} - * @default 1.0 - */ - encoder_repetition_penalty = 1.0; - - /** - * Exponential penalty to the length that is used with beam-based generation. - * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. - * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. - * @type {number} - * @default 1.0 - */ - length_penalty = 1.0; - - /** - * If set to int > 0, all ngrams of that size can only occur once. - * @type {number} - * @default 0 - */ - no_repeat_ngram_size = 0; - - /** - * List of token ids that are not allowed to be generated. - * In order to get the token ids of the words that should not appear in the generated text, use - * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`. - * @type {number[][]} - * @default null - */ - bad_words_ids = null; - - /** - * List of token ids that must be generated. - * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. - * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word. - * @type {number[][]|number[][][]} - * @default null - */ - force_words_ids = null; - - /** - * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). - * It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization. - * @type {boolean} - * @default false - */ - renormalize_logits = false; - - /** - * Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible. - * @type {Object[]} - * @default null - */ - constraints = null; - - /** - * The id of the token to force as the first generated token after the `decoder_start_token_id`. - * Useful for multilingual models like mBART where the first generated token needs to be the target language token. - * @type {number} - * @default null - */ - forced_bos_token_id = null; - - /** - * The id of the token to force as the last generated token when `max_length` is reached. - * Optionally, use a list to set multiple *end-of-sequence* tokens. - * @type {number|number[]} - * @default null - */ - forced_eos_token_id = null; - - /** - * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation. - * @type {boolean} - */ - remove_invalid_values = false; - - /** - * This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. - * The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay. - * @type {[number, number]} - * @default null - */ - exponential_decay_length_penalty = null; - - /** - * A list of tokens that will be suppressed at generation. - * The `SuppressTokens` logit processor will set their log probs to `-inf` so that they are not sampled. - * @type {number[]} - * @default null - */ - suppress_tokens = null; - - /** - * A streamer that will be used to stream the generation. - * @type {import('./streamers.js').TextStreamer} - * @default null - */ - streamer = null; - - /** - * A list of tokens that will be suppressed at the beginning of the generation. - * The `SuppressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled. - * @type {number[]} - * @default null - */ - begin_suppress_tokens = null; - - /** - * A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. - * For example, `[[1, 123]]` means the second generated token will always be a token of index 123. - * @type {[number, number][]} - * @default null - */ - forced_decoder_ids = null; - - /** - * The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. - * Higher guidance scale encourages the model to generate samples that are more closely linked to the input - * prompt, usually at the expense of poorer quality. - * @type {number} - * @default null - */ - guidance_scale = null; - - // Parameters that define the output variables of `generate` - /** - * The number of independently computed returned sequences for each element in the batch. - * @type {number} - * @default 1 - */ - num_return_sequences = 1; - - /** - * Whether or not to return the attentions tensors of all attention layers. - * See `attentions` under returned tensors for more details. - * @type {boolean} - * @default false - */ - output_attentions = false; - - /** - * Whether or not to return the hidden states of all layers. - * See `hidden_states` under returned tensors for more details. - * @type {boolean} - * @default false - */ - output_hidden_states = false; - - /** - * Whether or not to return the prediction scores. - * See `scores` under returned tensors for more details. - * @type {boolean} - * @default false - */ - output_scores = false; - - /** - * Whether or not to return a `ModelOutput` instead of a plain tuple. - * @type {boolean} - * @default false - */ - return_dict_in_generate = false; - - // Special tokens that can be used at generation time - /** - * The id of the *padding* token. - * @type {number} - * @default null - */ - pad_token_id = null; - - /** - * The id of the *beginning-of-sequence* token. - * @type {number} - * @default null - */ - bos_token_id = null; - - /** - * The id of the *end-of-sequence* token. - * Optionally, use a list to set multiple *end-of-sequence* tokens. - * @type {number|number[]} - * @default null - */ - eos_token_id = null; - - // Generation parameters exclusive to encoder-decoder models - /** - * If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. - * @type {number} - * @default 0 - */ - encoder_no_repeat_ngram_size = 0; - - /** - * If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token. - * @type {number} - * @default null - */ - decoder_start_token_id = null; - - // Wild card - /** - * Additional generation kwargs will be forwarded to the `generate` function of the model. - * Kwargs that are not present in `generate`'s signature will be used in the model forward pass. - * @type {Object} - * @default {} - */ - generation_kwargs = {}; - - /** - * - * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config - */ - constructor(config) { - Object.assign(this, (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.pick)(config, Object.getOwnPropertyNames(this))); - } -} - - - -/***/ }), - -/***/ "./src/generation/logits_process.js": -/*!******************************************!*\ - !*** ./src/generation/logits_process.js ***! - \******************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ClassifierFreeGuidanceLogitsProcessor: () => (/* binding */ ClassifierFreeGuidanceLogitsProcessor), -/* harmony export */ ForcedBOSTokenLogitsProcessor: () => (/* binding */ ForcedBOSTokenLogitsProcessor), -/* harmony export */ ForcedEOSTokenLogitsProcessor: () => (/* binding */ ForcedEOSTokenLogitsProcessor), -/* harmony export */ LogitsProcessor: () => (/* binding */ LogitsProcessor), -/* harmony export */ LogitsProcessorList: () => (/* binding */ LogitsProcessorList), -/* harmony export */ LogitsWarper: () => (/* binding */ LogitsWarper), -/* harmony export */ MinLengthLogitsProcessor: () => (/* binding */ MinLengthLogitsProcessor), -/* harmony export */ MinNewTokensLengthLogitsProcessor: () => (/* binding */ MinNewTokensLengthLogitsProcessor), -/* harmony export */ NoBadWordsLogitsProcessor: () => (/* binding */ NoBadWordsLogitsProcessor), -/* harmony export */ NoRepeatNGramLogitsProcessor: () => (/* binding */ NoRepeatNGramLogitsProcessor), -/* harmony export */ RepetitionPenaltyLogitsProcessor: () => (/* binding */ RepetitionPenaltyLogitsProcessor), -/* harmony export */ SuppressTokensAtBeginLogitsProcessor: () => (/* binding */ SuppressTokensAtBeginLogitsProcessor), -/* harmony export */ TemperatureLogitsWarper: () => (/* binding */ TemperatureLogitsWarper), -/* harmony export */ TopKLogitsWarper: () => (/* binding */ TopKLogitsWarper), -/* harmony export */ TopPLogitsWarper: () => (/* binding */ TopPLogitsWarper), -/* harmony export */ WhisperTimeStampLogitsProcessor: () => (/* binding */ WhisperTimeStampLogitsProcessor) -/* harmony export */ }); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/maths.js */ "./src/utils/maths.js"); - -/** - * @module generation/logits_process - */ - - - - - - -/** - * Abstract base class for all logit processors that can be applied during generation. - */ -class LogitsProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Apply the processor to the input logits. - * - * @abstract - * @param {bigint[][]} input_ids The input ids. - * @param {Tensor} logits The logits to process. - * @throws {Error} Throws an error if `_call` is not implemented in the subclass. - */ - _call(input_ids, logits) { - throw Error("`_call` should be implemented in a subclass") - } -} - - -/** - * Abstract base class for all logit warpers that can be applied during generation with multinomial sampling. - */ -class LogitsWarper extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Apply the processor to the input logits. - * - * @abstract - * @param {bigint[][]} input_ids The input ids. - * @param {Tensor} logits The logits to process. - * @throws {Error} Throws an error if `_call` is not implemented in the subclass. - */ - _call(input_ids, logits) { - throw Error("`_call` should be implemented in a subclass") - } -} - - -/** - * A class representing a list of logits processors. A logits processor is a function that modifies the logits - * output of a language model. This class provides methods for adding new processors and applying all processors to a - * batch of logits. - */ -class LogitsProcessorList extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Constructs a new instance of `LogitsProcessorList`. - */ - constructor() { - super(); - this.processors = []; - } - - /** - * Adds a new logits processor to the list. - * - * @param {LogitsProcessor} item The logits processor function to add. - */ - push(item) { - this.processors.push(item); - } - - /** - * Adds multiple logits processors to the list. - * - * @param {LogitsProcessor[]} items The logits processor functions to add. - */ - extend(items) { - this.processors.push(...items); - } - - /** - * Applies all logits processors in the list to a batch of logits, modifying them in-place. - * - * @param {bigint[][]} input_ids The input IDs for the language model. - * @param {Tensor} logits - */ - _call(input_ids, logits) { - let toReturn = logits; - // NOTE: Most processors modify logits inplace - for (const processor of this.processors) { - toReturn = processor(input_ids, toReturn); - } - return toReturn; - } - - [Symbol.iterator]() { - return this.processors.values(); - } -} - -// DEPRECATED: https://github.com/huggingface/transformers/pull/29485 -// /** -// * A logits processor that forces a specific token to be generated by the decoder. -// */ -// export class ForceTokensLogitsProcessor extends LogitsProcessor { -// /** -// * Constructs a new instance of `ForceTokensLogitsProcessor`. -// * -// * @param {[number, number][]} forced_decoder_ids The ids of tokens that should be forced. -// */ -// constructor(forced_decoder_ids) { -// super(); -// // TODO: convert to `new Map(forced_decoder_ids)` -// this.force_token_map = Object.fromEntries(forced_decoder_ids ?? []); -// } - -// /** -// * Apply the processor to the input logits. -// * -// * @param {bigint[][]} input_ids The input ids. -// * @param {Tensor} logits The logits to process. -// * @returns {Tensor} The processed logits. -// */ -// _call(input_ids, logits) { -// console.log('this.force_token_map', this.force_token_map) -// console.log('call ForceTokensLogitsProcessor', input_ids, logits) -// console.log('input_ids.length', input_ids.length) -// let map = this.force_token_map[input_ids.length]; -// if (map) { // There exists a mapping -// logits.data.fill(-Infinity) -// logits.data[map] = 0; -// } -// console.log('map', map) -// // throw Error("Not implemented") -// return logits; -// } -// } - -/** - * A LogitsProcessor that forces a BOS token at the beginning of the generated sequence. - */ -class ForcedBOSTokenLogitsProcessor extends LogitsProcessor { - /** - * Create a ForcedBOSTokenLogitsProcessor. - * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. - */ - constructor(bos_token_id) { - super(); - this.bos_token_id = bos_token_id; - } - - /** - * Apply the BOS token forcing to the logits. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The logits with BOS token forcing. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - if (input_ids[i].length === 1) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - batch_logits_data.fill(-Infinity); - batch_logits_data[this.bos_token_id] = 0; - } - } - return logits; - } -} - -/** - * A logits processor that enforces the specified token as the last generated token when `max_length` is reached. - */ -class ForcedEOSTokenLogitsProcessor extends LogitsProcessor { - /** - * Create a ForcedEOSTokenLogitsProcessor. - * @param {number} max_length The maximum length of the sequence to be generated. - * @param {number|number[]} eos_token_id The id(s) of the *end-of-sequence* token. - */ - constructor(max_length, eos_token_id) { - super(); - this.max_length = max_length; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - - /** - * Apply the processor to input_ids and logits. - * - * @param {bigint[][]} input_ids The input ids. - * @param {Tensor} logits The logits tensor. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - if (input_ids[i].length === this.max_length - 1) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - batch_logits_data.fill(-Infinity); - for (const eos_token of this.eos_token_id) { - batch_logits_data[eos_token] = 0; - } - } - } - return logits; - } -} - -/** - * A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts - * generating using `begin_index` tokens. This should ensure that the tokens defined by - * `begin_suppress_tokens` at not sampled at the begining of the generation. - */ -class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor { - /** - * Create a SuppressTokensAtBeginLogitsProcessor. - * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. - * @param {number} begin_index The number of tokens to generate before suppressing tokens. - */ - constructor(begin_suppress_tokens, begin_index) { - super(); - this.begin_suppress_tokens = begin_suppress_tokens; - this.begin_index = begin_index; - } - - /** - * Apply the BOS token forcing to the logits. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The logits with BOS token forcing. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - if (input_ids[i].length === this.begin_index) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - for (const token_id of this.begin_suppress_tokens) { - batch_logits_data[token_id] = -Infinity; - } - } - } - return logits; - } -} - -/** - * A LogitsProcessor that handles adding timestamps to generated text. - */ -class WhisperTimeStampLogitsProcessor extends LogitsProcessor { - /** - * Constructs a new WhisperTimeStampLogitsProcessor. - * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model. - * @param {number[]} init_tokens The initial tokens of the input sequence. - */ - constructor(generate_config, init_tokens) { - super(); - this.eos_token_id = - Array.isArray(generate_config.eos_token_id) - ? generate_config.eos_token_id[0] - : generate_config.eos_token_id; - - this.no_timestamps_token_id = generate_config.no_timestamps_token_id; - this.timestamp_begin = this.no_timestamps_token_id + 1; - - this.begin_index = init_tokens.length; - if (init_tokens.at(-1) === this.no_timestamps_token_id) { - this.begin_index -= 1; - } - this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; - } - - /** - * Modify the logits to handle timestamp tokens. - * @param {bigint[][]} input_ids The input sequence of tokens. - * @param {Tensor} logits The logits output by the model. - * @returns {Tensor} The modified logits. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - - // suppress <|notimestamps|> which is handled by without_timestamps - batch_logits_data[this.no_timestamps_token_id] = -Infinity; - - if (input_ids[i].length === this.begin_index - 1) { - batch_logits_data.fill(-Infinity); - batch_logits_data[this.timestamp_begin] = 0; - continue; - } - - // timestamps have to appear in pairs, except directly before eos_token; mask logits accordingly - const seq = input_ids[i].slice(this.begin_index); - const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; - const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; - - if (last_was_timestamp) { - if (penultimate_was_timestamp) { // has to be non-timestamp - batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity); - } else { // cannot be normal text tokens - batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity); - } - } - - // apply the `max_initial_timestamp` option - if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) { - const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; - batch_logits_data.subarray(last_allowed + 1).fill(-Infinity); - } - - // if sum of probability over timestamps is above any other token, sample timestamp - const logprobs = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.log_softmax)(batch_logits_data); - const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b)); - const max_text_token_logprob = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logprobs.subarray(0, this.timestamp_begin))[0]; - - if (timestamp_logprob > max_text_token_logprob) { - batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity); - } - } - - return logits; - } -} - -/** - * A logits processor that disallows ngrams of a certain size to be repeated. - */ -class NoRepeatNGramLogitsProcessor extends LogitsProcessor { - /** - * Create a NoRepeatNGramLogitsProcessor. - * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once. - */ - constructor(no_repeat_ngram_size) { - super(); - this.no_repeat_ngram_size = no_repeat_ngram_size; - } - - /** - * Generate n-grams from a sequence of token ids. - * @param {bigint[]} prevInputIds List of previous input ids - * @returns {Map} Map of generated n-grams - */ - getNgrams(prevInputIds) { - const curLen = prevInputIds.length; - - /**@type {number[][]} */ - const ngrams = []; - for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) { - const ngram = []; - for (let k = 0; k < this.no_repeat_ngram_size; ++k) { - ngram.push(prevInputIds[j + k]); - } - ngrams.push(ngram.map(Number)); - } - - /** @type {Map} */ - const generatedNgram = new Map(); - for (const ngram of ngrams) { - const prevNgram = ngram.slice(0, ngram.length - 1); - const prevNgramKey = JSON.stringify(prevNgram); - const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; - prevNgramValue.push(ngram[ngram.length - 1]); - generatedNgram.set(prevNgramKey, prevNgramValue); - } - return generatedNgram; - } - - /** - * Generate n-grams from a sequence of token ids. - * @param {Map} bannedNgrams Map of banned n-grams - * @param {bigint[]} prevInputIds List of previous input ids - * @returns {number[]} Map of generated n-grams - */ - getGeneratedNgrams(bannedNgrams, prevInputIds) { - const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); - const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? []; - return banned; - } - - /** - * Calculate banned n-gram tokens - * @param {bigint[]} prevInputIds List of previous input ids - * @returns {number[]} Map of generated n-grams - */ - calcBannedNgramTokens(prevInputIds) { - const bannedTokens = []; - if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { - // return no banned tokens if we haven't generated no_repeat_ngram_size tokens yet - return bannedTokens; - - } else { - const generatedNgrams = this.getNgrams(prevInputIds); - const bannedTokens = this.getGeneratedNgrams(generatedNgrams, prevInputIds); - return bannedTokens; - } - } - - /** - * Apply the no-repeat-ngram processor to the logits. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The logits with no-repeat-ngram processing. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - const bannedTokens = this.calcBannedNgramTokens(input_ids[i]); - for (const token of bannedTokens) { - batch_logits_data[token] = -Infinity; - } - } - return logits; - } -} - -/** - * A logits processor that prevents the repetition of previous tokens through a penalty. - * This penalty is applied at most once per token. Note that, for decoder-only models like most LLMs, - * the considered tokens include the prompt. - * - * In the original [paper](https://huggingface.co/papers/1909.05858), the authors suggest the use of a - * penalty of around 1.2 to achieve a good balance between truthful generation and lack of repetition. - * To penalize and reduce repetition, use `penalty` values above 1.0, where a higher value penalizes - * more strongly. To reward and encourage repetition, use `penalty` values between 0.0 and 1.0, where - * a lower value rewards more strongly. - */ -class RepetitionPenaltyLogitsProcessor extends LogitsProcessor { - /** - * Create a RepetitionPenaltyLogitsProcessor. - * @param {number} penalty The parameter for repetition penalty. - * - 1.0 means no penalty. Above 1.0 penalizes previously generated tokens. - * - Between 0.0 and 1.0 rewards previously generated tokens. - */ - constructor(penalty) { - super(); - this.penalty = penalty; - } - - /** - * Apply the repetition penalty to the logits. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The logits with repetition penalty processing. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - for (const input_id of new Set(input_ids[i])) { - const token = Number(input_id); - if (batch_logits_data[token] < 0) { - batch_logits_data[token] *= this.penalty; - } else { - batch_logits_data[token] /= this.penalty; - } - } - } - - return logits - } -} - -/** - * A logits processor that enforces a minimum number of tokens. - */ -class MinLengthLogitsProcessor extends LogitsProcessor { - /** - * Create a MinLengthLogitsProcessor. - * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. - * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. - */ - constructor(min_length, eos_token_id) { - super(); - this.min_length = min_length; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - - /** - * Apply logit processor. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The processed logits. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - if (input_ids[i].length < this.min_length) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - - for (const eos_token of this.eos_token_id) { - batch_logits_data[eos_token] = -Infinity; - } - } - } - - return logits - } -} - -/** - * A logits processor that enforces a minimum number of new tokens. - */ -class MinNewTokensLengthLogitsProcessor extends LogitsProcessor { - /** - * Create a MinNewTokensLengthLogitsProcessor. - * @param {number} prompt_length_to_skip The input tokens length. - * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. - * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token. - */ - constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { - super(); - this.prompt_length_to_skip = prompt_length_to_skip; - this.min_new_tokens = min_new_tokens; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - - /** - * Apply logit processor. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The processed logits. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip; - if (new_tokens_length < this.min_new_tokens) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - - for (const eos_token of this.eos_token_id) { - batch_logits_data[eos_token] = -Infinity; - } - } - } - return logits - } -} - -class NoBadWordsLogitsProcessor extends LogitsProcessor { - /** - * Create a `NoBadWordsLogitsProcessor`. - * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated. - * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. - */ - constructor(bad_words_ids, eos_token_id) { - super(); - this.bad_words_ids = bad_words_ids; - this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; - } - - /** - * Apply logit processor. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The processed logits. - */ - _call(input_ids, logits) { - for (let i = 0; i < input_ids.length; ++i) { - const batch_logits_data = /** @type {Float32Array} */(logits[i].data); - const ids = input_ids[i]; - for (const bad_word_ids of this.bad_words_ids) { - // There aren't enough tokens to match the banned sequence - if (ids.length < bad_word_ids.length - 1) continue; - - // Whether to modify the logits of the last token in the bad word id sequence - let mark = true; - - // For each bad word in the list, if the current sequence of input ids ends with this sequence (excluding the last), - // then we set the logits of the last bad word id to -Infinity. - for (let j = 1; j <= bad_word_ids.length - 1; ++j) { - // NOTE: We use != instead of !== to compare bigint and number - // @ts-ignore - if (bad_word_ids.at(-j - 1) != ids.at(-j)) { - // We have found a mismatch - mark = false; - break; - } - } - if (mark) { - batch_logits_data[bad_word_ids.at(-1)] = -Infinity; - } - } - } - return logits - } -} - -/** - * [`LogitsProcessor`] for classifier free guidance (CFG). The scores are split over the batch dimension, - * where the first half correspond to the conditional logits (predicted from the input prompt) and the second half - * correspond to the unconditional logits (predicted from an empty or 'null' prompt). The processor computes a - * weighted average across the conditional and unconditional logits, parameterised by the `guidance_scale`. - * - * See [the paper](https://huggingface.co/papers/2306.05284) for more information. - */ -class ClassifierFreeGuidanceLogitsProcessor extends LogitsProcessor { - - /** - * Create a `ClassifierFreeGuidanceLogitsProcessor`. - * @param {number} guidance_scale The guidance scale for classifier free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. - * Higher guidance scale encourages the model to generate samples that are more closely linked to the input - * prompt, usually at the expense of poorer quality. - */ - constructor(guidance_scale) { - super(); - if (guidance_scale <= 1) { - throw new Error( - `Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${guidance_scale}.` - ) - } - this.guidance_scale = guidance_scale; - } - - /** - * Apply logit processor. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The processed logits. - */ - _call(input_ids, logits) { - if (logits.dims[0] !== 2 * input_ids.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 ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.` - ) - } - - const unguided_bsz = input_ids.length; - const cond_logits = logits.slice([0, unguided_bsz], null); - const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null); - - // Merge into uncond_logits (to save memory). This is equivalent to the following: - // scores = uncond_logits + (cond_logits - uncond_logits) * guidance_scale - for (let i = 0; i < uncond_logits.data.length; ++i) { - uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale; - } - - return uncond_logits; - } -} - -/** - * [`LogitsWarper`] for temperature (exponential scaling output probability distribution), which effectively means - * that it can control the randomness of the predicted tokens. Often used together with [`TopPLogitsWarper`] and [`TopKLogitsWarper`]. - */ -class TemperatureLogitsWarper extends LogitsWarper { - /** - * Create a `TemperatureLogitsWarper`. - * @param {number} temperature Strictly positive float value used to modulate the logits distribution. - * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting - * all probability mass to the most likely token. - */ - constructor(temperature) { - super(); - - if (typeof temperature !== 'number' || temperature <= 0) { - let errorMessage = - `\`temperature\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`; - - if (temperature === 0) { - errorMessage += " If you're looking for greedy decoding strategies, set `do_sample=false`." - } - } - this.temperature = temperature; - } - - /** - * Apply logit warper. - * @param {bigint[][]} input_ids The input IDs. - * @param {Tensor} logits The logits. - * @returns {Tensor} The processed logits. - */ - _call(input_ids, logits) { - const batch_logits_data = /** @type {Float32Array} */(logits.data); - for (let i = 0; i < batch_logits_data.length; ++i) { - batch_logits_data[i] /= this.temperature; - } - return logits; - } -} - -/** - * [`LogitsWarper`] that performs top-p, i.e. restricting to top tokens summing to prob_cut_off <= prob_cut_off. - * Often used together with [`TemperatureLogitsWarper`] and [`TopKLogitsWarper`]. - */ -class TopPLogitsWarper extends LogitsWarper { - /** - * Create a `TopPLogitsWarper`. - * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with - * probabilities that add up to `top_p` or higher are kept for generation. - * @param {Object} options Additional options for the top-p sampling. - * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. - * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. - */ - constructor(top_p, { - filter_value = -Infinity, - min_tokens_to_keep = 1, - } = {}) { - super(); - if (top_p < 0 || top_p > 1.0) { - throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${top_p}`) - } - if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) { - throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${min_tokens_to_keep}`) - } - - this.top_p = top_p - this.filter_value = filter_value - this.min_tokens_to_keep = min_tokens_to_keep - } -} - -/** - * [`LogitsWarper`] that performs top-k, i.e. restricting to the k highest probability elements. - * Often used together with [`TemperatureLogitsWarper`] and [`TopPLogitsWarper`]. - */ -class TopKLogitsWarper extends LogitsWarper { - /** - * Create a `TopKLogitsWarper`. - * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation. - * @param {Object} options Additional options for the top-k sampling. - * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. - * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. - */ - constructor(top_k, { - filter_value = -Infinity, - min_tokens_to_keep = 1, - } = {}) { - super(); - if (!Number.isInteger(top_k) || top_k < 0) { - throw new Error(`\`top_k\` must be a positive integer, but is ${top_k}`) - } - - this.top_k = Math.max(top_k, min_tokens_to_keep) - this.filter_value = filter_value - } -} - -/***/ }), - -/***/ "./src/generation/logits_sampler.js": -/*!******************************************!*\ - !*** ./src/generation/logits_sampler.js ***! - \******************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ LogitsSampler: () => (/* binding */ LogitsSampler) -/* harmony export */ }); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../generation/configuration_utils.js */ "./src/generation/configuration_utils.js"); - -/** - * @module generation/logits_sampler - */ - - - - - - - -/** - * Sampler is a base class for all sampling methods used for text generation. - */ -class LogitsSampler extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Creates a new Sampler object with the specified generation config. - * @param {GenerationConfig} generation_config The generation config. - */ - constructor(generation_config) { - super(); - this.generation_config = generation_config; - } - - /** - * Executes the sampler, using the specified logits. - * @param {Tensor} logits - * @returns {Promise<[bigint, number][]>} - */ - async _call(logits) { - // Sample from logits, of dims [batch, sequence_length, vocab_size]. - // If index is specified, sample from [batch, index, vocab_size]. - return this.sample(logits); - } - - /** - * Abstract method for sampling the logits. - * @param {Tensor} logits - * @throws {Error} If not implemented in subclass. - * @returns {Promise<[bigint, number][]>} - */ - async sample(logits) { - throw Error("sample should be implemented in subclasses.") - } - - /** - * Returns the specified logits as an array, with temperature applied. - * @param {Tensor} logits - * @param {number} index - * @returns {Float32Array} - */ - getLogits(logits, index) { - let vocabSize = logits.dims.at(-1); - - let logs = /** @type {Float32Array} */(logits.data); - - if (index === -1) { - logs = logs.slice(-vocabSize); - } else { - let startIndex = index * vocabSize; - logs = logs.slice(startIndex, startIndex + vocabSize); - } - return logs; - } - - /** - * Selects an item randomly based on the specified probabilities. - * @param {import("../transformers.js").DataArray} probabilities An array of probabilities to use for selection. - * @returns {number} The index of the selected item. - */ - randomSelect(probabilities) { - // Return index of chosen item - let sumProbabilities = 0; - for (let i = 0; i < probabilities.length; ++i) { - sumProbabilities += probabilities[i]; - } - - let r = Math.random() * sumProbabilities; - for (let i = 0; i < probabilities.length; ++i) { - r -= probabilities[i]; - if (r <= 0) { - return i; - } - } - return 0; // return first (most probable) as a fallback - } - - /** - * Returns a Sampler object based on the specified options. - * @param {GenerationConfig} generation_config An object containing options for the sampler. - * @returns {LogitsSampler} A Sampler object. - */ - static getSampler(generation_config) { - // - *greedy decoding*: `num_beams=1` and `do_sample=False` - // - *contrastive search*: `penalty_alpha>0` and `top_k>1` - // - *multinomial sampling*: `num_beams=1` and `do_sample=True` - // - *beam-search decoding*: `num_beams>1` and `do_sample=False` - // - *beam-search multinomial sampling*: `num_beams>1` and `do_sample=True` - // - *diverse beam-search decoding*: `num_beams>1` and `num_beam_groups>1` - // - *constrained beam-search decoding*: `constraints!=None` or `force_words_ids!=None` - - // NOTE: beam search is implemented directly into the generation function - if (generation_config.do_sample) { - return new MultinomialSampler(generation_config); - - } else if (generation_config.num_beams > 1) { - return new BeamSearchSampler(generation_config); - - } else { - if (generation_config.num_return_sequences > 1) { - throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`) - } - return new GreedySampler(generation_config); - } - } -} - -/** - * Class representing a Greedy Sampler. - */ -class GreedySampler extends LogitsSampler { - /** - * Sample the maximum probability of a given logits tensor. - * @param {Tensor} logits - * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). - */ - async sample(logits) { - // NOTE: no need to do log_softmax here since we only take the maximum - const argmax = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(logits.data)[1]; - - // Note: score is meaningless in this context, since we are performing - // greedy search (p = 1 => log(p) = 0) - return [ - [BigInt(argmax), 0] - ]; - } -} - -/** - * Class representing a MultinomialSampler. - */ -class MultinomialSampler extends LogitsSampler { - - /** - * Sample from the logits. - * @param {Tensor} logits - * @returns {Promise<[bigint, number][]>} - */ - async sample(logits) { - let k = logits.dims.at(-1); // defaults to vocab size - if (this.generation_config.top_k > 0) { - k = Math.min(this.generation_config.top_k, k); - } - - // Get top k tokens - const [v, i] = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.topk)(logits, k); - - // Compute softmax over logits - const probabilities = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(/** @type {Float32Array} */(v.data)); - - return Array.from({ length: this.generation_config.num_beams }, () => { - const sampledIndex = this.randomSelect(probabilities); - return [ - i.data[sampledIndex], // token id - Math.log(probabilities[sampledIndex]), // score - ]; - }); - } -} - - -/** - * Class representing a BeamSearchSampler. - */ -class BeamSearchSampler extends LogitsSampler { - - /** - * Sample from the logits. - * @param {Tensor} logits - * @returns {Promise<[bigint, number][]>} - */ - async sample(logits) { - let k = logits.dims.at(-1); // defaults to vocab size - if (this.generation_config.top_k > 0) { - k = Math.min(this.generation_config.top_k, k); - } - - // Get top k tokens - const [v, i] = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.topk)(logits, k); - - // Compute softmax over logits - const probabilities = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(/** @type {Float32Array} */(v.data)); - - return Array.from({ length: this.generation_config.num_beams }, (_, x) => { - return [ - i.data[x], // token id - Math.log(probabilities[x]), // score - ]; - }); - } -} - - -/***/ }), - -/***/ "./src/generation/stopping_criteria.js": -/*!*********************************************!*\ - !*** ./src/generation/stopping_criteria.js ***! - \*********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EosTokenCriteria: () => (/* binding */ EosTokenCriteria), -/* harmony export */ InterruptableStoppingCriteria: () => (/* binding */ InterruptableStoppingCriteria), -/* harmony export */ MaxLengthCriteria: () => (/* binding */ MaxLengthCriteria), -/* harmony export */ StoppingCriteria: () => (/* binding */ StoppingCriteria), -/* harmony export */ StoppingCriteriaList: () => (/* binding */ StoppingCriteriaList) -/* harmony export */ }); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/generic.js */ "./src/utils/generic.js"); - -/** - * @module generation/stopping_criteria - */ - - - -// NOTE: -// Stopping Criteria returns a list of `batch_size` booleans, indicating whether each sequence in the batch should be stopped. - -/** - * Abstract base class for all stopping criteria that can be applied during generation. - */ -class StoppingCriteria extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * - * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`): - * Indices of input sequence tokens in the vocabulary. - * @param {number[][]} scores scores (`number[][]` of shape `(batch_size, config.vocab_size)`): - * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax - * or scores for each vocabulary token after SoftMax. - * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped. - */ - _call(input_ids, scores) { - throw Error("StoppingCriteria needs to be subclassed"); - } -} -/** - */ -class StoppingCriteriaList extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Constructs a new instance of `StoppingCriteriaList`. - */ - constructor() { - super(); - this.criteria = []; - } - - /** - * Adds a new stopping criterion to the list. - * - * @param {StoppingCriteria} item The stopping criterion to add. - */ - push(item) { - this.criteria.push(item); - } - - /** - * Adds multiple stopping criteria to the list. - * - * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add. - */ - extend(items) { - if (items instanceof StoppingCriteriaList) { - items = items.criteria; - } else if (items instanceof StoppingCriteria) { - items = [items]; + case "break": + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + result = new Break(); + break; + case "continue": + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + result = new Continue(); + break; + case "filter": { + ++current; + let filterNode = parsePrimaryExpression(); + if (filterNode instanceof Identifier && is2(TOKEN_TYPES.OpenParen)) { + filterNode = parseCallExpression(filterNode); } - this.criteria.push(...items); - } - - _call(input_ids, scores) { - const is_done = new Array(input_ids.length).fill(false); - for (const criterion of this.criteria) { - const criterion_done = criterion(input_ids, scores); - for (let i = 0; i < is_done.length; ++i) { - is_done[i] ||= criterion_done[i]; - } + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const filterBody = []; + while (!isStatement("endfilter")) { + filterBody.push(parseAny()); } - return is_done; - } - - [Symbol.iterator]() { - return this.criteria.values(); + expect(TOKEN_TYPES.OpenStatement, "Expected '{%'"); + expectIdentifier("endfilter"); + expect(TOKEN_TYPES.CloseStatement, "Expected '%}'"); + result = new FilterStatement(filterNode, filterBody); + break; + } + default: + throw new SyntaxError(`Unknown statement type: ${name}`); } -} - -/** - * This class can be used to stop generation whenever the full generated number of tokens exceeds `max_length`. - * Keep in mind for decoder-only type of transformers, this will include the initial prompted tokens. - */ -class MaxLengthCriteria extends StoppingCriteria { - - /** - * - * @param {number} max_length The maximum length that the output sequence can have in number of tokens. - * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute. - */ - constructor(max_length, max_position_embeddings = null) { - super(); - this.max_length = max_length; - this.max_position_embeddings = max_position_embeddings; + return result; + } + function parseJinjaExpression() { + expect(TOKEN_TYPES.OpenExpression, "Expected opening expression token"); + const result = parseExpression(); + expect(TOKEN_TYPES.CloseExpression, "Expected closing expression token"); + return result; + } + function parseSetStatement() { + const left = parseExpressionSequence(); + let value = null; + const body = []; + if (is2(TOKEN_TYPES.Equals)) { + ++current; + value = parseExpressionSequence(); + } else { + expect(TOKEN_TYPES.CloseStatement, "Expected %} token"); + while (!isStatement("endset")) { + body.push(parseAny()); + } + expect(TOKEN_TYPES.OpenStatement, "Expected {% token"); + expectIdentifier("endset"); } - - _call(input_ids) { - return input_ids.map(ids => ids.length >= this.max_length); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + return new SetStatement(left, value, body); + } + function parseIfStatement() { + const test = parseExpression(); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + const alternate = []; + while (!isStatement("elif", "else", "endif")) { + body.push(parseAny()); } -} - -// TODO: add MaxTimeCriteria - -/** - * This class can be used to stop generation whenever the "end-of-sequence" token is generated. - * By default, it uses the `model.generation_config.eos_token_id`. - */ -class EosTokenCriteria extends StoppingCriteria { - - /** - * - * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. - * Optionally, use a list to set multiple *end-of-sequence* tokens. - */ - constructor(eos_token_id) { - super(); - if (!Array.isArray(eos_token_id)) { - eos_token_id = [eos_token_id]; - } - this.eos_token_id = eos_token_id; + if (isStatement("elif")) { + ++current; + ++current; + const result = parseIfStatement(); + alternate.push(result); + } else if (isStatement("else")) { + ++current; + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + while (!isStatement("endif")) { + alternate.push(parseAny()); + } } - - /** - * - * @param {number[][]} input_ids - * @param {number[][]} scores - * @returns {boolean[]} - */ - _call(input_ids, scores) { - return input_ids.map(ids => { - const last = ids.at(-1); - // NOTE: We use == instead of === to allow for number/bigint comparison - return this.eos_token_id.some(eos_id => last == eos_id); - }); + return new If(test, body, alternate); + } + function parseMacroStatement() { + const name = parsePrimaryExpression(); + if (name.type !== "Identifier") { + throw new SyntaxError(`Expected identifier following macro statement`); } -} - -/** - * This class can be used to stop generation whenever the user interrupts the process. - */ -class InterruptableStoppingCriteria extends StoppingCriteria { - constructor() { - super(); - this.interrupted = false; + const args = parseArgs("parameters"); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + while (!isStatement("endmacro")) { + body.push(parseAny()); } - - interrupt() { - this.interrupted = true; + return new Macro(name, args, body); + } + function parseExpressionSequence(primary = false) { + const fn2 = primary ? parsePrimaryExpression : parseExpression; + const expressions = [fn2()]; + const isTuple = is2(TOKEN_TYPES.Comma); + while (isTuple) { + ++current; + expressions.push(fn2()); + if (!is2(TOKEN_TYPES.Comma)) { + break; + } } - - reset() { - this.interrupted = false; + return isTuple ? new TupleLiteral(expressions) : expressions[0]; + } + function parseForStatement() { + const loopVariable = parseExpressionSequence(true); + if (!(loopVariable instanceof Identifier || loopVariable instanceof TupleLiteral)) { + throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${loopVariable.type} instead`); } - - _call(input_ids, scores) { - return new Array(input_ids.length).fill(this.interrupted); + if (!isIdentifier("in")) { + throw new SyntaxError("Expected `in` keyword following loop variable"); } -} - - -/***/ }), - -/***/ "./src/generation/streamers.js": -/*!*************************************!*\ - !*** ./src/generation/streamers.js ***! - \*************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ BaseStreamer: () => (/* binding */ BaseStreamer), -/* harmony export */ TextStreamer: () => (/* binding */ TextStreamer), -/* harmony export */ WhisperTextStreamer: () => (/* binding */ WhisperTextStreamer) -/* harmony export */ }); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); - -/** - * @module generation/streamers - */ - - - - - -class BaseStreamer { - /** - * Function that is called by `.generate()` to push new tokens - * @param {bigint[][]} value - */ - put(value) { - throw Error('Not implemented'); + ++current; + const iterable = parseExpression(); + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + const body = []; + while (!isStatement("endfor", "else")) { + body.push(parseAny()); } - - /** - * Function that is called by `.generate()` to signal the end of generation - */ - end() { - throw Error('Not implemented'); + const alternative = []; + if (isStatement("else")) { + ++current; + ++current; + expect(TOKEN_TYPES.CloseStatement, "Expected closing statement token"); + while (!isStatement("endfor")) { + alternative.push(parseAny()); + } } -} - -const stdout_write = _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_PROCESS_AVAILABLE - ? x => process.stdout.write(x) - : x => console.log(x); - -/** - * Simple text streamer that prints the token(s) to stdout as soon as entire words are formed. - */ -class TextStreamer extends BaseStreamer { - /** - * - * @param {import('../tokenizers.js').PreTrainedTokenizer} tokenizer - * @param {Object} options - * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens - * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding - * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display - * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated - * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method - */ - constructor(tokenizer, { - skip_prompt = false, - callback_function = null, - token_callback_function = null, - skip_special_tokens = true, - decode_kwargs = {}, - ...kwargs - } = {}) { - super(); - this.tokenizer = tokenizer; - this.skip_prompt = skip_prompt; - this.callback_function = callback_function ?? stdout_write; - this.token_callback_function = token_callback_function; - this.decode_kwargs = { skip_special_tokens, ...decode_kwargs, ...kwargs }; - - // variables used in the streaming process - this.token_cache = []; - this.print_len = 0; - this.next_tokens_are_prompt = true; + return new For(loopVariable, iterable, body, alternative); + } + function parseExpression() { + return parseIfExpression(); + } + function parseIfExpression() { + const a = parseLogicalOrExpression(); + if (isIdentifier("if")) { + ++current; + const test = parseLogicalOrExpression(); + if (isIdentifier("else")) { + ++current; + const falseExpr = parseIfExpression(); + return new Ternary(test, a, falseExpr); + } else { + return new SelectExpression(a, test); + } } - - /** - * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words. - * @param {bigint[][]} value - */ - put(value) { - if (value.length > 1) { - throw Error('TextStreamer only supports batch size of 1'); - } - - const is_prompt = this.next_tokens_are_prompt; - if (is_prompt) { - this.next_tokens_are_prompt = false; - if (this.skip_prompt) return; - } - - const tokens = value[0]; - this.token_callback_function?.(tokens) - - // Add the new token to the cache and decodes the entire thing. - this.token_cache = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_0__.mergeArrays)(this.token_cache, tokens); - const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs); - - let printable_text; - if (is_prompt || text.endsWith('\n')) { - // After the symbol for a new line, we flush the cache. - printable_text = text.slice(this.print_len); - this.token_cache = []; - this.print_len = 0; - } else if (text.length > 0 && (0,_tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.is_chinese_char)(text.charCodeAt(text.length - 1))) { - // If the last token is a CJK character, we print the characters. - printable_text = text.slice(this.print_len); - this.print_len += printable_text.length; - } else { - // Otherwise, prints until the last space char (simple heuristic to avoid printing incomplete words, - // which may change with the subsequent token -- there are probably smarter ways to do this!) - printable_text = text.slice(this.print_len, text.lastIndexOf(' ') + 1); - this.print_len += printable_text.length; - } - - this.on_finalized_text(printable_text, false); + return a; + } + function parseLogicalOrExpression() { + let left = parseLogicalAndExpression(); + while (isIdentifier("or")) { + const operator = tokens[current]; + ++current; + const right = parseLogicalAndExpression(); + left = new BinaryExpression(operator, left, right); } - - /** - * Flushes any remaining cache and prints a newline to stdout. - */ - end() { - let printable_text; - if (this.token_cache.length > 0) { - const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs); - printable_text = text.slice(this.print_len); - this.token_cache = []; - this.print_len = 0; - } else { - printable_text = ''; - } - this.next_tokens_are_prompt = true; - this.on_finalized_text(printable_text, true); + return left; + } + function parseLogicalAndExpression() { + let left = parseLogicalNegationExpression(); + while (isIdentifier("and")) { + const operator = tokens[current]; + ++current; + const right = parseLogicalNegationExpression(); + left = new BinaryExpression(operator, left, right); } - - /** - * Prints the new text to stdout. If the stream is ending, also prints a newline. - * @param {string} text - * @param {boolean} stream_end - */ - on_finalized_text(text, stream_end) { - if (text.length > 0) { - this.callback_function?.(text); - } - if (stream_end && this.callback_function === stdout_write && _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_PROCESS_AVAILABLE) { - this.callback_function?.('\n'); - } + return left; + } + function parseLogicalNegationExpression() { + let right; + while (isIdentifier("not")) { + const operator = tokens[current]; + ++current; + const arg = parseLogicalNegationExpression(); + right = new UnaryExpression(operator, arg); } -} - -/** - * Utility class to handle streaming of tokens generated by whisper speech-to-text models. - * Callback functions are invoked when each of the following events occur: - * - A new chunk starts (on_chunk_start) - * - A new token is generated (callback_function) - * - A chunk ends (on_chunk_end) - * - The stream is finalized (on_finalize) - */ -class WhisperTextStreamer extends TextStreamer { - /** - * @param {import('../tokenizers.js').WhisperTokenizer} tokenizer - * @param {Object} options - * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens - * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display - * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated - * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts - * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends - * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized - * @param {number} [options.time_precision=0.02] Precision of the timestamps - * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding - * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method - */ - constructor(tokenizer, { - skip_prompt = false, - callback_function = null, - token_callback_function = null, - on_chunk_start = null, - on_chunk_end = null, - on_finalize = null, - time_precision = 0.02, - skip_special_tokens = true, - decode_kwargs = {}, - } = {}) { - super(tokenizer, { - skip_prompt, - skip_special_tokens, - callback_function, - token_callback_function, - decode_kwargs, - }); - this.timestamp_begin = tokenizer.timestamp_begin; - - this.on_chunk_start = on_chunk_start; - this.on_chunk_end = on_chunk_end; - this.on_finalize = on_finalize; - - this.time_precision = time_precision; - - this.waiting_for_timestamp = false; + return right ?? parseComparisonExpression(); + } + function parseComparisonExpression() { + let left = parseAdditiveExpression(); + while (true) { + let operator; + if (isIdentifier("not", "in")) { + operator = new Token("not in", TOKEN_TYPES.Identifier); + current += 2; + } else if (isIdentifier("in")) { + operator = tokens[current++]; + } else if (is2(TOKEN_TYPES.ComparisonBinaryOperator)) { + operator = tokens[current++]; + } else { + break; + } + const right = parseAdditiveExpression(); + left = new BinaryExpression(operator, left, right); } - - /** - * @param {bigint[][]} value - */ - put(value) { - if (value.length > 1) { - throw Error('WhisperTextStreamer only supports batch size of 1'); - } - const tokens = value[0]; - - // Check if the token is a timestamp - if (tokens.length === 1) { - const offset = Number(tokens[0]) - this.timestamp_begin; - if (offset >= 0) { - const time = offset * this.time_precision; - if (this.waiting_for_timestamp) { - this.on_chunk_end?.(time); - } else { - this.on_chunk_start?.(time); - } - this.waiting_for_timestamp = !this.waiting_for_timestamp; // Toggle - - // NOTE: Timestamp tokens should not be printed. Although, since they - // aren't classified as "special tokens", we need to handle them here. - this.token_callback_function?.(tokens); - return; - } - } - return super.put(value); - } - - end() { - super.end(); - this.on_finalize?.(); - } -} - - -/***/ }), - -/***/ "./src/models.js": -/*!***********************!*\ - !*** ./src/models.js ***! - \***********************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ASTForAudioClassification: () => (/* binding */ ASTForAudioClassification), -/* harmony export */ ASTModel: () => (/* binding */ ASTModel), -/* harmony export */ ASTPreTrainedModel: () => (/* binding */ ASTPreTrainedModel), -/* harmony export */ AlbertForMaskedLM: () => (/* binding */ AlbertForMaskedLM), -/* harmony export */ AlbertForQuestionAnswering: () => (/* binding */ AlbertForQuestionAnswering), -/* harmony export */ AlbertForSequenceClassification: () => (/* binding */ AlbertForSequenceClassification), -/* harmony export */ AlbertModel: () => (/* binding */ AlbertModel), -/* harmony export */ AlbertPreTrainedModel: () => (/* binding */ AlbertPreTrainedModel), -/* harmony export */ ArceeForCausalLM: () => (/* binding */ ArceeForCausalLM), -/* harmony export */ ArceeModel: () => (/* binding */ ArceeModel), -/* harmony export */ ArceePreTrainedModel: () => (/* binding */ ArceePreTrainedModel), -/* harmony export */ AutoModel: () => (/* binding */ AutoModel), -/* harmony export */ AutoModelForAudioClassification: () => (/* binding */ AutoModelForAudioClassification), -/* harmony export */ AutoModelForAudioFrameClassification: () => (/* binding */ AutoModelForAudioFrameClassification), -/* harmony export */ AutoModelForAudioTextToText: () => (/* binding */ AutoModelForAudioTextToText), -/* harmony export */ AutoModelForCTC: () => (/* binding */ AutoModelForCTC), -/* harmony export */ AutoModelForCausalLM: () => (/* binding */ AutoModelForCausalLM), -/* harmony export */ AutoModelForDepthEstimation: () => (/* binding */ AutoModelForDepthEstimation), -/* harmony export */ AutoModelForDocumentQuestionAnswering: () => (/* binding */ AutoModelForDocumentQuestionAnswering), -/* harmony export */ AutoModelForImageClassification: () => (/* binding */ AutoModelForImageClassification), -/* harmony export */ AutoModelForImageFeatureExtraction: () => (/* binding */ AutoModelForImageFeatureExtraction), -/* harmony export */ AutoModelForImageMatting: () => (/* binding */ AutoModelForImageMatting), -/* harmony export */ AutoModelForImageSegmentation: () => (/* binding */ AutoModelForImageSegmentation), -/* harmony export */ AutoModelForImageTextToText: () => (/* binding */ AutoModelForImageTextToText), -/* harmony export */ AutoModelForImageToImage: () => (/* binding */ AutoModelForImageToImage), -/* harmony export */ AutoModelForMaskGeneration: () => (/* binding */ AutoModelForMaskGeneration), -/* harmony export */ AutoModelForMaskedLM: () => (/* binding */ AutoModelForMaskedLM), -/* harmony export */ AutoModelForNormalEstimation: () => (/* binding */ AutoModelForNormalEstimation), -/* harmony export */ AutoModelForObjectDetection: () => (/* binding */ AutoModelForObjectDetection), -/* harmony export */ AutoModelForPoseEstimation: () => (/* binding */ AutoModelForPoseEstimation), -/* harmony export */ AutoModelForQuestionAnswering: () => (/* binding */ AutoModelForQuestionAnswering), -/* harmony export */ AutoModelForSemanticSegmentation: () => (/* binding */ AutoModelForSemanticSegmentation), -/* harmony export */ AutoModelForSeq2SeqLM: () => (/* binding */ AutoModelForSeq2SeqLM), -/* harmony export */ AutoModelForSequenceClassification: () => (/* binding */ AutoModelForSequenceClassification), -/* harmony export */ AutoModelForSpeechSeq2Seq: () => (/* binding */ AutoModelForSpeechSeq2Seq), -/* harmony export */ AutoModelForTextToSpectrogram: () => (/* binding */ AutoModelForTextToSpectrogram), -/* harmony export */ AutoModelForTextToWaveform: () => (/* binding */ AutoModelForTextToWaveform), -/* harmony export */ AutoModelForTokenClassification: () => (/* binding */ AutoModelForTokenClassification), -/* harmony export */ AutoModelForUniversalSegmentation: () => (/* binding */ AutoModelForUniversalSegmentation), -/* harmony export */ AutoModelForVision2Seq: () => (/* binding */ AutoModelForVision2Seq), -/* harmony export */ AutoModelForXVector: () => (/* binding */ AutoModelForXVector), -/* harmony export */ AutoModelForZeroShotObjectDetection: () => (/* binding */ AutoModelForZeroShotObjectDetection), -/* harmony export */ BartForConditionalGeneration: () => (/* binding */ BartForConditionalGeneration), -/* harmony export */ BartForSequenceClassification: () => (/* binding */ BartForSequenceClassification), -/* harmony export */ BartModel: () => (/* binding */ BartModel), -/* harmony export */ BartPretrainedModel: () => (/* binding */ BartPretrainedModel), -/* harmony export */ BaseModelOutput: () => (/* binding */ BaseModelOutput), -/* harmony export */ BeitForImageClassification: () => (/* binding */ BeitForImageClassification), -/* harmony export */ BeitModel: () => (/* binding */ BeitModel), -/* harmony export */ BeitPreTrainedModel: () => (/* binding */ BeitPreTrainedModel), -/* harmony export */ BertForMaskedLM: () => (/* binding */ BertForMaskedLM), -/* harmony export */ BertForQuestionAnswering: () => (/* binding */ BertForQuestionAnswering), -/* harmony export */ BertForSequenceClassification: () => (/* binding */ BertForSequenceClassification), -/* harmony export */ BertForTokenClassification: () => (/* binding */ BertForTokenClassification), -/* harmony export */ BertModel: () => (/* binding */ BertModel), -/* harmony export */ BertPreTrainedModel: () => (/* binding */ BertPreTrainedModel), -/* harmony export */ BlenderbotForConditionalGeneration: () => (/* binding */ BlenderbotForConditionalGeneration), -/* harmony export */ BlenderbotModel: () => (/* binding */ BlenderbotModel), -/* harmony export */ BlenderbotPreTrainedModel: () => (/* binding */ BlenderbotPreTrainedModel), -/* harmony export */ BlenderbotSmallForConditionalGeneration: () => (/* binding */ BlenderbotSmallForConditionalGeneration), -/* harmony export */ BlenderbotSmallModel: () => (/* binding */ BlenderbotSmallModel), -/* harmony export */ BlenderbotSmallPreTrainedModel: () => (/* binding */ BlenderbotSmallPreTrainedModel), -/* harmony export */ BloomForCausalLM: () => (/* binding */ BloomForCausalLM), -/* harmony export */ BloomModel: () => (/* binding */ BloomModel), -/* harmony export */ BloomPreTrainedModel: () => (/* binding */ BloomPreTrainedModel), -/* harmony export */ CLIPModel: () => (/* binding */ CLIPModel), -/* harmony export */ CLIPPreTrainedModel: () => (/* binding */ CLIPPreTrainedModel), -/* harmony export */ CLIPSegForImageSegmentation: () => (/* binding */ CLIPSegForImageSegmentation), -/* harmony export */ CLIPSegModel: () => (/* binding */ CLIPSegModel), -/* harmony export */ CLIPSegPreTrainedModel: () => (/* binding */ CLIPSegPreTrainedModel), -/* harmony export */ CLIPTextModel: () => (/* binding */ CLIPTextModel), -/* harmony export */ CLIPTextModelWithProjection: () => (/* binding */ CLIPTextModelWithProjection), -/* harmony export */ CLIPVisionModel: () => (/* binding */ CLIPVisionModel), -/* harmony export */ CLIPVisionModelWithProjection: () => (/* binding */ CLIPVisionModelWithProjection), -/* harmony export */ CamembertForMaskedLM: () => (/* binding */ CamembertForMaskedLM), -/* harmony export */ CamembertForQuestionAnswering: () => (/* binding */ CamembertForQuestionAnswering), -/* harmony export */ CamembertForSequenceClassification: () => (/* binding */ CamembertForSequenceClassification), -/* harmony export */ CamembertForTokenClassification: () => (/* binding */ CamembertForTokenClassification), -/* harmony export */ CamembertModel: () => (/* binding */ CamembertModel), -/* harmony export */ CamembertPreTrainedModel: () => (/* binding */ CamembertPreTrainedModel), -/* harmony export */ CausalLMOutput: () => (/* binding */ CausalLMOutput), -/* harmony export */ CausalLMOutputWithPast: () => (/* binding */ CausalLMOutputWithPast), -/* harmony export */ ChineseCLIPModel: () => (/* binding */ ChineseCLIPModel), -/* harmony export */ ChineseCLIPPreTrainedModel: () => (/* binding */ ChineseCLIPPreTrainedModel), -/* harmony export */ ClapAudioModelWithProjection: () => (/* binding */ ClapAudioModelWithProjection), -/* harmony export */ ClapModel: () => (/* binding */ ClapModel), -/* harmony export */ ClapPreTrainedModel: () => (/* binding */ ClapPreTrainedModel), -/* harmony export */ ClapTextModelWithProjection: () => (/* binding */ ClapTextModelWithProjection), -/* harmony export */ CodeGenForCausalLM: () => (/* binding */ CodeGenForCausalLM), -/* harmony export */ CodeGenModel: () => (/* binding */ CodeGenModel), -/* harmony export */ CodeGenPreTrainedModel: () => (/* binding */ CodeGenPreTrainedModel), -/* harmony export */ CohereForCausalLM: () => (/* binding */ CohereForCausalLM), -/* harmony export */ CohereModel: () => (/* binding */ CohereModel), -/* harmony export */ CoherePreTrainedModel: () => (/* binding */ CoherePreTrainedModel), -/* harmony export */ ConvBertForMaskedLM: () => (/* binding */ ConvBertForMaskedLM), -/* harmony export */ ConvBertForQuestionAnswering: () => (/* binding */ ConvBertForQuestionAnswering), -/* harmony export */ ConvBertForSequenceClassification: () => (/* binding */ ConvBertForSequenceClassification), -/* harmony export */ ConvBertForTokenClassification: () => (/* binding */ ConvBertForTokenClassification), -/* harmony export */ ConvBertModel: () => (/* binding */ ConvBertModel), -/* harmony export */ ConvBertPreTrainedModel: () => (/* binding */ ConvBertPreTrainedModel), -/* harmony export */ ConvNextForImageClassification: () => (/* binding */ ConvNextForImageClassification), -/* harmony export */ ConvNextModel: () => (/* binding */ ConvNextModel), -/* harmony export */ ConvNextPreTrainedModel: () => (/* binding */ ConvNextPreTrainedModel), -/* harmony export */ ConvNextV2ForImageClassification: () => (/* binding */ ConvNextV2ForImageClassification), -/* harmony export */ ConvNextV2Model: () => (/* binding */ ConvNextV2Model), -/* harmony export */ ConvNextV2PreTrainedModel: () => (/* binding */ ConvNextV2PreTrainedModel), -/* harmony export */ DFineForObjectDetection: () => (/* binding */ DFineForObjectDetection), -/* harmony export */ DFineModel: () => (/* binding */ DFineModel), -/* harmony export */ DFinePreTrainedModel: () => (/* binding */ DFinePreTrainedModel), -/* harmony export */ DINOv3ConvNextModel: () => (/* binding */ DINOv3ConvNextModel), -/* harmony export */ DINOv3ConvNextPreTrainedModel: () => (/* binding */ DINOv3ConvNextPreTrainedModel), -/* harmony export */ DINOv3ViTModel: () => (/* binding */ DINOv3ViTModel), -/* harmony export */ DINOv3ViTPreTrainedModel: () => (/* binding */ DINOv3ViTPreTrainedModel), -/* harmony export */ DPTForDepthEstimation: () => (/* binding */ DPTForDepthEstimation), -/* harmony export */ DPTModel: () => (/* binding */ DPTModel), -/* harmony export */ DPTPreTrainedModel: () => (/* binding */ DPTPreTrainedModel), -/* harmony export */ DacDecoderModel: () => (/* binding */ DacDecoderModel), -/* harmony export */ DacDecoderOutput: () => (/* binding */ DacDecoderOutput), -/* harmony export */ DacEncoderModel: () => (/* binding */ DacEncoderModel), -/* harmony export */ DacEncoderOutput: () => (/* binding */ DacEncoderOutput), -/* harmony export */ DacModel: () => (/* binding */ DacModel), -/* harmony export */ DacPreTrainedModel: () => (/* binding */ DacPreTrainedModel), -/* harmony export */ DebertaForMaskedLM: () => (/* binding */ DebertaForMaskedLM), -/* harmony export */ DebertaForQuestionAnswering: () => (/* binding */ DebertaForQuestionAnswering), -/* harmony export */ DebertaForSequenceClassification: () => (/* binding */ DebertaForSequenceClassification), -/* harmony export */ DebertaForTokenClassification: () => (/* binding */ DebertaForTokenClassification), -/* harmony export */ DebertaModel: () => (/* binding */ DebertaModel), -/* harmony export */ DebertaPreTrainedModel: () => (/* binding */ DebertaPreTrainedModel), -/* harmony export */ DebertaV2ForMaskedLM: () => (/* binding */ DebertaV2ForMaskedLM), -/* harmony export */ DebertaV2ForQuestionAnswering: () => (/* binding */ DebertaV2ForQuestionAnswering), -/* harmony export */ DebertaV2ForSequenceClassification: () => (/* binding */ DebertaV2ForSequenceClassification), -/* harmony export */ DebertaV2ForTokenClassification: () => (/* binding */ DebertaV2ForTokenClassification), -/* harmony export */ DebertaV2Model: () => (/* binding */ DebertaV2Model), -/* harmony export */ DebertaV2PreTrainedModel: () => (/* binding */ DebertaV2PreTrainedModel), -/* harmony export */ DecisionTransformerModel: () => (/* binding */ DecisionTransformerModel), -/* harmony export */ DecisionTransformerPreTrainedModel: () => (/* binding */ DecisionTransformerPreTrainedModel), -/* harmony export */ DeiTForImageClassification: () => (/* binding */ DeiTForImageClassification), -/* harmony export */ DeiTModel: () => (/* binding */ DeiTModel), -/* harmony export */ DeiTPreTrainedModel: () => (/* binding */ DeiTPreTrainedModel), -/* harmony export */ DepthAnythingForDepthEstimation: () => (/* binding */ DepthAnythingForDepthEstimation), -/* harmony export */ DepthAnythingPreTrainedModel: () => (/* binding */ DepthAnythingPreTrainedModel), -/* harmony export */ DepthProForDepthEstimation: () => (/* binding */ DepthProForDepthEstimation), -/* harmony export */ DepthProPreTrainedModel: () => (/* binding */ DepthProPreTrainedModel), -/* harmony export */ DetrForObjectDetection: () => (/* binding */ DetrForObjectDetection), -/* harmony export */ DetrForSegmentation: () => (/* binding */ DetrForSegmentation), -/* harmony export */ DetrModel: () => (/* binding */ DetrModel), -/* harmony export */ DetrObjectDetectionOutput: () => (/* binding */ DetrObjectDetectionOutput), -/* harmony export */ DetrPreTrainedModel: () => (/* binding */ DetrPreTrainedModel), -/* harmony export */ DetrSegmentationOutput: () => (/* binding */ DetrSegmentationOutput), -/* harmony export */ Dinov2ForImageClassification: () => (/* binding */ Dinov2ForImageClassification), -/* harmony export */ Dinov2Model: () => (/* binding */ Dinov2Model), -/* harmony export */ Dinov2PreTrainedModel: () => (/* binding */ Dinov2PreTrainedModel), -/* harmony export */ Dinov2WithRegistersForImageClassification: () => (/* binding */ Dinov2WithRegistersForImageClassification), -/* harmony export */ Dinov2WithRegistersModel: () => (/* binding */ Dinov2WithRegistersModel), -/* harmony export */ Dinov2WithRegistersPreTrainedModel: () => (/* binding */ Dinov2WithRegistersPreTrainedModel), -/* harmony export */ DistilBertForMaskedLM: () => (/* binding */ DistilBertForMaskedLM), -/* harmony export */ DistilBertForQuestionAnswering: () => (/* binding */ DistilBertForQuestionAnswering), -/* harmony export */ DistilBertForSequenceClassification: () => (/* binding */ DistilBertForSequenceClassification), -/* harmony export */ DistilBertForTokenClassification: () => (/* binding */ DistilBertForTokenClassification), -/* harmony export */ DistilBertModel: () => (/* binding */ DistilBertModel), -/* harmony export */ DistilBertPreTrainedModel: () => (/* binding */ DistilBertPreTrainedModel), -/* harmony export */ DonutSwinModel: () => (/* binding */ DonutSwinModel), -/* harmony export */ DonutSwinPreTrainedModel: () => (/* binding */ DonutSwinPreTrainedModel), -/* harmony export */ EfficientNetForImageClassification: () => (/* binding */ EfficientNetForImageClassification), -/* harmony export */ EfficientNetModel: () => (/* binding */ EfficientNetModel), -/* harmony export */ EfficientNetPreTrainedModel: () => (/* binding */ EfficientNetPreTrainedModel), -/* harmony export */ ElectraForMaskedLM: () => (/* binding */ ElectraForMaskedLM), -/* harmony export */ ElectraForQuestionAnswering: () => (/* binding */ ElectraForQuestionAnswering), -/* harmony export */ ElectraForSequenceClassification: () => (/* binding */ ElectraForSequenceClassification), -/* harmony export */ ElectraForTokenClassification: () => (/* binding */ ElectraForTokenClassification), -/* harmony export */ ElectraModel: () => (/* binding */ ElectraModel), -/* harmony export */ ElectraPreTrainedModel: () => (/* binding */ ElectraPreTrainedModel), -/* harmony export */ Ernie4_5_ForCausalLM: () => (/* binding */ Ernie4_5_ForCausalLM), -/* harmony export */ Ernie4_5_Model: () => (/* binding */ Ernie4_5_Model), -/* harmony export */ Ernie4_5_PretrainedModel: () => (/* binding */ Ernie4_5_PretrainedModel), -/* harmony export */ EsmForMaskedLM: () => (/* binding */ EsmForMaskedLM), -/* harmony export */ EsmForSequenceClassification: () => (/* binding */ EsmForSequenceClassification), -/* harmony export */ EsmForTokenClassification: () => (/* binding */ EsmForTokenClassification), -/* harmony export */ EsmModel: () => (/* binding */ EsmModel), -/* harmony export */ EsmPreTrainedModel: () => (/* binding */ EsmPreTrainedModel), -/* harmony export */ ExaoneForCausalLM: () => (/* binding */ ExaoneForCausalLM), -/* harmony export */ ExaoneModel: () => (/* binding */ ExaoneModel), -/* harmony export */ ExaonePreTrainedModel: () => (/* binding */ ExaonePreTrainedModel), -/* harmony export */ FalconForCausalLM: () => (/* binding */ FalconForCausalLM), -/* harmony export */ FalconModel: () => (/* binding */ FalconModel), -/* harmony export */ FalconPreTrainedModel: () => (/* binding */ FalconPreTrainedModel), -/* harmony export */ FastViTForImageClassification: () => (/* binding */ FastViTForImageClassification), -/* harmony export */ FastViTModel: () => (/* binding */ FastViTModel), -/* harmony export */ FastViTPreTrainedModel: () => (/* binding */ FastViTPreTrainedModel), -/* harmony export */ Florence2ForConditionalGeneration: () => (/* binding */ Florence2ForConditionalGeneration), -/* harmony export */ Florence2PreTrainedModel: () => (/* binding */ Florence2PreTrainedModel), -/* harmony export */ GLPNForDepthEstimation: () => (/* binding */ GLPNForDepthEstimation), -/* harmony export */ GLPNModel: () => (/* binding */ GLPNModel), -/* harmony export */ GLPNPreTrainedModel: () => (/* binding */ GLPNPreTrainedModel), -/* harmony export */ GPT2LMHeadModel: () => (/* binding */ GPT2LMHeadModel), -/* harmony export */ GPT2Model: () => (/* binding */ GPT2Model), -/* harmony export */ GPT2PreTrainedModel: () => (/* binding */ GPT2PreTrainedModel), -/* harmony export */ GPTBigCodeForCausalLM: () => (/* binding */ GPTBigCodeForCausalLM), -/* harmony export */ GPTBigCodeModel: () => (/* binding */ GPTBigCodeModel), -/* harmony export */ GPTBigCodePreTrainedModel: () => (/* binding */ GPTBigCodePreTrainedModel), -/* harmony export */ GPTJForCausalLM: () => (/* binding */ GPTJForCausalLM), -/* harmony export */ GPTJModel: () => (/* binding */ GPTJModel), -/* harmony export */ GPTJPreTrainedModel: () => (/* binding */ GPTJPreTrainedModel), -/* harmony export */ GPTNeoForCausalLM: () => (/* binding */ GPTNeoForCausalLM), -/* harmony export */ GPTNeoModel: () => (/* binding */ GPTNeoModel), -/* harmony export */ GPTNeoPreTrainedModel: () => (/* binding */ GPTNeoPreTrainedModel), -/* harmony export */ GPTNeoXForCausalLM: () => (/* binding */ GPTNeoXForCausalLM), -/* harmony export */ GPTNeoXModel: () => (/* binding */ GPTNeoXModel), -/* harmony export */ GPTNeoXPreTrainedModel: () => (/* binding */ GPTNeoXPreTrainedModel), -/* harmony export */ Gemma2ForCausalLM: () => (/* binding */ Gemma2ForCausalLM), -/* harmony export */ Gemma2Model: () => (/* binding */ Gemma2Model), -/* harmony export */ Gemma2PreTrainedModel: () => (/* binding */ Gemma2PreTrainedModel), -/* harmony export */ Gemma3ForCausalLM: () => (/* binding */ Gemma3ForCausalLM), -/* harmony export */ Gemma3Model: () => (/* binding */ Gemma3Model), -/* harmony export */ Gemma3PreTrainedModel: () => (/* binding */ Gemma3PreTrainedModel), -/* harmony export */ Gemma3nForConditionalGeneration: () => (/* binding */ Gemma3nForConditionalGeneration), -/* harmony export */ Gemma3nPreTrainedModel: () => (/* binding */ Gemma3nPreTrainedModel), -/* harmony export */ GemmaForCausalLM: () => (/* binding */ GemmaForCausalLM), -/* harmony export */ GemmaModel: () => (/* binding */ GemmaModel), -/* harmony export */ GemmaPreTrainedModel: () => (/* binding */ GemmaPreTrainedModel), -/* harmony export */ GlmForCausalLM: () => (/* binding */ GlmForCausalLM), -/* harmony export */ GlmModel: () => (/* binding */ GlmModel), -/* harmony export */ GlmPreTrainedModel: () => (/* binding */ GlmPreTrainedModel), -/* harmony export */ GraniteForCausalLM: () => (/* binding */ GraniteForCausalLM), -/* harmony export */ GraniteModel: () => (/* binding */ GraniteModel), -/* harmony export */ GranitePreTrainedModel: () => (/* binding */ GranitePreTrainedModel), -/* harmony export */ GroundingDinoForObjectDetection: () => (/* binding */ GroundingDinoForObjectDetection), -/* harmony export */ GroundingDinoPreTrainedModel: () => (/* binding */ GroundingDinoPreTrainedModel), -/* harmony export */ GroupViTModel: () => (/* binding */ GroupViTModel), -/* harmony export */ GroupViTPreTrainedModel: () => (/* binding */ GroupViTPreTrainedModel), -/* harmony export */ HeliumForCausalLM: () => (/* binding */ HeliumForCausalLM), -/* harmony export */ HeliumModel: () => (/* binding */ HeliumModel), -/* harmony export */ HeliumPreTrainedModel: () => (/* binding */ HeliumPreTrainedModel), -/* harmony export */ HieraForImageClassification: () => (/* binding */ HieraForImageClassification), -/* harmony export */ HieraModel: () => (/* binding */ HieraModel), -/* harmony export */ HieraPreTrainedModel: () => (/* binding */ HieraPreTrainedModel), -/* harmony export */ HubertForCTC: () => (/* binding */ HubertForCTC), -/* harmony export */ HubertForSequenceClassification: () => (/* binding */ HubertForSequenceClassification), -/* harmony export */ HubertModel: () => (/* binding */ HubertModel), -/* harmony export */ HubertPreTrainedModel: () => (/* binding */ HubertPreTrainedModel), -/* harmony export */ IJepaForImageClassification: () => (/* binding */ IJepaForImageClassification), -/* harmony export */ IJepaModel: () => (/* binding */ IJepaModel), -/* harmony export */ IJepaPreTrainedModel: () => (/* binding */ IJepaPreTrainedModel), -/* harmony export */ Idefics3ForConditionalGeneration: () => (/* binding */ Idefics3ForConditionalGeneration), -/* harmony export */ Idefics3PreTrainedModel: () => (/* binding */ Idefics3PreTrainedModel), -/* harmony export */ ImageMattingOutput: () => (/* binding */ ImageMattingOutput), -/* harmony export */ JAISLMHeadModel: () => (/* binding */ JAISLMHeadModel), -/* harmony export */ JAISModel: () => (/* binding */ JAISModel), -/* harmony export */ JAISPreTrainedModel: () => (/* binding */ JAISPreTrainedModel), -/* harmony export */ JinaCLIPModel: () => (/* binding */ JinaCLIPModel), -/* harmony export */ JinaCLIPPreTrainedModel: () => (/* binding */ JinaCLIPPreTrainedModel), -/* harmony export */ JinaCLIPTextModel: () => (/* binding */ JinaCLIPTextModel), -/* harmony export */ JinaCLIPVisionModel: () => (/* binding */ JinaCLIPVisionModel), -/* harmony export */ Lfm2ForCausalLM: () => (/* binding */ Lfm2ForCausalLM), -/* harmony export */ Lfm2Model: () => (/* binding */ Lfm2Model), -/* harmony export */ Lfm2PreTrainedModel: () => (/* binding */ Lfm2PreTrainedModel), -/* harmony export */ LiteWhisperForConditionalGeneration: () => (/* binding */ LiteWhisperForConditionalGeneration), -/* harmony export */ LlamaForCausalLM: () => (/* binding */ LlamaForCausalLM), -/* harmony export */ LlamaModel: () => (/* binding */ LlamaModel), -/* harmony export */ LlamaPreTrainedModel: () => (/* binding */ LlamaPreTrainedModel), -/* harmony export */ LlavaForConditionalGeneration: () => (/* binding */ LlavaForConditionalGeneration), -/* harmony export */ LlavaOnevisionForConditionalGeneration: () => (/* binding */ LlavaOnevisionForConditionalGeneration), -/* harmony export */ LlavaPreTrainedModel: () => (/* binding */ LlavaPreTrainedModel), -/* harmony export */ LlavaQwen2ForCausalLM: () => (/* binding */ LlavaQwen2ForCausalLM), -/* harmony export */ LongT5ForConditionalGeneration: () => (/* binding */ LongT5ForConditionalGeneration), -/* harmony export */ LongT5Model: () => (/* binding */ LongT5Model), -/* harmony export */ LongT5PreTrainedModel: () => (/* binding */ LongT5PreTrainedModel), -/* harmony export */ M2M100ForConditionalGeneration: () => (/* binding */ M2M100ForConditionalGeneration), -/* harmony export */ M2M100Model: () => (/* binding */ M2M100Model), -/* harmony export */ M2M100PreTrainedModel: () => (/* binding */ M2M100PreTrainedModel), -/* harmony export */ MBartForCausalLM: () => (/* binding */ MBartForCausalLM), -/* harmony export */ MBartForConditionalGeneration: () => (/* binding */ MBartForConditionalGeneration), -/* harmony export */ MBartForSequenceClassification: () => (/* binding */ MBartForSequenceClassification), -/* harmony export */ MBartModel: () => (/* binding */ MBartModel), -/* harmony export */ MBartPreTrainedModel: () => (/* binding */ MBartPreTrainedModel), -/* harmony export */ MPNetForMaskedLM: () => (/* binding */ MPNetForMaskedLM), -/* harmony export */ MPNetForQuestionAnswering: () => (/* binding */ MPNetForQuestionAnswering), -/* harmony export */ MPNetForSequenceClassification: () => (/* binding */ MPNetForSequenceClassification), -/* harmony export */ MPNetForTokenClassification: () => (/* binding */ MPNetForTokenClassification), -/* harmony export */ MPNetModel: () => (/* binding */ MPNetModel), -/* harmony export */ MPNetPreTrainedModel: () => (/* binding */ MPNetPreTrainedModel), -/* harmony export */ MT5ForConditionalGeneration: () => (/* binding */ MT5ForConditionalGeneration), -/* harmony export */ MT5Model: () => (/* binding */ MT5Model), -/* harmony export */ MT5PreTrainedModel: () => (/* binding */ MT5PreTrainedModel), -/* harmony export */ MarianMTModel: () => (/* binding */ MarianMTModel), -/* harmony export */ MarianModel: () => (/* binding */ MarianModel), -/* harmony export */ MarianPreTrainedModel: () => (/* binding */ MarianPreTrainedModel), -/* harmony export */ MaskFormerForInstanceSegmentation: () => (/* binding */ MaskFormerForInstanceSegmentation), -/* harmony export */ MaskFormerModel: () => (/* binding */ MaskFormerModel), -/* harmony export */ MaskFormerPreTrainedModel: () => (/* binding */ MaskFormerPreTrainedModel), -/* harmony export */ MaskedLMOutput: () => (/* binding */ MaskedLMOutput), -/* harmony export */ Metric3DForDepthEstimation: () => (/* binding */ Metric3DForDepthEstimation), -/* harmony export */ Metric3DPreTrainedModel: () => (/* binding */ Metric3DPreTrainedModel), -/* harmony export */ Metric3Dv2ForDepthEstimation: () => (/* binding */ Metric3Dv2ForDepthEstimation), -/* harmony export */ Metric3Dv2PreTrainedModel: () => (/* binding */ Metric3Dv2PreTrainedModel), -/* harmony export */ MgpstrForSceneTextRecognition: () => (/* binding */ MgpstrForSceneTextRecognition), -/* harmony export */ MgpstrModelOutput: () => (/* binding */ MgpstrModelOutput), -/* harmony export */ MgpstrPreTrainedModel: () => (/* binding */ MgpstrPreTrainedModel), -/* harmony export */ MimiDecoderModel: () => (/* binding */ MimiDecoderModel), -/* harmony export */ MimiDecoderOutput: () => (/* binding */ MimiDecoderOutput), -/* harmony export */ MimiEncoderModel: () => (/* binding */ MimiEncoderModel), -/* harmony export */ MimiEncoderOutput: () => (/* binding */ MimiEncoderOutput), -/* harmony export */ MimiModel: () => (/* binding */ MimiModel), -/* harmony export */ MimiPreTrainedModel: () => (/* binding */ MimiPreTrainedModel), -/* harmony export */ MistralForCausalLM: () => (/* binding */ MistralForCausalLM), -/* harmony export */ MistralModel: () => (/* binding */ MistralModel), -/* harmony export */ MistralPreTrainedModel: () => (/* binding */ MistralPreTrainedModel), -/* harmony export */ MobileBertForMaskedLM: () => (/* binding */ MobileBertForMaskedLM), -/* harmony export */ MobileBertForQuestionAnswering: () => (/* binding */ MobileBertForQuestionAnswering), -/* harmony export */ MobileBertForSequenceClassification: () => (/* binding */ MobileBertForSequenceClassification), -/* harmony export */ MobileBertModel: () => (/* binding */ MobileBertModel), -/* harmony export */ MobileBertPreTrainedModel: () => (/* binding */ MobileBertPreTrainedModel), -/* harmony export */ MobileLLMForCausalLM: () => (/* binding */ MobileLLMForCausalLM), -/* harmony export */ MobileLLMModel: () => (/* binding */ MobileLLMModel), -/* harmony export */ MobileLLMPreTrainedModel: () => (/* binding */ MobileLLMPreTrainedModel), -/* harmony export */ MobileNetV1ForImageClassification: () => (/* binding */ MobileNetV1ForImageClassification), -/* harmony export */ MobileNetV1ForSemanticSegmentation: () => (/* binding */ MobileNetV1ForSemanticSegmentation), -/* harmony export */ MobileNetV1Model: () => (/* binding */ MobileNetV1Model), -/* harmony export */ MobileNetV1PreTrainedModel: () => (/* binding */ MobileNetV1PreTrainedModel), -/* harmony export */ MobileNetV2ForImageClassification: () => (/* binding */ MobileNetV2ForImageClassification), -/* harmony export */ MobileNetV2ForSemanticSegmentation: () => (/* binding */ MobileNetV2ForSemanticSegmentation), -/* harmony export */ MobileNetV2Model: () => (/* binding */ MobileNetV2Model), -/* harmony export */ MobileNetV2PreTrainedModel: () => (/* binding */ MobileNetV2PreTrainedModel), -/* harmony export */ MobileNetV3ForImageClassification: () => (/* binding */ MobileNetV3ForImageClassification), -/* harmony export */ MobileNetV3ForSemanticSegmentation: () => (/* binding */ MobileNetV3ForSemanticSegmentation), -/* harmony export */ MobileNetV3Model: () => (/* binding */ MobileNetV3Model), -/* harmony export */ MobileNetV3PreTrainedModel: () => (/* binding */ MobileNetV3PreTrainedModel), -/* harmony export */ MobileNetV4ForImageClassification: () => (/* binding */ MobileNetV4ForImageClassification), -/* harmony export */ MobileNetV4ForSemanticSegmentation: () => (/* binding */ MobileNetV4ForSemanticSegmentation), -/* harmony export */ MobileNetV4Model: () => (/* binding */ MobileNetV4Model), -/* harmony export */ MobileNetV4PreTrainedModel: () => (/* binding */ MobileNetV4PreTrainedModel), -/* harmony export */ MobileViTForImageClassification: () => (/* binding */ MobileViTForImageClassification), -/* harmony export */ MobileViTModel: () => (/* binding */ MobileViTModel), -/* harmony export */ MobileViTPreTrainedModel: () => (/* binding */ MobileViTPreTrainedModel), -/* harmony export */ MobileViTV2ForImageClassification: () => (/* binding */ MobileViTV2ForImageClassification), -/* harmony export */ MobileViTV2Model: () => (/* binding */ MobileViTV2Model), -/* harmony export */ MobileViTV2PreTrainedModel: () => (/* binding */ MobileViTV2PreTrainedModel), -/* harmony export */ ModelOutput: () => (/* binding */ ModelOutput), -/* harmony export */ ModernBertDecoderForCausalLM: () => (/* binding */ ModernBertDecoderForCausalLM), -/* harmony export */ ModernBertDecoderModel: () => (/* binding */ ModernBertDecoderModel), -/* harmony export */ ModernBertDecoderPreTrainedModel: () => (/* binding */ ModernBertDecoderPreTrainedModel), -/* harmony export */ ModernBertForMaskedLM: () => (/* binding */ ModernBertForMaskedLM), -/* harmony export */ ModernBertForSequenceClassification: () => (/* binding */ ModernBertForSequenceClassification), -/* harmony export */ ModernBertForTokenClassification: () => (/* binding */ ModernBertForTokenClassification), -/* harmony export */ ModernBertModel: () => (/* binding */ ModernBertModel), -/* harmony export */ ModernBertPreTrainedModel: () => (/* binding */ ModernBertPreTrainedModel), -/* harmony export */ Moondream1ForConditionalGeneration: () => (/* binding */ Moondream1ForConditionalGeneration), -/* harmony export */ MoonshineForConditionalGeneration: () => (/* binding */ MoonshineForConditionalGeneration), -/* harmony export */ MoonshineModel: () => (/* binding */ MoonshineModel), -/* harmony export */ MoonshinePreTrainedModel: () => (/* binding */ MoonshinePreTrainedModel), -/* harmony export */ MptForCausalLM: () => (/* binding */ MptForCausalLM), -/* harmony export */ MptModel: () => (/* binding */ MptModel), -/* harmony export */ MptPreTrainedModel: () => (/* binding */ MptPreTrainedModel), -/* harmony export */ MultiModalityCausalLM: () => (/* binding */ MultiModalityCausalLM), -/* harmony export */ MultiModalityPreTrainedModel: () => (/* binding */ MultiModalityPreTrainedModel), -/* harmony export */ MusicgenForCausalLM: () => (/* binding */ MusicgenForCausalLM), -/* harmony export */ MusicgenForConditionalGeneration: () => (/* binding */ MusicgenForConditionalGeneration), -/* harmony export */ MusicgenModel: () => (/* binding */ MusicgenModel), -/* harmony export */ MusicgenPreTrainedModel: () => (/* binding */ MusicgenPreTrainedModel), -/* harmony export */ NeoBertForMaskedLM: () => (/* binding */ NeoBertForMaskedLM), -/* harmony export */ NeoBertForQuestionAnswering: () => (/* binding */ NeoBertForQuestionAnswering), -/* harmony export */ NeoBertForSequenceClassification: () => (/* binding */ NeoBertForSequenceClassification), -/* harmony export */ NeoBertForTokenClassification: () => (/* binding */ NeoBertForTokenClassification), -/* harmony export */ NeoBertModel: () => (/* binding */ NeoBertModel), -/* harmony export */ NeoBertPreTrainedModel: () => (/* binding */ NeoBertPreTrainedModel), -/* harmony export */ NomicBertModel: () => (/* binding */ NomicBertModel), -/* harmony export */ NomicBertPreTrainedModel: () => (/* binding */ NomicBertPreTrainedModel), -/* harmony export */ OPTForCausalLM: () => (/* binding */ OPTForCausalLM), -/* harmony export */ OPTModel: () => (/* binding */ OPTModel), -/* harmony export */ OPTPreTrainedModel: () => (/* binding */ OPTPreTrainedModel), -/* harmony export */ Olmo2ForCausalLM: () => (/* binding */ Olmo2ForCausalLM), -/* harmony export */ Olmo2Model: () => (/* binding */ Olmo2Model), -/* harmony export */ Olmo2PreTrainedModel: () => (/* binding */ Olmo2PreTrainedModel), -/* harmony export */ OlmoForCausalLM: () => (/* binding */ OlmoForCausalLM), -/* harmony export */ OlmoModel: () => (/* binding */ OlmoModel), -/* harmony export */ OlmoPreTrainedModel: () => (/* binding */ OlmoPreTrainedModel), -/* harmony export */ OpenELMForCausalLM: () => (/* binding */ OpenELMForCausalLM), -/* harmony export */ OpenELMModel: () => (/* binding */ OpenELMModel), -/* harmony export */ OpenELMPreTrainedModel: () => (/* binding */ OpenELMPreTrainedModel), -/* harmony export */ OwlViTForObjectDetection: () => (/* binding */ OwlViTForObjectDetection), -/* harmony export */ OwlViTModel: () => (/* binding */ OwlViTModel), -/* harmony export */ OwlViTPreTrainedModel: () => (/* binding */ OwlViTPreTrainedModel), -/* harmony export */ Owlv2ForObjectDetection: () => (/* binding */ Owlv2ForObjectDetection), -/* harmony export */ Owlv2Model: () => (/* binding */ Owlv2Model), -/* harmony export */ Owlv2PreTrainedModel: () => (/* binding */ Owlv2PreTrainedModel), -/* harmony export */ PaliGemmaForConditionalGeneration: () => (/* binding */ PaliGemmaForConditionalGeneration), -/* harmony export */ PaliGemmaPreTrainedModel: () => (/* binding */ PaliGemmaPreTrainedModel), -/* harmony export */ PatchTSMixerForPrediction: () => (/* binding */ PatchTSMixerForPrediction), -/* harmony export */ PatchTSMixerModel: () => (/* binding */ PatchTSMixerModel), -/* harmony export */ PatchTSMixerPreTrainedModel: () => (/* binding */ PatchTSMixerPreTrainedModel), -/* harmony export */ PatchTSTForPrediction: () => (/* binding */ PatchTSTForPrediction), -/* harmony export */ PatchTSTModel: () => (/* binding */ PatchTSTModel), -/* harmony export */ PatchTSTPreTrainedModel: () => (/* binding */ PatchTSTPreTrainedModel), -/* harmony export */ Phi3ForCausalLM: () => (/* binding */ Phi3ForCausalLM), -/* harmony export */ Phi3Model: () => (/* binding */ Phi3Model), -/* harmony export */ Phi3PreTrainedModel: () => (/* binding */ Phi3PreTrainedModel), -/* harmony export */ Phi3VForCausalLM: () => (/* binding */ Phi3VForCausalLM), -/* harmony export */ Phi3VPreTrainedModel: () => (/* binding */ Phi3VPreTrainedModel), -/* harmony export */ PhiForCausalLM: () => (/* binding */ PhiForCausalLM), -/* harmony export */ PhiModel: () => (/* binding */ PhiModel), -/* harmony export */ PhiPreTrainedModel: () => (/* binding */ PhiPreTrainedModel), -/* harmony export */ PreTrainedModel: () => (/* binding */ PreTrainedModel), -/* harmony export */ PretrainedMixin: () => (/* binding */ PretrainedMixin), -/* harmony export */ PvtForImageClassification: () => (/* binding */ PvtForImageClassification), -/* harmony export */ PvtModel: () => (/* binding */ PvtModel), -/* harmony export */ PvtPreTrainedModel: () => (/* binding */ PvtPreTrainedModel), -/* harmony export */ PyAnnoteForAudioFrameClassification: () => (/* binding */ PyAnnoteForAudioFrameClassification), -/* harmony export */ PyAnnoteModel: () => (/* binding */ PyAnnoteModel), -/* harmony export */ PyAnnotePreTrainedModel: () => (/* binding */ PyAnnotePreTrainedModel), -/* harmony export */ QuestionAnsweringModelOutput: () => (/* binding */ QuestionAnsweringModelOutput), -/* harmony export */ Qwen2ForCausalLM: () => (/* binding */ Qwen2ForCausalLM), -/* harmony export */ Qwen2Model: () => (/* binding */ Qwen2Model), -/* harmony export */ Qwen2PreTrainedModel: () => (/* binding */ Qwen2PreTrainedModel), -/* harmony export */ Qwen2VLForConditionalGeneration: () => (/* binding */ Qwen2VLForConditionalGeneration), -/* harmony export */ Qwen2VLPreTrainedModel: () => (/* binding */ Qwen2VLPreTrainedModel), -/* harmony export */ Qwen3ForCausalLM: () => (/* binding */ Qwen3ForCausalLM), -/* harmony export */ Qwen3Model: () => (/* binding */ Qwen3Model), -/* harmony export */ Qwen3PreTrainedModel: () => (/* binding */ Qwen3PreTrainedModel), -/* harmony export */ RFDetrForObjectDetection: () => (/* binding */ RFDetrForObjectDetection), -/* harmony export */ RFDetrModel: () => (/* binding */ RFDetrModel), -/* harmony export */ RFDetrObjectDetectionOutput: () => (/* binding */ RFDetrObjectDetectionOutput), -/* harmony export */ RFDetrPreTrainedModel: () => (/* binding */ RFDetrPreTrainedModel), -/* harmony export */ RTDetrForObjectDetection: () => (/* binding */ RTDetrForObjectDetection), -/* harmony export */ RTDetrModel: () => (/* binding */ RTDetrModel), -/* harmony export */ RTDetrObjectDetectionOutput: () => (/* binding */ RTDetrObjectDetectionOutput), -/* harmony export */ RTDetrPreTrainedModel: () => (/* binding */ RTDetrPreTrainedModel), -/* harmony export */ RTDetrV2ForObjectDetection: () => (/* binding */ RTDetrV2ForObjectDetection), -/* harmony export */ RTDetrV2Model: () => (/* binding */ RTDetrV2Model), -/* harmony export */ RTDetrV2ObjectDetectionOutput: () => (/* binding */ RTDetrV2ObjectDetectionOutput), -/* harmony export */ RTDetrV2PreTrainedModel: () => (/* binding */ RTDetrV2PreTrainedModel), -/* harmony export */ ResNetForImageClassification: () => (/* binding */ ResNetForImageClassification), -/* harmony export */ ResNetModel: () => (/* binding */ ResNetModel), -/* harmony export */ ResNetPreTrainedModel: () => (/* binding */ ResNetPreTrainedModel), -/* harmony export */ RoFormerForMaskedLM: () => (/* binding */ RoFormerForMaskedLM), -/* harmony export */ RoFormerForQuestionAnswering: () => (/* binding */ RoFormerForQuestionAnswering), -/* harmony export */ RoFormerForSequenceClassification: () => (/* binding */ RoFormerForSequenceClassification), -/* harmony export */ RoFormerForTokenClassification: () => (/* binding */ RoFormerForTokenClassification), -/* harmony export */ RoFormerModel: () => (/* binding */ RoFormerModel), -/* harmony export */ RoFormerPreTrainedModel: () => (/* binding */ RoFormerPreTrainedModel), -/* harmony export */ RobertaForMaskedLM: () => (/* binding */ RobertaForMaskedLM), -/* harmony export */ RobertaForQuestionAnswering: () => (/* binding */ RobertaForQuestionAnswering), -/* harmony export */ RobertaForSequenceClassification: () => (/* binding */ RobertaForSequenceClassification), -/* harmony export */ RobertaForTokenClassification: () => (/* binding */ RobertaForTokenClassification), -/* harmony export */ RobertaModel: () => (/* binding */ RobertaModel), -/* harmony export */ RobertaPreTrainedModel: () => (/* binding */ RobertaPreTrainedModel), -/* harmony export */ SamImageSegmentationOutput: () => (/* binding */ SamImageSegmentationOutput), -/* harmony export */ SamModel: () => (/* binding */ SamModel), -/* harmony export */ SamPreTrainedModel: () => (/* binding */ SamPreTrainedModel), -/* harmony export */ SapiensForDepthEstimation: () => (/* binding */ SapiensForDepthEstimation), -/* harmony export */ SapiensForNormalEstimation: () => (/* binding */ SapiensForNormalEstimation), -/* harmony export */ SapiensForSemanticSegmentation: () => (/* binding */ SapiensForSemanticSegmentation), -/* harmony export */ SapiensPreTrainedModel: () => (/* binding */ SapiensPreTrainedModel), -/* harmony export */ SegformerForImageClassification: () => (/* binding */ SegformerForImageClassification), -/* harmony export */ SegformerForSemanticSegmentation: () => (/* binding */ SegformerForSemanticSegmentation), -/* harmony export */ SegformerModel: () => (/* binding */ SegformerModel), -/* harmony export */ SegformerPreTrainedModel: () => (/* binding */ SegformerPreTrainedModel), -/* harmony export */ Seq2SeqLMOutput: () => (/* binding */ Seq2SeqLMOutput), -/* harmony export */ SequenceClassifierOutput: () => (/* binding */ SequenceClassifierOutput), -/* harmony export */ SiglipModel: () => (/* binding */ SiglipModel), -/* harmony export */ SiglipPreTrainedModel: () => (/* binding */ SiglipPreTrainedModel), -/* harmony export */ SiglipTextModel: () => (/* binding */ SiglipTextModel), -/* harmony export */ SiglipVisionModel: () => (/* binding */ SiglipVisionModel), -/* harmony export */ SmolLM3ForCausalLM: () => (/* binding */ SmolLM3ForCausalLM), -/* harmony export */ SmolLM3Model: () => (/* binding */ SmolLM3Model), -/* harmony export */ SmolLM3PreTrainedModel: () => (/* binding */ SmolLM3PreTrainedModel), -/* harmony export */ SmolVLMForConditionalGeneration: () => (/* binding */ SmolVLMForConditionalGeneration), -/* harmony export */ SnacDecoderModel: () => (/* binding */ SnacDecoderModel), -/* harmony export */ SnacEncoderModel: () => (/* binding */ SnacEncoderModel), -/* harmony export */ SnacModel: () => (/* binding */ SnacModel), -/* harmony export */ SnacPreTrainedModel: () => (/* binding */ SnacPreTrainedModel), -/* harmony export */ SpeechT5ForSpeechToText: () => (/* binding */ SpeechT5ForSpeechToText), -/* harmony export */ SpeechT5ForTextToSpeech: () => (/* binding */ SpeechT5ForTextToSpeech), -/* harmony export */ SpeechT5HifiGan: () => (/* binding */ SpeechT5HifiGan), -/* harmony export */ SpeechT5Model: () => (/* binding */ SpeechT5Model), -/* harmony export */ SpeechT5PreTrainedModel: () => (/* binding */ SpeechT5PreTrainedModel), -/* harmony export */ SqueezeBertForMaskedLM: () => (/* binding */ SqueezeBertForMaskedLM), -/* harmony export */ SqueezeBertForQuestionAnswering: () => (/* binding */ SqueezeBertForQuestionAnswering), -/* harmony export */ SqueezeBertForSequenceClassification: () => (/* binding */ SqueezeBertForSequenceClassification), -/* harmony export */ SqueezeBertModel: () => (/* binding */ SqueezeBertModel), -/* harmony export */ SqueezeBertPreTrainedModel: () => (/* binding */ SqueezeBertPreTrainedModel), -/* harmony export */ StableLmForCausalLM: () => (/* binding */ StableLmForCausalLM), -/* harmony export */ StableLmModel: () => (/* binding */ StableLmModel), -/* harmony export */ StableLmPreTrainedModel: () => (/* binding */ StableLmPreTrainedModel), -/* harmony export */ Starcoder2ForCausalLM: () => (/* binding */ Starcoder2ForCausalLM), -/* harmony export */ Starcoder2Model: () => (/* binding */ Starcoder2Model), -/* harmony export */ Starcoder2PreTrainedModel: () => (/* binding */ Starcoder2PreTrainedModel), -/* harmony export */ StyleTextToSpeech2Model: () => (/* binding */ StyleTextToSpeech2Model), -/* harmony export */ StyleTextToSpeech2PreTrainedModel: () => (/* binding */ StyleTextToSpeech2PreTrainedModel), -/* harmony export */ Swin2SRForImageSuperResolution: () => (/* binding */ Swin2SRForImageSuperResolution), -/* harmony export */ Swin2SRModel: () => (/* binding */ Swin2SRModel), -/* harmony export */ Swin2SRPreTrainedModel: () => (/* binding */ Swin2SRPreTrainedModel), -/* harmony export */ SwinForImageClassification: () => (/* binding */ SwinForImageClassification), -/* harmony export */ SwinForSemanticSegmentation: () => (/* binding */ SwinForSemanticSegmentation), -/* harmony export */ SwinModel: () => (/* binding */ SwinModel), -/* harmony export */ SwinPreTrainedModel: () => (/* binding */ SwinPreTrainedModel), -/* harmony export */ T5ForConditionalGeneration: () => (/* binding */ T5ForConditionalGeneration), -/* harmony export */ T5Model: () => (/* binding */ T5Model), -/* harmony export */ T5PreTrainedModel: () => (/* binding */ T5PreTrainedModel), -/* harmony export */ TableTransformerForObjectDetection: () => (/* binding */ TableTransformerForObjectDetection), -/* harmony export */ TableTransformerModel: () => (/* binding */ TableTransformerModel), -/* harmony export */ TableTransformerObjectDetectionOutput: () => (/* binding */ TableTransformerObjectDetectionOutput), -/* harmony export */ TableTransformerPreTrainedModel: () => (/* binding */ TableTransformerPreTrainedModel), -/* harmony export */ TokenClassifierOutput: () => (/* binding */ TokenClassifierOutput), -/* harmony export */ TrOCRForCausalLM: () => (/* binding */ TrOCRForCausalLM), -/* harmony export */ TrOCRPreTrainedModel: () => (/* binding */ TrOCRPreTrainedModel), -/* harmony export */ UltravoxModel: () => (/* binding */ UltravoxModel), -/* harmony export */ UltravoxPreTrainedModel: () => (/* binding */ UltravoxPreTrainedModel), -/* harmony export */ UniSpeechForCTC: () => (/* binding */ UniSpeechForCTC), -/* harmony export */ UniSpeechForSequenceClassification: () => (/* binding */ UniSpeechForSequenceClassification), -/* harmony export */ UniSpeechModel: () => (/* binding */ UniSpeechModel), -/* harmony export */ UniSpeechPreTrainedModel: () => (/* binding */ UniSpeechPreTrainedModel), -/* harmony export */ UniSpeechSatForAudioFrameClassification: () => (/* binding */ UniSpeechSatForAudioFrameClassification), -/* harmony export */ UniSpeechSatForCTC: () => (/* binding */ UniSpeechSatForCTC), -/* harmony export */ UniSpeechSatForSequenceClassification: () => (/* binding */ UniSpeechSatForSequenceClassification), -/* harmony export */ UniSpeechSatModel: () => (/* binding */ UniSpeechSatModel), -/* harmony export */ UniSpeechSatPreTrainedModel: () => (/* binding */ UniSpeechSatPreTrainedModel), -/* harmony export */ ViTForImageClassification: () => (/* binding */ ViTForImageClassification), -/* harmony export */ ViTMAEModel: () => (/* binding */ ViTMAEModel), -/* harmony export */ ViTMAEPreTrainedModel: () => (/* binding */ ViTMAEPreTrainedModel), -/* harmony export */ ViTMSNForImageClassification: () => (/* binding */ ViTMSNForImageClassification), -/* harmony export */ ViTMSNModel: () => (/* binding */ ViTMSNModel), -/* harmony export */ ViTMSNPreTrainedModel: () => (/* binding */ ViTMSNPreTrainedModel), -/* harmony export */ ViTModel: () => (/* binding */ ViTModel), -/* harmony export */ ViTPreTrainedModel: () => (/* binding */ ViTPreTrainedModel), -/* harmony export */ VisionEncoderDecoderModel: () => (/* binding */ VisionEncoderDecoderModel), -/* harmony export */ VitMatteForImageMatting: () => (/* binding */ VitMatteForImageMatting), -/* harmony export */ VitMattePreTrainedModel: () => (/* binding */ VitMattePreTrainedModel), -/* harmony export */ VitPoseForPoseEstimation: () => (/* binding */ VitPoseForPoseEstimation), -/* harmony export */ VitPosePreTrainedModel: () => (/* binding */ VitPosePreTrainedModel), -/* harmony export */ VitsModel: () => (/* binding */ VitsModel), -/* harmony export */ VitsModelOutput: () => (/* binding */ VitsModelOutput), -/* harmony export */ VitsPreTrainedModel: () => (/* binding */ VitsPreTrainedModel), -/* harmony export */ VoxtralForConditionalGeneration: () => (/* binding */ VoxtralForConditionalGeneration), -/* harmony export */ Wav2Vec2BertForCTC: () => (/* binding */ Wav2Vec2BertForCTC), -/* harmony export */ Wav2Vec2BertForSequenceClassification: () => (/* binding */ Wav2Vec2BertForSequenceClassification), -/* harmony export */ Wav2Vec2BertModel: () => (/* binding */ Wav2Vec2BertModel), -/* harmony export */ Wav2Vec2BertPreTrainedModel: () => (/* binding */ Wav2Vec2BertPreTrainedModel), -/* harmony export */ Wav2Vec2ForAudioFrameClassification: () => (/* binding */ Wav2Vec2ForAudioFrameClassification), -/* harmony export */ Wav2Vec2ForCTC: () => (/* binding */ Wav2Vec2ForCTC), -/* harmony export */ Wav2Vec2ForSequenceClassification: () => (/* binding */ Wav2Vec2ForSequenceClassification), -/* harmony export */ Wav2Vec2Model: () => (/* binding */ Wav2Vec2Model), -/* harmony export */ Wav2Vec2PreTrainedModel: () => (/* binding */ Wav2Vec2PreTrainedModel), -/* harmony export */ WavLMForAudioFrameClassification: () => (/* binding */ WavLMForAudioFrameClassification), -/* harmony export */ WavLMForCTC: () => (/* binding */ WavLMForCTC), -/* harmony export */ WavLMForSequenceClassification: () => (/* binding */ WavLMForSequenceClassification), -/* harmony export */ WavLMForXVector: () => (/* binding */ WavLMForXVector), -/* harmony export */ WavLMModel: () => (/* binding */ WavLMModel), -/* harmony export */ WavLMPreTrainedModel: () => (/* binding */ WavLMPreTrainedModel), -/* harmony export */ WeSpeakerResNetModel: () => (/* binding */ WeSpeakerResNetModel), -/* harmony export */ WeSpeakerResNetPreTrainedModel: () => (/* binding */ WeSpeakerResNetPreTrainedModel), -/* harmony export */ WhisperForConditionalGeneration: () => (/* binding */ WhisperForConditionalGeneration), -/* harmony export */ WhisperModel: () => (/* binding */ WhisperModel), -/* harmony export */ WhisperPreTrainedModel: () => (/* binding */ WhisperPreTrainedModel), -/* harmony export */ XLMForQuestionAnswering: () => (/* binding */ XLMForQuestionAnswering), -/* harmony export */ XLMForSequenceClassification: () => (/* binding */ XLMForSequenceClassification), -/* harmony export */ XLMForTokenClassification: () => (/* binding */ XLMForTokenClassification), -/* harmony export */ XLMModel: () => (/* binding */ XLMModel), -/* harmony export */ XLMPreTrainedModel: () => (/* binding */ XLMPreTrainedModel), -/* harmony export */ XLMRobertaForMaskedLM: () => (/* binding */ XLMRobertaForMaskedLM), -/* harmony export */ XLMRobertaForQuestionAnswering: () => (/* binding */ XLMRobertaForQuestionAnswering), -/* harmony export */ XLMRobertaForSequenceClassification: () => (/* binding */ XLMRobertaForSequenceClassification), -/* harmony export */ XLMRobertaForTokenClassification: () => (/* binding */ XLMRobertaForTokenClassification), -/* harmony export */ XLMRobertaModel: () => (/* binding */ XLMRobertaModel), -/* harmony export */ XLMRobertaPreTrainedModel: () => (/* binding */ XLMRobertaPreTrainedModel), -/* harmony export */ XLMWithLMHeadModel: () => (/* binding */ XLMWithLMHeadModel), -/* harmony export */ XVectorOutput: () => (/* binding */ XVectorOutput), -/* harmony export */ YolosForObjectDetection: () => (/* binding */ YolosForObjectDetection), -/* harmony export */ YolosModel: () => (/* binding */ YolosModel), -/* harmony export */ YolosObjectDetectionOutput: () => (/* binding */ YolosObjectDetectionOutput), -/* harmony export */ YolosPreTrainedModel: () => (/* binding */ YolosPreTrainedModel) -/* harmony export */ }); -/* harmony import */ var _configs_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./configs.js */ "./src/configs.js"); -/* harmony import */ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./backends/onnx.js */ "./src/backends/onnx.js"); -/* harmony import */ var _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/dtypes.js */ "./src/utils/dtypes.js"); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/constants.js */ "./src/utils/constants.js"); -/* harmony import */ var _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./generation/logits_process.js */ "./src/generation/logits_process.js"); -/* harmony import */ var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./generation/configuration_utils.js */ "./src/generation/configuration_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/image.js */ "./src/utils/image.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./generation/stopping_criteria.js */ "./src/generation/stopping_criteria.js"); -/* harmony import */ var _generation_logits_sampler_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./generation/logits_sampler.js */ "./src/generation/logits_sampler.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./env.js */ "./src/env.js"); -/* harmony import */ var _models_whisper_generation_whisper_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./models/whisper/generation_whisper.js */ "./src/models/whisper/generation_whisper.js"); -/* harmony import */ var _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./models/whisper/common_whisper.js */ "./src/models/whisper/common_whisper.js"); - -/** - * @file Definitions of all models available in Transformers.js. - * - * **Example:** Load and run an `AutoModel`. - * - * ```javascript - * import { AutoModel, AutoTokenizer } from '@huggingface/transformers'; - * - * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); - * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased'); - * - * let inputs = await tokenizer('I love transformers!'); - * let { logits } = await model(inputs); - * // Tensor { - * // data: Float32Array(183132) [-7.117443084716797, -7.107812881469727, -7.092104911804199, ...] - * // dims: (3) [1, 6, 30522], - * // type: "float32", - * // size: 183132, - * // } - * ``` - * - * We also provide other `AutoModel`s (listed below), which you can use in the same way as the Python library. For example: - * - * **Example:** Load and run an `AutoModelForSeq2SeqLM`. - * ```javascript - * import { AutoModelForSeq2SeqLM, AutoTokenizer } from '@huggingface/transformers'; - * - * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/t5-small'); - * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small'); - * - * let { input_ids } = await tokenizer('translate English to German: I love transformers!'); - * let outputs = await model.generate(input_ids); - * let decoded = tokenizer.decode(outputs[0], { skip_special_tokens: true }); - * // 'Ich liebe Transformatoren!' - * ``` - * - * @module models - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -////////////////////////////////////////////////// -// Model types: used internally -const MODEL_TYPES = { - EncoderOnly: 0, - EncoderDecoder: 1, - Seq2Seq: 2, - Vision2Seq: 3, - DecoderOnly: 4, - MaskGeneration: 5, - ImageTextToText: 6, - Musicgen: 7, - MultiModality: 8, - Phi3V: 9, - AudioTextToText: 10, - AutoEncoder: 11, - ImageAudioTextToText: 12, -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Helper functions - -// NOTE: These will be populated fully later -const MODEL_TYPE_MAPPING = new Map(); -const MODEL_NAME_TO_CLASS_MAPPING = new Map(); -const MODEL_CLASS_TO_NAME_MAPPING = new Map(); - - -/** - * Constructs an InferenceSession using a model file located at the specified path. - * @param {string} pretrained_model_name_or_path The path to the directory containing the model file. - * @param {string} fileName The name of the model file. - * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model. - * @returns {Promise<{buffer_or_path: Uint8Array|string, session_options: Object, session_config: Object}>} A Promise that resolves to the data needed to create an InferenceSession object. - * @private - */ -async function getSession(pretrained_model_name_or_path, fileName, options) { - let custom_config = options.config?.['transformers.js_config'] ?? {}; - - let device = options.device ?? custom_config.device; - if (device && typeof device !== 'string') { - if (device.hasOwnProperty(fileName)) { - device = device[fileName]; - } else { - console.warn(`device not specified for "${fileName}". Using the default device.`); - device = null; - } + return left; + } + function parseAdditiveExpression() { + let left = parseMultiplicativeExpression(); + while (is2(TOKEN_TYPES.AdditiveBinaryOperator)) { + const operator = tokens[current]; + ++current; + const right = parseMultiplicativeExpression(); + left = new BinaryExpression(operator, left, right); } - - // If the device is not specified, we use the default (supported) execution providers. - const selectedDevice = /** @type {import("./utils/devices.js").DeviceType} */( - device ?? (_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV ? 'cpu' : 'wasm') - ); - - const executionProviders = (0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.deviceToExecutionProviders)(selectedDevice); - - // Update custom config with the selected device's config, if it exists - const device_config = custom_config.device_config ?? {}; - if (device_config.hasOwnProperty(selectedDevice)) { - custom_config = { - ...custom_config, - ...device_config[selectedDevice], - }; + return left; + } + function parseCallMemberExpression() { + const member = parseMemberExpression(parsePrimaryExpression()); + if (is2(TOKEN_TYPES.OpenParen)) { + return parseCallExpression(member); } - - // If options.dtype is specified, we use it to choose the suffix for the model file. - // Otherwise, we use the default dtype for the device. - let dtype = options.dtype ?? custom_config.dtype; - if (typeof dtype !== 'string') { - if (dtype && dtype.hasOwnProperty(fileName)) { - dtype = dtype[fileName]; - } else { - dtype = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp32; - console.warn(`dtype not specified for "${fileName}". Using the default dtype (${dtype}) for this device (${selectedDevice}).`); - } + return member; + } + function parseCallExpression(callee) { + let expression = new CallExpression(callee, parseArgs("call")); + expression = parseMemberExpression(expression); + if (is2(TOKEN_TYPES.OpenParen)) { + expression = parseCallExpression(expression); } - - if (dtype === _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.auto) { - // Try to choose the auto dtype based on the custom config - let config_dtype = custom_config.dtype; - if (typeof config_dtype !== 'string') { - config_dtype = config_dtype?.[fileName]; + return expression; + } + function parseArgs(mode) { + expect(TOKEN_TYPES.OpenParen, "Expected opening parenthesis for arguments list"); + const args = parseArgumentsList(mode); + expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis for arguments list"); + return args; + } + function parseArgumentsList(mode) { + const args = []; + const parameterNames = /* @__PURE__ */ new Set(); + let sawKeywordOrDefault = false; + let sawSpreadArgument = false; + while (!is2(TOKEN_TYPES.CloseParen)) { + const isKeywordSpread = is2(TOKEN_TYPES.ExponentiationBinaryOperator); + const isPositionalSpread = is2(TOKEN_TYPES.MultiplicativeBinaryOperator) && tokens[current].value === "*"; + if (mode === "parameters" && (isKeywordSpread || isPositionalSpread)) { + throw new SyntaxError("Argument unpacking is not allowed in parameter declarations"); + } + if (isKeywordSpread) { + ++current; + args.push(new KeywordSpreadExpression(parseExpression())); + if (is2(TOKEN_TYPES.Comma)) { + ++current; } - - if (config_dtype && config_dtype !== _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.auto && _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.hasOwnProperty(config_dtype)) { - // Defined by the config, and is not "auto" - dtype = config_dtype; - } else { - // Choose default dtype based on device, falling back to fp32 - dtype = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp32; + if (!is2(TOKEN_TYPES.CloseParen)) { + throw new SyntaxError("Expected closing parenthesis: `**` must be applied to the final argument"); } - } - - const selectedDtype = /** @type {import("./utils/dtypes.js").DataType} */(dtype); - - if (!_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) { - throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES).join(', ')}`); - } else if (selectedDtype === _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DATA_TYPES.fp16 && selectedDevice === 'webgpu' && !(await (0,_utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.isWebGpuFp16Supported)())) { - throw new Error(`The device (${selectedDevice}) does not support fp16.`); - } - - // Only valid for models with a decoder - const kv_cache_dtype_config = custom_config.kv_cache_dtype; - const kv_cache_dtype = kv_cache_dtype_config - ? (typeof kv_cache_dtype_config === 'string' - ? kv_cache_dtype_config - : kv_cache_dtype_config[selectedDtype] ?? 'float32') - : undefined; - - if (kv_cache_dtype && !['float32', 'float16'].includes(kv_cache_dtype)) { - throw new Error(`Invalid kv_cache_dtype: ${kv_cache_dtype}. Should be one of: float32, float16`); - } - - const session_config = { - dtype: selectedDtype, - kv_cache_dtype, - device: selectedDevice, - } - - // Construct the model file name - const suffix = _utils_dtypes_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype]; - const baseName = `${fileName}${suffix}.onnx`; - const modelFileName = `${options.subfolder ?? ''}/${baseName}`; - - const session_options = { ...options.session_options }; - - // Overwrite `executionProviders` if not specified - session_options.executionProviders ??= executionProviders; - - // Overwrite `freeDimensionOverrides` if specified in config and not set in session options - const free_dimension_overrides = custom_config.free_dimension_overrides; - if (free_dimension_overrides) { - session_options.freeDimensionOverrides ??= free_dimension_overrides; - } else if (selectedDevice.startsWith('webnn') && !session_options.freeDimensionOverrides) { - console.warn( - `WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${selectedDevice}"]. ` + - `When 'free_dimension_overrides' is not set, you may experience significant performance degradation.` - ); - } - - const return_path = _env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV && _env_js__WEBPACK_IMPORTED_MODULE_14__.env.useFSCache; - const bufferOrPathPromise = (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, modelFileName, true, options, return_path); - - // Handle onnx external data files - const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format; - /** @type {Promise[]} */ - let externalDataPromises = []; - if (use_external_data_format) { - let external_data_format; - if (typeof use_external_data_format === 'object') { - if (use_external_data_format.hasOwnProperty(baseName)) { - external_data_format = use_external_data_format[baseName]; - } else if (use_external_data_format.hasOwnProperty(fileName)) { - external_data_format = use_external_data_format[fileName]; - } else { - external_data_format = false; - } - } else { - external_data_format = use_external_data_format; - } - - const num_chunks = +external_data_format; // (false=0, true=1, number remains the same) - if (num_chunks > _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS) { - throw new Error(`The number of external data chunks (${num_chunks}) exceeds the maximum allowed value (${_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS}).`); - } - for (let i = 0; i < num_chunks; ++i) { - const path = `${baseName}_data${i === 0 ? '' : '_' + i}`; - const fullPath = `${options.subfolder ?? ''}/${path}`; - externalDataPromises.push(new Promise(async (resolve, reject) => { - const data = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path); - resolve(data instanceof Uint8Array ? { path, data } : path); - })); - } - - } else if (session_options.externalData !== undefined) { - externalDataPromises = session_options.externalData.map(async (ext) => { - // if the external data is a string, fetch the file and replace the string with its content - // @ts-expect-error TS2339 - if (typeof ext.data === "string") { - // @ts-expect-error TS2339 - const ext_buffer = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, ext.data, true, options); - // @ts-expect-error TS2698 - return { ...ext, data: ext_buffer }; - } - return ext; - }); - } - - if (externalDataPromises.length > 0) { - const externalData = await Promise.all(externalDataPromises); - if (!_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_NODE_ENV) { - session_options.externalData = externalData; + break; + } + let argument; + if (isPositionalSpread) { + if (sawSpreadArgument) { + throw new SyntaxError("Only one `*` argument unpacking is allowed"); } - } - - if (selectedDevice === 'webgpu') { - const shapes = (0,_configs_js__WEBPACK_IMPORTED_MODULE_0__.getCacheShapes)(options.config, { - prefix: 'present', - }); - if (Object.keys(shapes).length > 0 && !(0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXProxy)()) { - // Only set preferredOutputLocation if shapes are present and we aren't proxying ONNX - /** @type {Record} */ - const preferredOutputLocation = {}; - for (const key in shapes) { - preferredOutputLocation[key] = 'gpu-buffer'; - } - session_options.preferredOutputLocation = preferredOutputLocation; + sawSpreadArgument = true; + ++current; + const expr = parseExpression(); + argument = new SpreadExpression(expr); + } else { + argument = parseExpression(); + if (is2(TOKEN_TYPES.Equals)) { + ++current; + if (!(argument instanceof Identifier)) { + throw new SyntaxError( + mode === "parameters" ? "Expected identifier for parameter declaration" : "Expected identifier for keyword argument" + ); + } + const value = parseExpression(); + argument = new KeywordArgumentExpression(argument, value); } - } - - const buffer_or_path = await bufferOrPathPromise; - - return { buffer_or_path, session_options, session_config }; -} - -/** - * Helper function to create multiple InferenceSession objects. - * - * @param {string} pretrained_model_name_or_path The path to the directory containing the model file. - * @param {Record} names The names of the model files to load. - * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model. - * @returns {Promise>} A Promise that resolves to a dictionary of InferenceSession objects. - * @private - */ -async function constructSessions(pretrained_model_name_or_path, names, options) { - return Object.fromEntries(await Promise.all( - Object.keys(names).map(async (name) => { - const { buffer_or_path, session_options, session_config } = await getSession(pretrained_model_name_or_path, names[name], options); - const session = await (0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.createInferenceSession)(buffer_or_path, session_options, session_config); - return [name, session]; - }) - )); -} - -/** - * Helper function to load multiple optional configuration files - * @param {string} pretrained_model_name_or_path The path to the directory containing the config file. - * @param {Record} names The names of the config files to load. - * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the configs. - * @returns {Promise>} A Promise that resolves to a dictionary of configuration objects. - * @private - */ -async function getOptionalConfigs(pretrained_model_name_or_path, names, options) { - return Object.fromEntries(await Promise.all( - Object.keys(names).map(async (name) => { - const config = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelJSON)(pretrained_model_name_or_path, names[name], false, options); - return [name, config]; - }) - )); -} - -/** - * Validate model inputs - * @param {Object} session The InferenceSession object that will be run. - * @param {Object} inputs The inputs to check. - * @returns {Record} The checked inputs. - * @throws {Error} If any inputs are missing. - * @private - */ -function validateInputs(session, inputs) { - /** - * NOTE: Create either a shallow or deep copy based on `onnx.wasm.proxy` - * @type {Record} - */ - const checkedInputs = Object.create(null); - const missingInputs = []; - for (const inputName of session.inputNames) { - const tensor = inputs[inputName]; - // Rare case where one of the model's input names corresponds to a built-in - // object name (e.g., toString), which would cause a simple (!tensor) check to fail, - // because it's not undefined but a function. - if (!(tensor instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor)) { - missingInputs.push(inputName); - continue; + if (mode === "parameters") { + if (!(argument instanceof Identifier || argument instanceof KeywordArgumentExpression)) { + throw new SyntaxError("Expected identifier for parameter declaration"); + } + const parameterName = argument instanceof Identifier ? argument.value : argument.key.value; + if (parameterNames.has(parameterName)) { + throw new SyntaxError(`Duplicate parameter name: ${parameterName}`); + } + parameterNames.add(parameterName); + } + if (argument instanceof KeywordArgumentExpression) { + sawKeywordOrDefault = true; + } else if (sawKeywordOrDefault) { + throw new SyntaxError( + mode === "call" ? "Positional arguments must come before keyword arguments" : "Non-default argument follows default argument" + ); + } else if (sawSpreadArgument) { + throw new SyntaxError("Positional arguments must not follow `*` argument unpacking"); } - // NOTE: When `env.wasm.proxy is true` the tensor is moved across the Worker - // boundary, transferring ownership to the worker and invalidating the tensor. - // So, in this case, we simply sacrifice a clone for it. - checkedInputs[inputName] = (0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXProxy)() ? tensor.clone() : tensor; + } + args.push(argument); + if (is2(TOKEN_TYPES.Comma)) { + ++current; + } } - if (missingInputs.length > 0) { - throw new Error( - `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(', ')}.`); + return args; + } + function parseMemberExpressionArgumentsList() { + const slices = []; + let isSlice = false; + while (!is2(TOKEN_TYPES.CloseSquareBracket)) { + if (is2(TOKEN_TYPES.Colon)) { + slices.push(void 0); + ++current; + isSlice = true; + } else { + slices.push(parseExpression()); + if (is2(TOKEN_TYPES.Colon)) { + ++current; + isSlice = true; + } + } } - - const numInputsProvided = Object.keys(inputs).length; - const numInputsNeeded = session.inputNames.length; - if (numInputsProvided > numInputsNeeded) { - // No missing inputs, but too many inputs were provided. - // Warn the user and ignore the extra inputs. - let ignored = Object.keys(inputs).filter(inputName => !session.inputNames.includes(inputName)); - console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(', ')}".`); + if (slices.length === 0) { + throw new SyntaxError(`Expected at least one argument for member/slice expression`); } - - return checkedInputs; -} - -// Currently, Transformers.js doesn't support simultaneous execution of sessions in WASM/WebGPU. -// For this reason, we need to chain the inference calls (otherwise we get "Error: Session already started"). -let webInferenceChain = Promise.resolve(); - -/** - * Executes an InferenceSession using the specified inputs. - * NOTE: `inputs` must contain at least the input names of the model. - * - If additional inputs are passed, they will be ignored. - * - If inputs are missing, an error will be thrown. - * - * @param {Object} session The InferenceSession object to run. - * @param {Object} inputs An object that maps input names to input tensors. - * @returns {Promise} A Promise that resolves to an object that maps output names to output tensors. - * @private - */ -async function sessionRun(session, inputs) { - const checkedInputs = validateInputs(session, inputs); - try { - // pass the original ort tensor - const ortFeed = Object.fromEntries(Object.entries(checkedInputs).map(([k, v]) => [k, v.ort_tensor])); - const run = () => session.run(ortFeed); - const output = await ((_env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_BROWSER_ENV || _env_js__WEBPACK_IMPORTED_MODULE_14__.apis.IS_WEBWORKER_ENV) - ? (webInferenceChain = webInferenceChain.then(run)) - : run()); - return replaceTensors(output); - } catch (e) { - // Error messages can be long (nested) and uninformative. For this reason, - // we apply minor formatting to show the most important information - const formatted = Object.fromEntries(Object.entries(checkedInputs) - .map(([k, tensor]) => { - // Extract these properties from the underlying ORT tensor - const unpacked = { - type: tensor.type, - dims: tensor.dims, - location: tensor.location, - } - if (unpacked.location !== "gpu-buffer") { - // Only return the data if it's not a GPU buffer - unpacked.data = tensor.data; - } - return [k, unpacked]; - })); - - // This usually occurs when the inputs are of the wrong type. - console.error(`An error occurred during model execution: "${e}".`); - console.error('Inputs given to model:', formatted); - throw e; + if (isSlice) { + if (slices.length > 3) { + throw new SyntaxError(`Expected 0-3 arguments for slice expression`); + } + return new SliceExpression(...slices); } -} - -/** - * Replaces ONNX Tensor objects with custom Tensor objects to support additional functions. - * @param {Object} obj The object to replace tensor objects in. - * @returns {Object} The object with tensor objects replaced by custom Tensor objects. - * @private - */ -function replaceTensors(obj) { - for (let prop in obj) { - if ((0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXTensor)(obj[prop])) { - obj[prop] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(obj[prop]); - } else if (typeof obj[prop] === 'object') { - replaceTensors(obj[prop]); + return slices[0]; + } + function parseMemberExpression(object) { + while (is2(TOKEN_TYPES.Dot) || is2(TOKEN_TYPES.OpenSquareBracket)) { + const operator = tokens[current]; + ++current; + let property; + const computed = operator.type === TOKEN_TYPES.OpenSquareBracket; + if (computed) { + property = parseMemberExpressionArgumentsList(); + expect(TOKEN_TYPES.CloseSquareBracket, "Expected closing square bracket"); + } else { + property = parsePrimaryExpression(); + if (property.type !== "Identifier" && property.type !== "IntegerLiteral") { + throw new SyntaxError(`Expected identifier or integer following dot operator`); } + } + object = new MemberExpression(object, property, computed); } - return obj; -} - - -/** - * Converts an array or Tensor of integers to an int64 Tensor. - * @param {any[]|Tensor} items The input integers to be converted. - * @returns {Tensor} The int64 Tensor with the converted values. - * @throws {Error} If the input array is empty or the input is a batched Tensor and not all sequences have the same length. - * @private - */ -function toI64Tensor(items) { - if (items instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor) { - return items; - } - // items is an array - if (items.length === 0) { - throw Error("items must be non-empty"); + return object; + } + function parseMultiplicativeExpression() { + let left = parsePowerExpression(); + while (is2(TOKEN_TYPES.MultiplicativeBinaryOperator)) { + const operator = tokens[current++]; + const right = parsePowerExpression(); + left = new BinaryExpression(operator, left, right); } - - if (Array.isArray(items[0])) { - // batched - if (items.some(x => x.length !== items[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 _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', - BigInt64Array.from(items.flat().map(x => BigInt(x))), - [items.length, items[0].length] - ); - } else { - //flat - return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', - BigInt64Array.from(items.map(x => BigInt(x))), - [1, items.length] - ); + return left; + } + function parsePowerExpression() { + let left = parseTestExpression(); + while (is2(TOKEN_TYPES.ExponentiationBinaryOperator)) { + const operator = tokens[current++]; + const right = parseTestExpression(); + left = new BinaryExpression(operator, left, right); } -} - -/** - * Creates a boolean tensor with a single value. - * @param {boolean} value The value of the tensor. - * @returns {Tensor} The boolean tensor. - * @private - */ -function boolTensor(value) { - return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('bool', [value], [1]); -} - -// JS doesn't support mixins, so we define some reused functions here, and allow "this" to be passed in -/** - * Perform forward pass on the seq2seq model (both encoder and decoder). - * @param {Object} self The seq2seq model object. - * @param {Object} model_inputs The input object for the model containing encoder and decoder inputs. - * @returns {Promise} Promise that resolves with the output of the seq2seq model. - * @private - */ -async function seq2seqForward(self, model_inputs) { - let { encoder_outputs, input_ids, decoder_input_ids, ...other_decoder_inputs } = model_inputs; - // Encode if needed - if (!encoder_outputs) { - const encoder_inputs = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, self.sessions['model'].inputNames); - // Encoder outputs are not given, so we must compute them. - encoder_outputs = (await encoderForward(self, encoder_inputs)).last_hidden_state; + return left; + } + function parseTestExpression() { + let operand = parseFilterExpression(); + while (isIdentifier("is")) { + ++current; + const negate = isIdentifier("not"); + if (negate) { + ++current; + } + const filter = parsePrimaryExpression(); + if (!(filter instanceof Identifier)) { + throw new SyntaxError(`Expected identifier for the test`); + } + operand = new TestExpression(operand, negate, filter); } - - other_decoder_inputs.input_ids = decoder_input_ids; - other_decoder_inputs.encoder_hidden_states = encoder_outputs; - - if (self.sessions['decoder_model_merged'].inputNames.includes('encoder_attention_mask')) { - other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask + return operand; + } + function parseFilterExpression() { + let operand = parseUnarySignExpression(); + while (is2(TOKEN_TYPES.Pipe)) { + ++current; + let filter = parsePrimaryExpression(); + if (!(filter instanceof Identifier)) { + throw new SyntaxError(`Expected identifier for the filter`); + } + if (is2(TOKEN_TYPES.OpenParen)) { + filter = parseCallExpression(filter); + } + operand = new FilterExpression(operand, filter); } - - const decoderResults = await decoderForward(self, other_decoder_inputs, true); - - return decoderResults; -} - -/** - * Forward pass of an encoder model. - * @param {Object} self The encoder model. - * @param {Object} model_inputs The input data to be used for the forward pass. - * @returns {Promise} The model's outputs. - * @private - */ -async function encoderForward(self, model_inputs) { - const session = self.sessions['model']; - const encoderFeeds = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, session.inputNames); - - if (session.inputNames.includes('inputs_embeds') && !encoderFeeds.inputs_embeds) { - if (!model_inputs.input_ids) { - throw new Error('Both `input_ids` and `inputs_embeds` are missing in the model inputs.'); - } - encoderFeeds.inputs_embeds = await self.encode_text({ input_ids: model_inputs.input_ids }); + return operand; + } + function parseUnarySignExpression() { + const token = tokens[current]; + if (token && (token.type === TOKEN_TYPES.UnaryOperator || token.type === TOKEN_TYPES.AdditiveBinaryOperator) && (token.value === "-" || token.value === "+")) { + const operator = tokens[current++]; + const argument = parseUnarySignExpression(); + return new UnaryExpression(operator, argument); } - if (session.inputNames.includes('token_type_ids') && !encoderFeeds.token_type_ids) { - if (!encoderFeeds.input_ids) { - throw new Error('Both `input_ids` and `token_type_ids` are missing in the model inputs.'); + return parseCallMemberExpression(); + } + function parsePrimaryExpression() { + const token = tokens[current++]; + switch (token.type) { + case TOKEN_TYPES.NumericLiteral: { + const num = token.value; + return num.includes(".") ? new FloatLiteral(Number(num)) : new IntegerLiteral(Number(num)); + } + case TOKEN_TYPES.StringLiteral: { + let value = token.value; + while (is2(TOKEN_TYPES.StringLiteral)) { + value += tokens[current++].value; } - // Assign default `token_type_ids` (all zeroes) to the `encoderFeeds` if the model expects it, - // but they weren't created by the tokenizer. - encoderFeeds.token_type_ids = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros_like)(encoderFeeds.input_ids); - } - if (session.inputNames.includes('pixel_mask') && !encoderFeeds.pixel_mask) { - if (!encoderFeeds.pixel_values) { - throw new Error('Both `pixel_values` and `pixel_mask` are missing in the model inputs.'); + return new StringLiteral(value); + } + case TOKEN_TYPES.Identifier: + return new Identifier(token.value); + case TOKEN_TYPES.OpenParen: { + const expression = parseExpressionSequence(); + expect(TOKEN_TYPES.CloseParen, "Expected closing parenthesis, got ${tokens[current].type} instead."); + return expression; + } + case TOKEN_TYPES.OpenSquareBracket: { + const values = []; + while (!is2(TOKEN_TYPES.CloseSquareBracket)) { + values.push(parseExpression()); + if (is2(TOKEN_TYPES.Comma)) { + ++current; + } } - // Assign default `pixel_mask` (all ones) to the `encoderFeeds` if the model expects it, - // but they weren't created by the processor. - const dims = encoderFeeds.pixel_values.dims; - encoderFeeds.pixel_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([dims[0], dims[2], dims[3]]); - } - - return await sessionRun(session, encoderFeeds); -} - -async function autoEncoderForward(self, model_inputs) { - const encoded = await self.encode(model_inputs); - const decoded = await self.decode(encoded); - return decoded; -} - -/** - * Forward pass of a decoder model. - * @param {Object} self The decoder model. - * @param {Object} model_inputs The input data to be used for the forward pass. - * @returns {Promise} The logits and past key values. - * @private - */ -async function decoderForward(self, model_inputs, is_encoder_decoder = false) { - - const session = self.sessions[ - is_encoder_decoder ? 'decoder_model_merged' : 'model' - ] - - const { past_key_values, ...new_model_inputs } = model_inputs; - - if (session.inputNames.includes('use_cache_branch')) { - new_model_inputs.use_cache_branch = boolTensor(!!past_key_values); - } - if (session.inputNames.includes('position_ids') && new_model_inputs.attention_mask && !new_model_inputs.position_ids) { - // NOTE: Handle a special case for paligemma/gemma3 models, where positions are 1-indexed - const start_index = ['paligemma', 'gemma3_text', 'gemma3'].includes(self.config.model_type) ? 1 : 0; - new_model_inputs.position_ids = createPositionIds(new_model_inputs, past_key_values, start_index); + ++current; + return new ArrayLiteral(values); + } + case TOKEN_TYPES.OpenCurlyBracket: { + const values = /* @__PURE__ */ new Map(); + while (!is2(TOKEN_TYPES.CloseCurlyBracket)) { + const key = parseExpression(); + expect(TOKEN_TYPES.Colon, "Expected colon between key and value in object literal"); + const value = parseExpression(); + values.set(key, value); + if (is2(TOKEN_TYPES.Comma)) { + ++current; + } + } + ++current; + return new ObjectLiteral(values); + } + default: + throw new SyntaxError(`Unexpected token: ${token.type}`); } - - // Unpack the `past_key_values` object into model inputs - self.addPastKeyValues(new_model_inputs, past_key_values); - - // Select only the inputs that are needed for the current session - const fixed = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(new_model_inputs, session.inputNames); - return await sessionRun(session, fixed); + } + while (current < tokens.length) { + program.body.push(parseAny()); + } + return program; } - - - -function default_merge_input_ids_with_features({ - modality_token_id, - inputs_embeds, - modality_features, - input_ids, - attention_mask, -}) { - const token_positions = input_ids.tolist().map(ids => - ids.reduce((acc, x, idx) => { - if (x == modality_token_id) acc.push(idx); - return acc; - }, []) - ); - const n_tokens = token_positions.reduce((acc, x) => acc + x.length, 0); - const n_features = modality_features.dims[0]; - if (n_tokens !== n_features) { - throw new Error(`Number of tokens and features do not match: tokens: ${n_tokens}, features ${n_features}`); +function range(start, stop, step = 1) { + if (stop === void 0) { + stop = start; + start = 0; + } + if (step === 0) { + throw new Error("range() step must not be zero"); + } + const result = []; + if (step > 0) { + for (let i = start; i < stop; i += step) { + result.push(i); } - - // Equivalent to performing a masked_scatter - let img = 0; - for (let i = 0; i < token_positions.length; ++i) { - const tokens = token_positions[i]; - const embeds = inputs_embeds[i]; - for (let j = 0; j < tokens.length; ++j) { - embeds[tokens[j]].data.set(modality_features[img++].data) - } + } else { + for (let i = start; i > stop; i += step) { + result.push(i); } - return { inputs_embeds, attention_mask } + } + return result; } - - -function default_merge_input_ids_with_image_features({ - image_token_id, - inputs_embeds, - image_features, - input_ids, - attention_mask, -}) { - return default_merge_input_ids_with_features({ - modality_token_id: image_token_id, - inputs_embeds, - modality_features: image_features, - input_ids, - attention_mask, - }) +function slice(array, start, stop, step = 1) { + const direction = Math.sign(step); + if (direction >= 0) { + start = (start ??= 0) < 0 ? Math.max(array.length + start, 0) : Math.min(start, array.length); + stop = (stop ??= array.length) < 0 ? Math.max(array.length + stop, 0) : Math.min(stop, array.length); + } else { + start = (start ??= array.length - 1) < 0 ? Math.max(array.length + start, -1) : Math.min(start, array.length - 1); + stop = (stop ??= -1) < -1 ? Math.max(array.length + stop, -1) : Math.min(stop, array.length - 1); + } + const result = []; + for (let i = start; direction * i < direction * stop; i += step) { + result.push(array[i]); + } + return result; } - -function default_merge_input_ids_with_audio_features({ - audio_token_id, - inputs_embeds, - audio_features, - input_ids, - attention_mask, -}) { - return default_merge_input_ids_with_features({ - modality_token_id: audio_token_id, - inputs_embeds, - modality_features: audio_features, - input_ids, - attention_mask, - }) +function titleCase(value) { + return value.replace(/\b\w/g, (c) => c.toUpperCase()); } - -/** - * Abstract forward pass function for image-text-to-text or audio-text-to-text models. - * @param {Object} self The model object. - * @param {Object} params Additional parameters. - * @param {Function} [params.encode_function] The function to encode the modality values. - * @param {Function} [params.merge_function] The function to merge the modality features with the input embeddings. - * @param {string} [params.modality_input_name] The modality input name. - * @param {string} [params.modality_output_name] The modality output name. - * @param {Tensor} [params.input_ids=null] - * @param {Tensor} [params.attention_mask=null] - * @param {Tensor} [params.position_ids=null] - * @param {Tensor} [params.inputs_embeds=null] - * @param {Tensor} [params.past_key_values=null] - * @param {Object} [params.generation_config=null] - * @param {Object} [params.logits_processor=null] - * @returns {Promise} The model's output tensor - * @private - */ -async function genericTextToTextForward(self, { - // Generic parameters: - encode_function, - merge_function, - modality_input_name, - modality_output_name, - - // Produced by the tokenizer/processor: - input_ids = null, - attention_mask = null, - - // Used during generation: - position_ids = null, - inputs_embeds = null, - past_key_values = null, - - // Generic generation parameters - generation_config = null, - logits_processor = null, - - // Additional parameters - ...kwargs -}) { - const modality_values = kwargs[modality_input_name]; - if (!inputs_embeds) { - // 1. Extract the text embeddings. - inputs_embeds = await self.encode_text({ input_ids, ...kwargs }); - - // 2. Possibly, merge text and modality values - if (modality_values && input_ids.dims[1] !== 1) { - const modality_features = await encode_function({ - // Pass the modality values under its expected key. - // The caller knows whether this is audio or image. - [modality_input_name]: modality_values, - ...kwargs - }); - ({ inputs_embeds, attention_mask } = merge_function({ - [modality_output_name]: modality_features, - inputs_embeds, - input_ids, - attention_mask, - })); - - } else if (past_key_values && modality_values && input_ids.dims[1] === 1) { - // This branch handles the cache case. - const target_length = input_ids.dims[1]; // always 1 - const past_length = Object.values(past_key_values)[0].dims.at(-2); - - attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([input_ids.dims[0], past_length]), - attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]), - ], 1); - } - } - - if (!position_ids) { - - if (self.config.model_type === 'qwen2_vl') { - // Special case for qwen2_vl models - // @ts-ignore - const { image_grid_thw, video_grid_thw } = kwargs; - [position_ids] = self.get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask) - } +function strftime_now(format2) { + return strftime(/* @__PURE__ */ new Date(), format2); +} +function strftime(date, format2) { + const monthFormatterLong = new Intl.DateTimeFormat(void 0, { month: "long" }); + const monthFormatterShort = new Intl.DateTimeFormat(void 0, { month: "short" }); + const pad2 = (n) => n < 10 ? "0" + n : n.toString(); + return format2.replace(/%[YmdbBHM%]/g, (token) => { + switch (token) { + case "%Y": + return date.getFullYear().toString(); + case "%m": + return pad2(date.getMonth() + 1); + case "%d": + return pad2(date.getDate()); + case "%b": + return monthFormatterShort.format(date); + case "%B": + return monthFormatterLong.format(date); + case "%H": + return pad2(date.getHours()); + case "%M": + return pad2(date.getMinutes()); + case "%%": + return "%"; + default: + return token; } - - // 3. Call the decoder forward using the updated inputs. - const outputs = await decoderForward(self, { - inputs_embeds, - past_key_values, - attention_mask, - position_ids, - generation_config, - logits_processor, - }, true); - return outputs; + }); } - -/** - * Forward pass of an audio-text-to-text model. - * @param {Object} self The audio-text-to-text model. - * @param {Object} params The inputs for the audio-text-to-text forward pass. - * @returns {Promise} The model's output tensor. - * @private - */ -async function audioTextToTextForward(self, params) { - return await genericTextToTextForward(self, { - ...params, - modality_input_name: 'audio_values', - modality_output_name: 'audio_features', - encode_function: self.encode_audio.bind(self), - merge_function: self._merge_input_ids_with_audio_features.bind(self), - }); +function escapeRegExp(s) { + return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } - -/** - * Forward pass of an image-text-to-text model. - * @param {Object} self The image-text-to-text model. - * @param {Object} params The inputs for the image-text-to-text forward pass. - * @returns {Promise} The model's output tensor. - * @private - */ -async function imageTextToTextForward(self, params) { - return await genericTextToTextForward(self, { - ...params, - modality_input_name: 'pixel_values', - modality_output_name: 'image_features', - encode_function: self.encode_image.bind(self), - merge_function: self._merge_input_ids_with_image_features.bind(self), - }); +function replace(str, oldvalue, newvalue, count2) { + if (count2 === 0) { + return str; + } + let remaining = count2 == null || count2 < 0 ? Infinity : count2; + const pattern = oldvalue.length === 0 ? new RegExp("(?=)", "gu") : new RegExp(escapeRegExp(oldvalue), "gu"); + return str.replaceAll(pattern, (match) => { + if (remaining > 0) { + --remaining; + return newvalue; + } + return match; + }); } - -/** - * Helper function to perform the following: - * ```python - * x = attention_mask.long().cumsum(-1) - 1 - * x.masked_fill_(attention_mask == 0, 1) - * ``` - * @param {Tensor} attention_mask - * @returns {{data: BigInt64Array, dims: number[]}} - */ -function cumsum_masked_fill(attention_mask, start_index = 0) { - const [bz, seq_len] = attention_mask.dims; - const attn_mask_data = attention_mask.data; - - const data = new BigInt64Array(attn_mask_data.length); - for (let i = 0; i < bz; ++i) { - const start = i * seq_len; - let sum = BigInt(start_index); - for (let j = 0; j < seq_len; ++j) { - const index = start + j; - if (attn_mask_data[index] === 0n) { - data[index] = BigInt(1); - } else { // === 1n - data[index] = sum; - sum += attn_mask_data[index]; +var BreakControl = class extends Error { +}; +var ContinueControl = class extends Error { +}; +var EMPTY_BUILTINS = /* @__PURE__ */ new Map(); +var RuntimeValue = class { + type = "RuntimeValue"; + value; + /** + * A collection of built-in functions for this type. + */ + get builtins() { + return EMPTY_BUILTINS; + } + /** + * Creates a new RuntimeValue. + */ + constructor(value = void 0) { + this.value = value; + } + /** + * Determines truthiness or falsiness of the runtime value. + * This function should be overridden by subclasses if it has custom truthiness criteria. + * @returns {BooleanValue} BooleanValue(true) if the value is truthy, BooleanValue(false) otherwise. + */ + __bool__() { + return new BooleanValue(!!this.value); + } + toString() { + return String(this.value); + } +}; +var IntegerValue = class extends RuntimeValue { + type = "IntegerValue"; +}; +var FloatValue = class extends RuntimeValue { + type = "FloatValue"; + toString() { + if (Object.is(this.value, -0)) { + return "-0.0"; + } + return this.value % 1 === 0 ? this.value.toFixed(1) : this.value.toString(); + } +}; +var StringValue = class extends RuntimeValue { + type = "StringValue"; + _builtins; + get builtins() { + return this._builtins ??= /* @__PURE__ */ new Map([ + [ + "upper", + new FunctionValue(() => { + return new StringValue(this.value.toUpperCase()); + }) + ], + [ + "lower", + new FunctionValue(() => { + return new StringValue(this.value.toLowerCase()); + }) + ], + [ + "strip", + new FunctionValue(() => { + return new StringValue(this.value.trim()); + }) + ], + [ + "title", + new FunctionValue(() => { + return new StringValue(titleCase(this.value)); + }) + ], + [ + "capitalize", + new FunctionValue(() => { + return new StringValue(this.value.charAt(0).toUpperCase() + this.value.slice(1)); + }) + ], + ["length", new IntegerValue(this.value.length)], + [ + "rstrip", + new FunctionValue(() => { + return new StringValue(this.value.trimEnd()); + }) + ], + [ + "lstrip", + new FunctionValue(() => { + return new StringValue(this.value.trimStart()); + }) + ], + [ + "startswith", + new FunctionValue((args) => { + if (args.length === 0) { + throw new Error("startswith() requires at least one argument"); + } + const pattern = args[0]; + if (pattern instanceof StringValue) { + return new BooleanValue(this.value.startsWith(pattern.value)); + } else if (pattern instanceof ArrayValue) { + for (const item of pattern.value) { + if (!(item instanceof StringValue)) { + throw new Error("startswith() tuple elements must be strings"); + } + if (this.value.startsWith(item.value)) { + return new BooleanValue(true); + } } - } + return new BooleanValue(false); + } + throw new Error("startswith() argument must be a string or tuple of strings"); + }) + ], + [ + "endswith", + new FunctionValue((args) => { + if (args.length === 0) { + throw new Error("endswith() requires at least one argument"); + } + const pattern = args[0]; + if (pattern instanceof StringValue) { + return new BooleanValue(this.value.endsWith(pattern.value)); + } else if (pattern instanceof ArrayValue) { + for (const item of pattern.value) { + if (!(item instanceof StringValue)) { + throw new Error("endswith() tuple elements must be strings"); + } + if (this.value.endsWith(item.value)) { + return new BooleanValue(true); + } + } + return new BooleanValue(false); + } + throw new Error("endswith() argument must be a string or tuple of strings"); + }) + ], + [ + "split", + // follows Python's `str.split(sep=None, maxsplit=-1)` function behavior + // https://docs.python.org/3.13/library/stdtypes.html#str.split + new FunctionValue((args) => { + const sep = args[0] ?? new NullValue(); + if (!(sep instanceof StringValue || sep instanceof NullValue)) { + throw new Error("sep argument must be a string or null"); + } + const maxsplit = args[1] ?? new IntegerValue(-1); + if (!(maxsplit instanceof IntegerValue)) { + throw new Error("maxsplit argument must be a number"); + } + let result = []; + if (sep instanceof NullValue) { + const text = this.value.trimStart(); + for (const { 0: match, index } of text.matchAll(/\S+/g)) { + if (maxsplit.value !== -1 && result.length >= maxsplit.value && index !== void 0) { + result.push(match + text.slice(index + match.length)); + break; + } + result.push(match); + } + } else { + if (sep.value === "") { + throw new Error("empty separator"); + } + result = this.value.split(sep.value); + if (maxsplit.value !== -1 && result.length > maxsplit.value) { + result.push(result.splice(maxsplit.value).join(sep.value)); + } + } + return new ArrayValue(result.map((part) => new StringValue(part))); + }) + ], + [ + "replace", + new FunctionValue((args) => { + if (args.length < 2) { + throw new Error("replace() requires at least two arguments"); + } + const oldValue = args[0]; + const newValue = args[1]; + if (!(oldValue instanceof StringValue && newValue instanceof StringValue)) { + throw new Error("replace() arguments must be strings"); + } + let count2; + if (args.length > 2) { + if (args[2].type === "KeywordArgumentsValue") { + count2 = args[2].value.get("count") ?? new NullValue(); + } else { + count2 = args[2]; + } + } else { + count2 = new NullValue(); + } + if (!(count2 instanceof IntegerValue || count2 instanceof NullValue)) { + throw new Error("replace() count argument must be a number or null"); + } + return new StringValue(replace(this.value, oldValue.value, newValue.value, count2.value)); + }) + ] + ]); + } +}; +var BooleanValue = class extends RuntimeValue { + type = "BooleanValue"; +}; +var NON_ASCII_CHARS = /[\x7f-\uffff]/g; +function makeAsciiSafe(str) { + return str.replace(NON_ASCII_CHARS, (char) => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0")); +} +function toJSON(input, options = {}, depth = 0, convertUndefinedToNull = true) { + const { indent = null, ensureAscii = false, separators = null, sortKeys = false } = options; + let itemSeparator; + let keySeparator; + if (separators) { + [itemSeparator, keySeparator] = separators; + } else if (indent) { + itemSeparator = ","; + keySeparator = ": "; + } else { + itemSeparator = ", "; + keySeparator = ": "; + } + switch (input.type) { + case "NullValue": + return "null"; + case "UndefinedValue": + return convertUndefinedToNull ? "null" : "undefined"; + case "IntegerValue": + case "FloatValue": + case "BooleanValue": + return JSON.stringify(input.value); + case "StringValue": { + let result = JSON.stringify(input.value); + if (ensureAscii) { + result = makeAsciiSafe(result); + } + return result; + } + case "ArrayValue": + case "NamespaceValue": + case "ObjectValue": { + const indentValue = indent ? " ".repeat(indent) : ""; + const basePadding = "\n" + indentValue.repeat(depth); + const childrenPadding = basePadding + indentValue; + if (input.type === "ArrayValue") { + const core = input.value.map((x) => toJSON(x, options, depth + 1, convertUndefinedToNull)); + return indent ? `[${childrenPadding}${core.join(`${itemSeparator}${childrenPadding}`)}${basePadding}]` : `[${core.join(itemSeparator)}]`; + } else { + let entries = Array.from(input.value.entries()); + if (sortKeys) { + entries = entries.sort(([a], [b]) => a.localeCompare(b)); + } + const core = entries.map(([key, value]) => { + let keyStr = JSON.stringify(key); + if (ensureAscii) { + keyStr = makeAsciiSafe(keyStr); + } + const v = `${keyStr}${keySeparator}${toJSON(value, options, depth + 1, convertUndefinedToNull)}`; + return indent ? `${childrenPadding}${v}` : v; + }); + return indent ? `{${core.join(itemSeparator)}${basePadding}}` : `{${core.join(itemSeparator)}}`; + } } - return { data, dims: attention_mask.dims }; - + default: + throw new Error(`Cannot convert to JSON: ${input.type}`); + } } - -/** - * If the model supports providing position_ids, we create position_ids on the fly for batch generation, - * by computing the cumulative sum of the attention mask along the sequence length dimension. - * - * Equivalent to: - * ```python - * position_ids = attention_mask.long().cumsum(-1) - 1 - * position_ids.masked_fill_(attention_mask == 0, 1) - * if past_key_values: - * position_ids = position_ids[:, -input_ids.shape[1] :] - * ``` - */ -function createPositionIds(model_inputs, past_key_values = null, start_index = 0) { - const { input_ids, inputs_embeds, attention_mask } = model_inputs; - - const { data, dims } = cumsum_masked_fill(attention_mask, start_index); - let position_ids = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', data, dims); - if (past_key_values) { - const offset = -(input_ids ?? inputs_embeds).dims.at(1); - position_ids = position_ids.slice(null, [offset, null]); - } - return position_ids; +var ObjectValue = class extends RuntimeValue { + type = "ObjectValue"; + _builtins; + /** + * NOTE: necessary to override since all JavaScript arrays are considered truthy, + * while only non-empty Python arrays are consider truthy. + * + * e.g., + * - JavaScript: {} && 5 -> 5 + * - Python: {} and 5 -> {} + */ + __bool__() { + return new BooleanValue(this.value.size > 0); + } + get builtins() { + return this._builtins ??= /* @__PURE__ */ new Map([ + [ + "get", + new FunctionValue(([key, defaultValue]) => { + if (!(key instanceof StringValue)) { + throw new Error(`Object key must be a string: got ${key.type}`); + } + return this.value.get(key.value) ?? defaultValue ?? new NullValue(); + }) + ], + ["items", new FunctionValue(() => this.items())], + ["keys", new FunctionValue(() => this.keys())], + ["values", new FunctionValue(() => this.values())], + [ + "dictsort", + new FunctionValue((args) => { + let kwargs = /* @__PURE__ */ new Map(); + const positionalArgs = args.filter((arg) => { + if (arg instanceof KeywordArgumentsValue) { + kwargs = arg.value; + return false; + } + return true; + }); + const caseSensitive = positionalArgs.at(0) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false); + if (!(caseSensitive instanceof BooleanValue)) { + throw new Error("case_sensitive must be a boolean"); + } + const by = positionalArgs.at(1) ?? kwargs.get("by") ?? new StringValue("key"); + if (!(by instanceof StringValue)) { + throw new Error("by must be a string"); + } + if (!["key", "value"].includes(by.value)) { + throw new Error("by must be either 'key' or 'value'"); + } + const reverse = positionalArgs.at(2) ?? kwargs.get("reverse") ?? new BooleanValue(false); + if (!(reverse instanceof BooleanValue)) { + throw new Error("reverse must be a boolean"); + } + const items = Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])).sort((a, b) => { + const index = by.value === "key" ? 0 : 1; + const aVal = a.value[index]; + const bVal = b.value[index]; + const result = compareRuntimeValues(aVal, bVal, caseSensitive.value); + return reverse.value ? -result : result; + }); + return new ArrayValue(items); + }) + ] + ]); + } + items() { + return new ArrayValue( + Array.from(this.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) + ); + } + keys() { + return new ArrayValue(Array.from(this.value.keys()).map((key) => new StringValue(key))); + } + values() { + return new ArrayValue(Array.from(this.value.values())); + } + toString() { + return toJSON(this, {}, 0, false); + } +}; +var KeywordArgumentsValue = class extends ObjectValue { + type = "KeywordArgumentsValue"; +}; +var NamespaceValue = class extends RuntimeValue { + type = "NamespaceValue"; + toString() { + return toJSON(this, {}, 0, false); + } +}; +var ArrayValue = class extends RuntimeValue { + type = "ArrayValue"; + _builtins; + get builtins() { + return this._builtins ??= /* @__PURE__ */ new Map([["length", new IntegerValue(this.value.length)]]); + } + /** + * NOTE: necessary to override since all JavaScript arrays are considered truthy, + * while only non-empty Python arrays are consider truthy. + * + * e.g., + * - JavaScript: [] && 5 -> 5 + * - Python: [] and 5 -> [] + */ + __bool__() { + return new BooleanValue(this.value.length > 0); + } + toString() { + return toJSON(this, {}, 0, false); + } +}; +var TupleValue = class extends ArrayValue { + type = "TupleValue"; +}; +var FunctionValue = class extends RuntimeValue { + type = "FunctionValue"; +}; +var NullValue = class extends RuntimeValue { + type = "NullValue"; +}; +var UndefinedValue = class extends RuntimeValue { + type = "UndefinedValue"; +}; +function normalizeNamespaceEntry(pair) { + let values; + if (pair instanceof ArrayValue) { + values = pair.value; + } else if (pair instanceof StringValue) { + values = Array.from(pair.value, (char) => new StringValue(char)); + } + if (!values || values.length !== 2) { + throw new Error("namespace expected an object or an iterable of [key, value] pairs"); + } + const [key, value] = values; + if (!(key instanceof StringValue)) { + throw new Error("namespace keys must be strings"); + } + return [key, value]; } - -function decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) { - const past_length = model_inputs.past_key_values - ? Object.values(model_inputs.past_key_values)[0].dims.at(-2) - : 0; - - if (!model_inputs.attention_mask) { - // If the attention mask is not provided, we attempt to infer based on provided inputs - let dims; - for (const key of ['input_ids', 'inputs_embeds', 'position_ids']) { - if (model_inputs[key]) { - dims = model_inputs[key].dims; - break; - } - } - if (!dims) { - throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs."); - } - model_inputs.attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([dims[0], past_length + dims[1]]); - } - - if (model_inputs.past_key_values) { - const { input_ids, attention_mask } = model_inputs; - - // Keep only the unprocessed tokens: - // 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where - // some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as - // input) - if (attention_mask && attention_mask.dims[1] > input_ids.dims[1]) { - // NOTE: not needed since we only pass the generated tokens to the next forward pass - // const offset = -(attention_mask.dims[1] - past_length); - // model_inputs.input_ids = input_ids.slice(null, [offset, null]); +var _Environment = class { + constructor(parent) { + this.parent = parent; + } + /** + * The variables declared in this environment. + */ + variables = /* @__PURE__ */ new Map([ + [ + "namespace", + new FunctionValue((args) => { + const positional = args.slice(); + let kwargs; + if (positional.at(-1) instanceof KeywordArgumentsValue) { + kwargs = positional.pop(); } - // 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. - // We can discard input_ids based on the past_length. - else if (past_length < input_ids.dims[1]) { - // NOTE: Required for phi models. - // See https://github.com/huggingface/transformers/issues/30809#issuecomment-2111918479 for more information. - model_inputs.input_ids = input_ids.slice(null, [past_length, null]); + if (positional.length > 1) { + throw new Error(`namespace expected at most 1 argument, got ${positional.length}`); } - // 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens. - else { - + const entries = /* @__PURE__ */ new Map(); + if (positional.length === 1) { + const source = positional[0]; + if (source instanceof ObjectValue) { + for (const [key, value] of source.value) { + entries.set(key, value); + } + } else if (source instanceof ArrayValue) { + for (const pair of source.value) { + const [key, value] = normalizeNamespaceEntry(pair); + entries.set(key.value, value); + } + } else { + throw new Error(`'${source.type}' object is not iterable`); + } } - } - - return model_inputs; -} - -function encoder_decoder_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) { - if (model_inputs.past_key_values) { - input_ids = input_ids.map(x => [x.at(-1)]); - } - - return { - ...model_inputs, - decoder_input_ids: toI64Tensor(input_ids), - }; -} - -function multimodal_text_to_text_prepare_inputs_for_generation(self, ...args) { - if (self.config.is_encoder_decoder) { - return encoder_decoder_prepare_inputs_for_generation(self, ...args); - } else { - return decoder_prepare_inputs_for_generation(self, ...args); - } -} - -function multimodality_prepare_inputs_for_generation(self, input_ids, model_inputs, generation_config) { - const has_past_key_values = !!model_inputs.past_key_values; - - if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { - if (has_past_key_values) { - model_inputs.input_ids = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - model_inputs.input_ids, - model_inputs.input_ids, - ], 0) - // NOTE: attention_mask handled in generation - } else { - model_inputs.input_ids = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - model_inputs.input_ids, - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(model_inputs.input_ids, BigInt(generation_config.pad_token_id)), - ], 0); - model_inputs.attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - model_inputs.attention_mask, - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(model_inputs.attention_mask, 0n), - ], 0); + if (kwargs) { + for (const [key, value] of kwargs.value) { + entries.set(key, value); + } } + return new NamespaceValue(entries); + }) + ] + ]); + tests = _Environment.TESTS; + /** + * Set the value of a variable in the current environment. + */ + set(name, value) { + return this.declareVariable(name, convertToRuntimeValues(value)); + } + declareVariable(name, value) { + if (this.variables.has(name)) { + throw new SyntaxError(`Variable already declared: ${name}`); } - - if (has_past_key_values || !model_inputs.pixel_values) { - model_inputs.pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([0, 0, 3, 384, 384], 1.0); + this.variables.set(name, value); + return value; + } + // private assignVariable(name: string, value: AnyRuntimeValue): AnyRuntimeValue { + // const env = this.resolve(name); + // env.variables.set(name, value); + // return value; + // } + /** + * Set variable in the current scope. + * See https://jinja.palletsprojects.com/en/3.0.x/templates/#assignments for more information. + */ + setVariable(name, value) { + this.variables.set(name, value); + return value; + } + /** + * Resolve the environment in which the variable is declared. + * @param {string} name The name of the variable. + * @returns {Environment} The environment in which the variable is declared. + */ + resolve(name) { + if (this.variables.has(name)) { + return this; } - - if (has_past_key_values) { - const num_img_tokens = 0; - const num_text_tokens = 1; - const has_image = num_img_tokens > 0 ? 1 : 0; - - const batch_size = 1; - model_inputs.images_seq_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - 'bool', - new Array(num_img_tokens + num_text_tokens).fill(true).fill(false, 0, num_text_tokens), - [batch_size, num_img_tokens + num_text_tokens], - ); - model_inputs.images_emb_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - 'bool', - new Array(num_img_tokens).fill(!!has_image), - [batch_size, 1, num_img_tokens], - ); + if (this.parent) { + return this.parent.resolve(name); } - return model_inputs; -} - -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -/** - * A base class for pre-trained models that provides the model configuration and an ONNX session. - */ -class PreTrainedModel extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_3__.Callable { - main_input_name = 'input_ids'; - forward_params = ['input_ids', 'attention_mask']; - /** - * Creates a new instance of the `PreTrainedModel` class. - * @param {import('./configs.js').PretrainedConfig} config The model configuration. - * @param {Record} sessions The inference sessions for the model. - * @param {Record} configs Additional configuration files (e.g., generation_config.json). - */ - constructor(config, sessions, configs) { - super(); - - this.config = config; - this.sessions = sessions; - this.configs = configs; - - const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); - const modelType = MODEL_TYPE_MAPPING.get(modelName); - - this.can_generate = false; - this._forward = null; - - this._prepare_inputs_for_generation = null; - switch (modelType) { - case MODEL_TYPES.DecoderOnly: - this.can_generate = true; - this._forward = decoderForward; - this._prepare_inputs_for_generation = decoder_prepare_inputs_for_generation; - break; - case MODEL_TYPES.Seq2Seq: - case MODEL_TYPES.Vision2Seq: - case MODEL_TYPES.Musicgen: - this.can_generate = true; - - this._forward = seq2seqForward; - this._prepare_inputs_for_generation = encoder_decoder_prepare_inputs_for_generation; - break; - - case MODEL_TYPES.EncoderDecoder: - this._forward = seq2seqForward; - break; - case MODEL_TYPES.ImageTextToText: - this.can_generate = true; - this._forward = imageTextToTextForward; - this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation; - break; - case MODEL_TYPES.AudioTextToText: - this.can_generate = true; - this._forward = audioTextToTextForward; - this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation; - break; - case MODEL_TYPES.Phi3V: - case MODEL_TYPES.ImageAudioTextToText: - this.can_generate = true; - this._prepare_inputs_for_generation = multimodal_text_to_text_prepare_inputs_for_generation; - break; - case MODEL_TYPES.MultiModality: - this.can_generate = true; - this._prepare_inputs_for_generation = multimodality_prepare_inputs_for_generation; - break; - case MODEL_TYPES.AutoEncoder: - this._forward = autoEncoderForward; - break; - default: - // should be MODEL_TYPES.EncoderOnly - this._forward = encoderForward; - break; - } - - if (this.can_generate) { - this.forward_params.push('past_key_values'); - } - - /** @type {import('./configs.js').TransformersJSConfig} */ - this.custom_config = this.config['transformers.js_config'] ?? {}; + throw new Error(`Unknown variable: ${name}`); + } + lookupVariable(name) { + try { + return this.resolve(name).variables.get(name) ?? new UndefinedValue(); + } catch { + return new UndefinedValue(); } - - /** - * Disposes of all the ONNX sessions that were created during inference. - * @returns {Promise} An array of promises, one for each ONNX session that is being disposed. - * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry - */ - async dispose() { - const promises = []; - for (const session of Object.values(this.sessions)) { - if (session?.handler?.dispose) { - promises.push(session.handler.dispose()) - } - } - return await Promise.all(promises); + } +}; +var Environment = _Environment; +__publicField(Environment, "TESTS", /* @__PURE__ */ new Map([ + ["boolean", (operand) => operand.type === "BooleanValue"], + ["callable", (operand) => operand instanceof FunctionValue], + [ + "odd", + (operand) => { + if (!(operand instanceof IntegerValue)) { + throw new Error(`cannot odd on ${operand.type}`); + } + return operand.value % 2 !== 0; + } + ], + [ + "even", + (operand) => { + if (!(operand instanceof IntegerValue)) { + throw new Error(`cannot even on ${operand.type}`); + } + return operand.value % 2 === 0; + } + ], + ["false", (operand) => operand.type === "BooleanValue" && !operand.value], + ["true", (operand) => operand.type === "BooleanValue" && operand.value], + ["none", (operand) => operand.type === "NullValue"], + ["string", (operand) => operand.type === "StringValue"], + ["number", (operand) => operand instanceof IntegerValue || operand instanceof FloatValue], + ["integer", (operand) => operand instanceof IntegerValue], + ["iterable", (operand) => operand.type === "ArrayValue" || operand.type === "StringValue"], + ["mapping", (operand) => operand instanceof ObjectValue], + [ + "sequence", + (operand) => operand instanceof ArrayValue || operand instanceof ObjectValue || operand instanceof StringValue + ], + [ + "lower", + (operand) => { + const str = operand.value; + return operand.type === "StringValue" && str === str.toLowerCase(); + } + ], + [ + "upper", + (operand) => { + const str = operand.value; + return operand.type === "StringValue" && str === str.toUpperCase(); + } + ], + ["none", (operand) => operand.type === "NullValue"], + ["defined", (operand) => operand.type !== "UndefinedValue"], + ["undefined", (operand) => operand.type === "UndefinedValue"], + ["equalto", (a, b) => a.value === b.value], + ["eq", (a, b) => a.value === b.value] +])); +function setupGlobals(env3) { + env3.set("false", false); + env3.set("true", true); + env3.set("none", null); + env3.set("raise_exception", (args) => { + throw new Error(args); + }); + env3.set("range", range); + env3.set("strftime_now", strftime_now); + env3.set("True", true); + env3.set("False", false); + env3.set("None", null); +} +function isAttributeContainer(value) { + return value instanceof ObjectValue || value instanceof NamespaceValue; +} +function isNumericLikeValue(value) { + return value instanceof IntegerValue || value instanceof FloatValue || value instanceof BooleanValue; +} +function getNumericValue(value) { + return value instanceof BooleanValue ? Number(value.value) : value.value; +} +function getAttributeValue(item, attributePath) { + const parts = attributePath.split("."); + let value = item; + for (const part of parts) { + if (isAttributeContainer(value)) { + value = value.value.get(part) ?? new UndefinedValue(); + } else if (value instanceof ArrayValue) { + const index = parseInt(part, 10); + if (!isNaN(index) && index >= 0 && index < value.value.length) { + value = value.value[index]; + } else { + return new UndefinedValue(); + } + } else { + return new UndefinedValue(); } - - /** - * Instantiate one of the model classes of the library from a pretrained model. - * - * The model class to instantiate is selected based on the `model_type` property of the config object - * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. - * @param {import('./utils/hub.js').PretrainedModelOptions} options Additional options for loading the model. - * - * @returns {Promise} A new instance of the `PreTrainedModel` class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = 'main', - model_file_name = null, - subfolder = 'onnx', - device = null, - dtype = null, - use_external_data_format = null, - session_options = {}, - } = {}) { - - let options = { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - model_file_name, - subfolder, - device, - dtype, - use_external_data_format, - session_options, - } - - const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this); - const modelType = MODEL_TYPE_MAPPING.get(modelName); - - config = options.config = await _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options); - - let info; - if (modelType === MODEL_TYPES.DecoderOnly) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - model: options.model_file_name ?? 'model', - }, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - model: 'encoder_model', - decoder_model_merged: 'decoder_model_merged', - }, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.MaskGeneration) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - model: 'vision_encoder', - prompt_encoder_mask_decoder: 'prompt_encoder_mask_decoder', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.EncoderDecoder) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - model: 'encoder_model', - decoder_model_merged: 'decoder_model_merged', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.ImageTextToText) { - const sessions = { - embed_tokens: 'embed_tokens', - vision_encoder: 'vision_encoder', - decoder_model_merged: 'decoder_model_merged', - } - if (config.is_encoder_decoder) { - sessions['model'] = 'encoder_model'; - } - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, sessions, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.AudioTextToText) { - const sessions = { - embed_tokens: 'embed_tokens', - audio_encoder: 'audio_encoder', - decoder_model_merged: 'decoder_model_merged', - } - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, sessions, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - } else if (modelType === MODEL_TYPES.ImageAudioTextToText) { - const sessions = { - embed_tokens: 'embed_tokens', - audio_encoder: 'audio_encoder', - vision_encoder: 'vision_encoder', - decoder_model_merged: 'decoder_model_merged', - } - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, sessions, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - } else if (modelType === MODEL_TYPES.Musicgen) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - model: 'text_encoder', - decoder_model_merged: 'decoder_model_merged', - encodec_decode: 'encodec_decode', - }, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.MultiModality) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - 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', - }, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - - } else if (modelType === MODEL_TYPES.Phi3V) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - prepare_inputs_embeds: 'prepare_inputs_embeds', - model: 'model', - vision_encoder: 'vision_encoder', - }, options), - getOptionalConfigs(pretrained_model_name_or_path, { - generation_config: 'generation_config.json', - }, options), - ]); - } else if (modelType === MODEL_TYPES.AutoEncoder) { - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - encoder_model: 'encoder_model', - decoder_model: 'decoder_model', - }, options), - ]); - } else { // should be MODEL_TYPES.EncoderOnly - if (modelType !== MODEL_TYPES.EncoderOnly) { - const type = modelName ?? config?.model_type; - if (type !== 'custom') { - console.warn(`Model type for '${type}' not found, assuming encoder-only architecture. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_6__.GITHUB_ISSUE_URL}.`) - } - } - info = await Promise.all([ - constructSessions(pretrained_model_name_or_path, { - model: options.model_file_name ?? 'model', - }, options), - ]); - } - - // @ts-ignore - return new this(config, ...info); + } + return value; +} +function compareRuntimeValues(a, b, caseSensitive = false) { + if (a instanceof NullValue && b instanceof NullValue) { + return 0; + } + if (a instanceof NullValue || b instanceof NullValue) { + throw new Error(`Cannot compare ${a.type} with ${b.type}`); + } + if (a instanceof UndefinedValue && b instanceof UndefinedValue) { + return 0; + } + if (a instanceof UndefinedValue || b instanceof UndefinedValue) { + throw new Error(`Cannot compare ${a.type} with ${b.type}`); + } + if (isNumericLikeValue(a) && isNumericLikeValue(b)) { + const aNum = getNumericValue(a); + const bNum = getNumericValue(b); + return aNum < bNum ? -1 : aNum > bNum ? 1 : 0; + } + if (a.type !== b.type) { + throw new Error(`Cannot compare different types: ${a.type} and ${b.type}`); + } + switch (a.type) { + case "StringValue": { + let aStr = a.value; + let bStr = b.value; + if (!caseSensitive) { + aStr = aStr.toLowerCase(); + bStr = bStr.toLowerCase(); + } + return aStr < bStr ? -1 : aStr > bStr ? 1 : 0; } - - /** - * Runs the model with the provided inputs - * @param {Object} model_inputs Object containing input tensors - * @returns {Promise} Object containing output tensors - */ - async _call(model_inputs) { - return await this.forward(model_inputs); + default: + throw new Error(`Cannot compare type: ${a.type}`); + } +} +function getParameterDescriptor(argument) { + if (argument.type === "Identifier") { + return { name: argument.value }; + } + const keywordArgument = argument; + return { name: keywordArgument.key.value, defaultValue: keywordArgument.value }; +} +function isSpecialMacroArgument(name) { + return name === "kwargs" || name === "varargs"; +} +function findAccessedSpecialMacroArguments(parameters, body) { + const declared = /* @__PURE__ */ new Set(); + const accessed = /* @__PURE__ */ new Set(); + const declareName = (name) => { + if (isSpecialMacroArgument(name)) { + declared.add(name); } - - /** - * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method - * will be chosen based on the model type. - * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. - * @returns {Promise} The output data from the model in the format specified in the ONNX model. - * @throws {Error} This method must be implemented in subclasses. - */ - async forward(model_inputs) { - return await this._forward(this, model_inputs); + }; + const declareTarget = (target) => { + if (target.type === "Identifier") { + declareName(target.value); + } else if (target.type === "TupleLiteral") { + for (const item of target.value) { + declareTarget(item); + } } - - /** - * Get the model's generation config, if it exists. - * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`. - */ - get generation_config() { - return this.configs?.generation_config ?? null; + }; + const declareArgument = (argument) => { + declareName(getParameterDescriptor(argument).name); + }; + const visitArgumentDefaults = (args) => { + for (const argument of args) { + const parameter = getParameterDescriptor(argument); + if (parameter.defaultValue) { + visit(parameter.defaultValue); + } } - - /** - * This function returns a [`LogitsProcessorList`] list object that contains all relevant [`LogitsWarper`] - * instances used for multinomial sampling. - * @param {GenerationConfig} generation_config The generation config. - * @returns {LogitsProcessorList} generation_config - */ - _get_logits_warper(generation_config) { - - // instantiate warpers list - const warpers = new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); - - if (generation_config.temperature !== null && generation_config.temperature !== 1.0) { - warpers.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.TemperatureLogitsWarper(generation_config.temperature)); - } - if (generation_config.top_k !== null && generation_config.top_k !== 0) { - // TODO: add min_tokens_to_keep - warpers.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.TopKLogitsWarper(generation_config.top_k)); - } - if (generation_config.top_p !== null && generation_config.top_p < 1.0) { - // TODO: add min_tokens_to_keep - warpers.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.TopPLogitsWarper(generation_config.top_p)); - } - - return warpers; + }; + const visitFilter = (filter) => { + if (filter.type === "CallExpression") { + visit(filter.args); } - - /** - * @param {GenerationConfig} generation_config - * @param {number} input_ids_seq_length The starting sequence length for the input ids. - * @returns {LogitsProcessorList} - * @private - */ - _get_logits_processor( - generation_config, - input_ids_seq_length, - // encoder_input_ids, TODO - // prefix_allowed_tokens_fn, TODO - logits_processor = null - ) { - const processors = new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); - - // if (generation_config.diversity_penalty !== null && generation_config.diversity_penalty > 0.0) { - // processors.push(new HammingDiversityLogitsProcessor( - // generation_config.diversity_penalty, - // generation_config.num_beams, - // generation_config.num_beam_groups - // )); - // } - - // if (generation_config.encoder_repetition_penalty !== null && generation_config.encoder_repetition_penalty !== 1.0) { - // processors.push(new EncoderRepetitionPenaltyLogitsProcessor( - // generation_config.encoder_repetition_penalty, - // encoder_input_ids - // )); - // } - - if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1.0) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty)); + }; + const visit = (node) => { + if (Array.isArray(node)) { + for (const item of node) { + visit(item); + } + return; + } + if (node instanceof Map) { + for (const [key, value] of node) { + visit(key); + visit(value); + } + return; + } + if (!(node instanceof Statement)) { + return; + } + switch (node.type) { + case "For": { + const statement = node; + declareTarget(statement.loopvar); + if (statement.iterable.type === "SelectExpression") { + const iterable = statement.iterable; + visit(iterable.lhs); + visit(statement.body); + visit(statement.defaultBlock); + visit(iterable.test); + return; + } + visit(statement.iterable); + visit(statement.body); + visit(statement.defaultBlock); + return; + } + case "Set": { + const statement = node; + declareTarget(statement.assignee); + visit(statement.value); + visit(statement.body); + return; + } + case "Macro": { + const statement = node; + for (const argument of statement.args) { + declareArgument(argument); } - - if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size)); + visitArgumentDefaults(statement.args); + visit(statement.body); + return; + } + case "CallStatement": { + const statement = node; + visit(statement.call); + for (const argument of statement.callerArgs ?? []) { + declareArgument(argument); + } + visitArgumentDefaults(statement.callerArgs ?? []); + visit(statement.body); + return; + } + case "FilterStatement": { + const statement = node; + visit(statement.body); + visitFilter(statement.filter); + return; + } + case "Identifier": { + const name = node.value; + if (isSpecialMacroArgument(name) && !declared.has(name)) { + accessed.add(name); } - - // if (generation_config.encoder_no_repeat_ngram_size !== null && generation_config.encoder_no_repeat_ngram_size > 0) { - // if (this.config.is_encoder_decoder) { - // processors.push(new EncoderNoRepeatNGramLogitsProcessor( - // generation_config.encoder_no_repeat_ngram_size, - // encoder_input_ids - // )); - // } else { - // throw new Error("It's impossible to use `encoder_no_repeat_ngram_size` with decoder-only architecture"); - // } - // } - - if (generation_config.bad_words_ids !== null) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id)); + return; + } + case "MemberExpression": { + const expression = node; + visit(expression.object); + if (expression.computed) { + visit(expression.property); } - - if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)); + return; + } + case "FilterExpression": { + const expression = node; + visit(expression.operand); + visitFilter(expression.filter); + return; + } + case "TestExpression": + visit(node.operand); + return; + case "SelectExpression": { + const expression = node; + visit(expression.test); + visit(expression.lhs); + return; + } + case "KeywordArgumentExpression": + visit(node.value); + return; + default: + for (const child of Object.values(node)) { + visit(child); } - - if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.MinNewTokensLengthLogitsProcessor( - input_ids_seq_length, - generation_config.min_new_tokens, - generation_config.eos_token_id - )); + } + }; + for (const parameter of parameters) { + declareArgument(parameter); + } + visit(body); + return accessed; +} +var Interpreter = class { + global; + constructor(env3) { + this.global = env3 ?? new Environment(); + } + /** + * Run the program. + */ + run(program) { + return this.evaluate(program, this.global); + } + /** + * Evaluates expressions following the binary operation type. + */ + evaluateBinaryExpression(node, environment) { + const left = this.evaluate(node.left, environment); + switch (node.operator.value) { + case "and": + return left.__bool__().value ? this.evaluate(node.right, environment) : left; + case "or": + return left.__bool__().value ? left : this.evaluate(node.right, environment); + } + const right = this.evaluate(node.right, environment); + switch (node.operator.value) { + case "==": + return new BooleanValue(left.value == right.value); + case "!=": + return new BooleanValue(left.value != right.value); + } + if (left instanceof UndefinedValue || right instanceof UndefinedValue) { + if (right instanceof UndefinedValue && ["in", "not in"].includes(node.operator.value)) { + return new BooleanValue(node.operator.value === "not in"); + } + throw new Error(`Cannot perform operation ${node.operator.value} on undefined values`); + } else if (left instanceof NullValue || right instanceof NullValue) { + throw new Error("Cannot perform operation on null values"); + } else if (node.operator.value === "~") { + return new StringValue(left.value.toString() + right.value.toString()); + } else if (node.operator.value === "**" && isNumericLikeValue(left) && isNumericLikeValue(right)) { + const a = getNumericValue(left); + const b = getNumericValue(right); + if (a === 0 && b < 0) { + throw new Error("0.0 cannot be raised to a negative power"); + } + const result = a ** b; + if (!Number.isFinite(result)) { + throw new Error("Exponentiation result is not a finite real number"); + } + const isFloat = left instanceof FloatValue || right instanceof FloatValue || b < 0; + return isFloat ? new FloatValue(result) : new IntegerValue(result); + } else if ((left instanceof IntegerValue || left instanceof FloatValue) && (right instanceof IntegerValue || right instanceof FloatValue)) { + const a = left.value, b = right.value; + switch (node.operator.value) { + case "+": + case "-": + case "*": { + const res = node.operator.value === "+" ? a + b : node.operator.value === "-" ? a - b : a * b; + const isFloat = left instanceof FloatValue || right instanceof FloatValue; + return isFloat ? new FloatValue(res) : new IntegerValue(res); } - - // if (prefix_allowed_tokens_fn !== null) { - // processors.push(new PrefixConstrainedLogitsProcessor( - // prefix_allowed_tokens_fn, - // generation_config.num_beams / generation_config.num_beam_groups - // )); - // } - - - if (generation_config.forced_bos_token_id !== null) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id)); + case "/": + return new FloatValue(a / b); + case "//": { + const res = Math.floor(a / b); + const isFloat = left instanceof FloatValue || right instanceof FloatValue; + return isFloat ? new FloatValue(res) : new IntegerValue(res); } - - if (generation_config.forced_eos_token_id !== null) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.ForcedEOSTokenLogitsProcessor( - generation_config.max_length, - generation_config.forced_eos_token_id - )); + case "%": { + const rem = a % b; + const isFloat = left instanceof FloatValue || right instanceof FloatValue; + return isFloat ? new FloatValue(rem) : new IntegerValue(rem); } - - // if (generation_config.remove_invalid_values === true) { - // processors.push(new InfNanRemoveLogitsProcessor()); - // } - - // if (generation_config.exponential_decay_length_penalty !== null) { - // processors.push(new ExponentialDecayLengthPenalty( - // generation_config.exponential_decay_length_penalty, - // generation_config.eos_token_id, - // input_ids_seq_length - // )); - // } - - // if (generation_config.suppress_tokens !== null) { - // processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens)); - // } - - if (generation_config.begin_suppress_tokens !== null) { - const begin_index = (input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null) - ? input_ids_seq_length - : input_ids_seq_length + 1; - - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index)); + case "<": + return new BooleanValue(a < b); + case ">": + return new BooleanValue(a > b); + case ">=": + return new BooleanValue(a >= b); + case "<=": + return new BooleanValue(a <= b); + } + } else if (left instanceof ArrayValue && right instanceof ArrayValue) { + switch (node.operator.value) { + case "+": + return new ArrayValue(left.value.concat(right.value)); + } + } else if (right instanceof ArrayValue) { + const member = right.value.find((x) => x.value === left.value) !== void 0; + switch (node.operator.value) { + case "in": + return new BooleanValue(member); + case "not in": + return new BooleanValue(!member); + } + } + if (left instanceof StringValue || right instanceof StringValue) { + switch (node.operator.value) { + case "+": + return new StringValue(left.value.toString() + right.value.toString()); + } + } + if (left instanceof StringValue && right instanceof StringValue) { + switch (node.operator.value) { + case "in": + return new BooleanValue(right.value.includes(left.value)); + case "not in": + return new BooleanValue(!right.value.includes(left.value)); + } + } + if (left instanceof StringValue && right instanceof ObjectValue) { + switch (node.operator.value) { + case "in": + return new BooleanValue(right.value.has(left.value)); + case "not in": + return new BooleanValue(!right.value.has(left.value)); + } + } + throw new SyntaxError(`Unknown operator "${node.operator.value}" between ${left.type} and ${right.type}`); + } + evaluateArguments(args, environment) { + const positionalArguments = []; + const keywordArguments = /* @__PURE__ */ new Map(); + const addKeywordArgument = (key, value) => { + if (keywordArguments.has(key)) { + throw new Error(`Got multiple values for keyword argument '${key}'`); + } + keywordArguments.set(key, value); + }; + for (const argument of args) { + if (argument.type === "SpreadExpression") { + const spreadNode = argument; + const val = this.evaluate(spreadNode.argument, environment); + if (!(val instanceof ArrayValue)) { + throw new Error(`Cannot unpack non-iterable type: ${val.type}`); } - - // DEPRECATED: https://github.com/huggingface/transformers/pull/29485 - // if (generation_config.forced_decoder_ids !== null) { - // processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids)); - // } - - - // 8. prepare batched CFG externally - if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { - processors.push(new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale)); + for (const item of val.value) { + positionalArguments.push(item); } - - if (logits_processor !== null) { - processors.extend(logits_processor) + } else if (argument.type !== "KeywordArgumentExpression" && argument.type !== "KeywordSpreadExpression") { + positionalArguments.push(this.evaluate(argument, environment)); + } + } + for (const argument of args) { + if (argument.type === "KeywordArgumentExpression") { + const kwarg = argument; + addKeywordArgument(kwarg.key.value, this.evaluate(kwarg.value, environment)); + } else if (argument.type === "KeywordSpreadExpression") { + const spreadNode = argument; + const val = this.evaluate(spreadNode.argument, environment); + if (!(val instanceof ObjectValue)) { + throw new Error(`Argument after ** must be a mapping, not ${val.type}`); } - - // `LogitNormalization` should always be the last logit processor, when present - // if (generation_config.renormalize_logits === true) { - // processors.push(new LogitNormalization()); - // } - - return processors; + for (const [key, value] of val.value) { + addKeywordArgument(key, value); + } + } } - - /** - * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. - * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. - * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters. - * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object. - * @returns {GenerationConfig} The final generation config object to be used by the model for text generation. - */ - _prepare_generation_config(generation_config, kwargs, cls = _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_8__.GenerationConfig) { - // Create empty generation config (contains defaults) - // We pass `this.config` so that if `eos_token_id` or `bos_token_id` exist in the model's config, we will use them - const config = { ...this.config }; - for (const key of ["decoder", "generator", "text_config"]) { - // Special case: some models have generation attributes set in the decoder. - // Use them if still unset in the generation config. - if (key in config) { - Object.assign(config, config[key]); + return [positionalArguments, keywordArguments]; + } + applyFilter(operand, filterNode, environment) { + if (filterNode.type === "Identifier") { + const filter = filterNode; + if (filter.value === "safe") { + return operand; + } + if (filter.value === "tojson") { + return new StringValue(toJSON(operand, {})); + } + if (operand instanceof ArrayValue) { + switch (filter.value) { + case "list": + return operand; + case "first": + return operand.value[0]; + case "last": + return operand.value[operand.value.length - 1]; + case "length": + return new IntegerValue(operand.value.length); + case "reverse": + return new ArrayValue(operand.value.slice().reverse()); + case "sort": { + return new ArrayValue(operand.value.slice().sort((a, b) => compareRuntimeValues(a, b, false))); + } + case "join": + return new StringValue(operand.value.map((x) => x.value).join("")); + case "string": + return new StringValue(toJSON(operand, {}, 0, false)); + case "unique": { + const seen = /* @__PURE__ */ new Set(); + const output = []; + for (const item of operand.value) { + if (!seen.has(item.value)) { + seen.add(item.value); + output.push(item); + } } + return new ArrayValue(output); + } + default: + throw new Error(`Unknown ArrayValue filter: ${filter.value}`); } - - const gen_config = new cls(config); - - // Apply model's generation config, if it exists - Object.assign(gen_config, this.generation_config ?? {}); - - // Next, use any generation config specified by the user - // when calling `generate` - if (generation_config) { - Object.assign(gen_config, generation_config); - } - - // Finally, if any kwargs were passed, use them to overwrite - if (kwargs) { - Object.assign(gen_config, (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(kwargs, Object.getOwnPropertyNames(gen_config))); - } - - return gen_config; - } - - /** - * - * @param {GenerationConfig} generation_config - * @param {StoppingCriteriaList} [stopping_criteria=null] - */ - _get_stopping_criteria(generation_config, stopping_criteria = null) { - const criteria = new _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__.StoppingCriteriaList(); - - if (generation_config.max_length !== null) { - criteria.push(new _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__.MaxLengthCriteria( - generation_config.max_length, - this.config.max_position_embeddings ?? null, - )); - } - // if (generation_config.max_time !== null) { - // criteria.push(new MaxTimeCriteria(generation_config.max_time)); - // } - if (generation_config.eos_token_id !== null) { - criteria.push(new _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_12__.EosTokenCriteria(generation_config.eos_token_id)); + } else if (operand instanceof StringValue) { + switch (filter.value) { + case "length": + case "upper": + case "lower": + case "title": + case "capitalize": { + const builtin = operand.builtins.get(filter.value); + if (builtin instanceof FunctionValue) { + return builtin.value( + /* no arguments */ + [], + environment + ); + } else if (builtin instanceof IntegerValue) { + return builtin; + } else { + throw new Error(`Unknown StringValue filter: ${filter.value}`); + } + } + case "trim": + return new StringValue(operand.value.trim()); + case "indent": + return new StringValue( + operand.value.split("\n").map( + (x, i) => ( + // By default, don't indent the first line or empty lines + i === 0 || x.length === 0 ? x : " " + x + ) + ).join("\n") + ); + case "join": + case "string": + return operand; + case "int": { + const val = parseInt(operand.value, 10); + return new IntegerValue(isNaN(val) ? 0 : val); + } + case "float": { + const val = parseFloat(operand.value); + return new FloatValue(isNaN(val) ? 0 : val); + } + default: + throw new Error(`Unknown StringValue filter: ${filter.value}`); } - - if (stopping_criteria) { - criteria.extend(stopping_criteria); + } else if (operand instanceof IntegerValue || operand instanceof FloatValue) { + switch (filter.value) { + case "abs": + return operand instanceof IntegerValue ? new IntegerValue(Math.abs(operand.value)) : new FloatValue(Math.abs(operand.value)); + case "int": + return new IntegerValue(Math.floor(operand.value)); + case "float": + return new FloatValue(operand.value); + case "string": + return new StringValue(operand.toString()); + default: + throw new Error(`Unknown NumericValue filter: ${filter.value}`); } - return criteria; - - } - - /** - * Confirms that the model class is compatible with generation. - * If not, raises an exception that points to the right class to use. - */ - _validate_model_class() { - if (!this.can_generate) { - const generate_compatible_mappings = [ - MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, - // MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO - MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, - MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, - ]; - - const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); - - const generate_compatible_classes = new Set(); - const modelType = this.config.model_type; - for (const model_mapping of generate_compatible_mappings) { - const supported_models = model_mapping.get(modelType); - if (supported_models) { - generate_compatible_classes.add(supported_models[0]); - } - } - - let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.` - if (generate_compatible_classes.size > 0) { - errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(', ')}`; + } else if (operand instanceof ObjectValue) { + switch (filter.value) { + case "items": + return new ArrayValue( + Array.from(operand.value.entries()).map(([key, value]) => new ArrayValue([new StringValue(key), value])) + ); + case "length": + return new IntegerValue(operand.value.size); + default: { + const builtin = operand.builtins.get(filter.value); + if (builtin) { + if (builtin instanceof FunctionValue) { + return builtin.value([], environment); + } + return builtin; } - throw Error(errorMessage); + throw new Error(`Unknown ObjectValue filter: ${filter.value}`); + } } - } - - prepare_inputs_for_generation(...args) { - return this._prepare_inputs_for_generation(this, ...args); - } - - /** - * - * @param {Object} inputs - * @param {bigint[][]} inputs.generated_input_ids - * @param {Object} inputs.outputs - * @param {Object} inputs.model_inputs - * @param {boolean} inputs.is_encoder_decoder - * @returns {Object} The updated model inputs for the next generation iteration. - */ - _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) { - // update past_key_values - model_inputs['past_key_values'] = this.getPastKeyValues(outputs, model_inputs.past_key_values); - - // update inputs for next run - model_inputs['input_ids'] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', generated_input_ids.flat(), [generated_input_ids.length, 1]); - - if (!is_encoder_decoder) { - // update attention mask - model_inputs.attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)( - [ - model_inputs.attention_mask, - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([model_inputs.attention_mask.dims[0], 1]), - ], 1 - ); - } else if ('decoder_attention_mask' in model_inputs) { - // TODO: update decoder attention mask if the model requires it + } else if (operand instanceof BooleanValue) { + switch (filter.value) { + case "bool": + return new BooleanValue(operand.value); + case "int": + return new IntegerValue(operand.value ? 1 : 0); + case "float": + return new FloatValue(operand.value ? 1 : 0); + case "string": + return new StringValue(operand.value ? "true" : "false"); + default: + throw new Error(`Unknown BooleanValue filter: ${filter.value}`); } - - // force recreate position_ids in next iteration - model_inputs['position_ids'] = null; - - return model_inputs; - } - - /** - * This function extracts the model-specific `inputs` for generation. - * @param {Object} params - * @param {Tensor} [params.inputs=null] - * @param {number} [params.bos_token_id=null] - * @param {Record} [params.model_kwargs] - * @returns {{inputs_tensor: Tensor, model_inputs: Record, model_input_name: string}} The model-specific inputs for generation. - */ - _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) { - const model_inputs = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_kwargs, this.forward_params); - const input_name = this.main_input_name; - if (input_name in model_inputs) { - if (inputs) { - throw new Error( - "`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. " + - "Make sure to either pass {inputs} or {input_name}=..." - ); - } - } else { - model_inputs[input_name] = inputs; + } + throw new Error(`Cannot apply filter "${filter.value}" to type: ${operand.type}`); + } else if (filterNode.type === "CallExpression") { + const filter = filterNode; + if (filter.callee.type !== "Identifier") { + throw new Error(`Unknown filter: ${filter.callee.type}`); + } + const filterName = filter.callee.value; + if (filterName === "tojson") { + const [, kwargs] = this.evaluateArguments(filter.args, environment); + const indent = kwargs.get("indent") ?? new NullValue(); + if (!(indent instanceof IntegerValue || indent instanceof NullValue)) { + throw new Error("If set, indent must be a number"); } - - const inputs_tensor = model_inputs[input_name]; - - return { inputs_tensor, model_inputs, model_input_name: input_name }; - } - - async _prepare_encoder_decoder_kwargs_for_generation({ inputs_tensor, model_inputs, model_input_name, generation_config }) { - if ( - this.sessions['model'].inputNames.includes('inputs_embeds') - && !model_inputs.inputs_embeds - && '_prepare_inputs_embeds' in this - ) { - // Encoder expects `inputs_embeds` instead of `input_ids` - const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs; - // @ts-ignore - const prepared_inputs = await this._prepare_inputs_embeds(model_inputs); - model_inputs = { - ...kwargs, - ...(0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(prepared_inputs, ['inputs_embeds', 'attention_mask']), - }; + const ensureAscii = kwargs.get("ensure_ascii") ?? new BooleanValue(false); + if (!(ensureAscii instanceof BooleanValue)) { + throw new Error("If set, ensure_ascii must be a boolean"); } - let { last_hidden_state } = await encoderForward(this, model_inputs); - - // for classifier free guidance we need to add a 'null' input to our encoder hidden states - if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { - - last_hidden_state = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - last_hidden_state, - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full_like)(last_hidden_state, 0.0), - ], 0); - - if ('attention_mask' in model_inputs) { - model_inputs['attention_mask'] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - model_inputs['attention_mask'], - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros_like)(model_inputs['attention_mask']), - ], 0); - } - - } else if (model_inputs.decoder_input_ids) { - // Ensure that the encoder outputs have the same batch size as the decoder inputs, - // allowing for more efficient batched generation for single inputs - const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0]; - if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) { - if (last_hidden_state.dims[0] !== 1) { - throw new Error( - `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).` - ) - } - last_hidden_state = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)(Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), 0); - } + const sortKeys = kwargs.get("sort_keys") ?? new BooleanValue(false); + if (!(sortKeys instanceof BooleanValue)) { + throw new Error("If set, sort_keys must be a boolean"); } - model_inputs['encoder_outputs'] = last_hidden_state; - - return model_inputs; - } - - /** - * Prepares `decoder_input_ids` for generation with encoder-decoder models - * @param {*} param0 - */ - _prepare_decoder_input_ids_for_generation({ batch_size, model_input_name, model_kwargs, decoder_start_token_id, bos_token_id, generation_config }) { - let { decoder_input_ids, ...model_inputs } = model_kwargs; - - // Prepare input ids if the user has not defined `decoder_input_ids` manually. - if (!(decoder_input_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor)) { - if (!decoder_input_ids) { - decoder_start_token_id ??= bos_token_id; - - if (this.config.model_type === 'musicgen') { - // Custom logic (TODO: move to Musicgen class) - decoder_input_ids = Array.from({ - // @ts-expect-error TS2339 - length: batch_size * this.config.decoder.num_codebooks - }, () => [decoder_start_token_id]); - - } else if (Array.isArray(decoder_start_token_id)) { - if (decoder_start_token_id.length !== batch_size) { - throw new Error( - `\`decoder_start_token_id\` expcted to have length ${batch_size} but got ${decoder_start_token_id.length}` - ) - } - decoder_input_ids = decoder_start_token_id; - } else { - decoder_input_ids = Array.from({ - length: batch_size, - }, () => [decoder_start_token_id]); - } - } else if (!Array.isArray(decoder_input_ids[0])) { - // Correct batch size - decoder_input_ids = Array.from({ - length: batch_size, - }, () => decoder_input_ids); - } - decoder_input_ids = toI64Tensor(decoder_input_ids); + const separatorsArg = kwargs.get("separators") ?? new NullValue(); + let separators = null; + if (separatorsArg instanceof ArrayValue || separatorsArg instanceof TupleValue) { + if (separatorsArg.value.length !== 2) { + throw new Error("separators must be a tuple of two strings"); + } + const [itemSep, keySep] = separatorsArg.value; + if (!(itemSep instanceof StringValue) || !(keySep instanceof StringValue)) { + throw new Error("separators must be a tuple of two strings"); + } + separators = [itemSep.value, keySep.value]; + } else if (!(separatorsArg instanceof NullValue)) { + throw new Error("If set, separators must be a tuple of two strings"); + } + return new StringValue( + toJSON(operand, { + indent: indent.value, + ensureAscii: ensureAscii.value, + sortKeys: sortKeys.value, + separators + }) + ); + } else if (filterName === "join") { + let value; + if (operand instanceof StringValue) { + value = Array.from(operand.value); + } else if (operand instanceof ArrayValue) { + value = operand.value.map((x) => x.value); + } else { + throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); } - - model_kwargs['decoder_attention_mask'] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones_like)(decoder_input_ids); - - return { input_ids: decoder_input_ids, model_inputs }; - } - - /** - * Generates sequences of token ids for models with a language modeling head. - * @param {import('./generation/parameters.js').GenerationFunctionParameters} options - * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. - */ - async generate({ - inputs = null, - generation_config = null, - logits_processor = null, - stopping_criteria = null, - streamer = null, - - // inputs_attention_mask = null, - ...kwargs - }) { - this._validate_model_class(); - - // Update generation config with defaults and kwargs - generation_config = this._prepare_generation_config(generation_config, kwargs); - - // 3. Define model inputs - let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({ - inputs, - model_kwargs: kwargs, - }); - - const is_encoder_decoder = this.config.is_encoder_decoder; - - // 4. Define other model kwargs - if (!is_encoder_decoder) { - // decoder-only models should use left-padding for generation - } else if (!('encoder_outputs' in model_inputs)) { - // if model is encoder decoder encoder_outputs are created - // and added to `model_kwargs` - model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation( - { inputs_tensor, model_inputs, model_input_name, generation_config } - ) + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const separator = args.at(0) ?? kwargs.get("separator") ?? new StringValue(""); + if (!(separator instanceof StringValue)) { + throw new Error("separator must be a string"); } - - // 5. Prepare `input_ids` which will be used for auto-regressive generation - // TODO: Update to align with HF transformers' implementation - let input_ids; - if (is_encoder_decoder) { - // Generating from the encoder outputs - ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({ - batch_size: model_inputs[model_input_name].dims.at(0), - model_input_name, - model_kwargs: model_inputs, - decoder_start_token_id: generation_config.decoder_start_token_id, - bos_token_id: generation_config.bos_token_id, - generation_config, - })); + return new StringValue(value.join(separator.value)); + } else if (filterName === "int" || filterName === "float") { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const defaultValue = args.at(0) ?? kwargs.get("default") ?? (filterName === "int" ? new IntegerValue(0) : new FloatValue(0)); + if (operand instanceof StringValue) { + const val = filterName === "int" ? parseInt(operand.value, 10) : parseFloat(operand.value); + return isNaN(val) ? defaultValue : filterName === "int" ? new IntegerValue(val) : new FloatValue(val); + } else if (operand instanceof IntegerValue || operand instanceof FloatValue) { + return operand; + } else if (operand instanceof BooleanValue) { + return filterName === "int" ? new IntegerValue(operand.value ? 1 : 0) : new FloatValue(operand.value ? 1 : 0); } else { - input_ids = model_inputs[model_input_name] + throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); } - - // 6. Prepare `max_length` depending on other stopping criteria. - let input_ids_length = input_ids.dims.at(-1); - - if (generation_config.max_new_tokens !== null) { - generation_config.max_length = input_ids_length + generation_config.max_new_tokens; + } else if (filterName === "default") { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const defaultValue = args[0] ?? new StringValue(""); + const booleanValue = args[1] ?? kwargs.get("boolean") ?? new BooleanValue(false); + if (!(booleanValue instanceof BooleanValue)) { + throw new Error("`default` filter flag must be a boolean"); } - - // input_ids_length = model_inputs[model_input_name].dims.at(1); - // // inputs instanceof Tensor ? : inputs.length; - - // // decoder-only - // if (input_ids_length === 0) { - // throw Error("Must supply a non-empty array of input token ids.") - // } - - // let decoder_input_ids = - // generation_config.decoder_input_ids - // ?? generation_config.decoder_start_token_id - // ?? generation_config.bos_token_id - // ?? generation_config.eos_token_id; - - // Update logits processor - // 8. prepare distribution pre_processing samplers - const prepared_logits_processor = this._get_logits_processor( - generation_config, - input_ids_length, - logits_processor, - ) - - // 9. prepare stopping criteria - const prepared_stopping_criteria = this._get_stopping_criteria( - generation_config, stopping_criteria - ) - - // /** @type {number[]} */ - // let eos_token_ids = generation_config.eos_token_id; - // if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) { - // eos_token_ids = [eos_token_ids]; - // } - - const numInputs = model_inputs[model_input_name].dims.at(0); - - // TODO: - // done is a list of booleans to keep track of which inputs are done - // const done = new Array(numInputs).fill(false); - // For efficiency purposes, we remove completed rows from model_inputs - // when the beam is complete, and we keep track of the row index - // const rowIndexToBatchIndex = new Map(); - - const sampler = _generation_logits_sampler_js__WEBPACK_IMPORTED_MODULE_13__.LogitsSampler.getSampler(generation_config); - - // TODO make > numInputs - const scores = new Array(numInputs).fill(0); - /** @type {bigint[][]} */ - const all_input_ids = input_ids.tolist(); - if (streamer) { - streamer.put(all_input_ids); - } - // const all_generated_input_ids = Array.from({ length: numInputs }, () => []); - - // NOTE: For now, we don't support spawning new beams - // TODO: when we do, we simply copy past key values and accumulate into single large tensor - - //////////////////////////////////////////////////// - // Generic search which handles 4 generation modes: - // - GenerationMode.GREEDY_SEARCH - // - GenerationMode.SAMPLE - // - GenerationMode.BEAM_SEARCH - // - GenerationMode.BEAM_SAMPLE - //////////////////////////////////////////////////// - let outputs; - let attentions = {}; - while (true) { - // prepare model inputs - model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); - outputs = await this.forward(model_inputs); - - if (generation_config.output_attentions && generation_config.return_dict_in_generate) { - // Get attentions if they are present - const token_attentions = this.getAttentions(outputs); - for (const key in token_attentions) { - if (!(key in attentions)) { - attentions[key] = []; - } - attentions[key].push(token_attentions[key]); - } + if (operand instanceof UndefinedValue || booleanValue.value && !operand.__bool__().value) { + return defaultValue; + } + return operand; + } + if (operand instanceof ArrayValue) { + switch (filterName) { + case "sort": { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const reverse = args.at(0) ?? kwargs.get("reverse") ?? new BooleanValue(false); + if (!(reverse instanceof BooleanValue)) { + throw new Error("reverse must be a boolean"); } - - // Logits are of the form [batch_size, out_seq_length, vocab_size] - // In most cases, this will be [batch_size, 1, vocab_size] - // So, we select the last token's logits: - // (equivalent to `logits = outputs.logits[:, -1, :]`) - const logits = outputs.logits.slice(null, -1, null); - - const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); - - /** @type {[bigint][]} */ - const generated_input_ids = []; - // const new_kv_cache = [];// NOTE: Only used for beam search when concatenating new kv - // Loop over each batch - for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { - const logs = next_tokens_scores[batch_idx]; - - const sampledTokens = await sampler(logs); - for (const [newTokenId, logProb] of sampledTokens) { - const bigint = BigInt(newTokenId); - // TODO: If branching, use previous beam as a starting point - // update generated ids, model inputs, and length for next step - scores[batch_idx] += logProb; - all_input_ids[batch_idx].push(bigint); - generated_input_ids.push([bigint]); - - // TODO: Support beam search - break; - } + const caseSensitive = args.at(1) ?? kwargs.get("case_sensitive") ?? new BooleanValue(false); + if (!(caseSensitive instanceof BooleanValue)) { + throw new Error("case_sensitive must be a boolean"); } - if (streamer) { - streamer.put(generated_input_ids); + const attribute = args.at(2) ?? kwargs.get("attribute") ?? new NullValue(); + if (!(attribute instanceof StringValue || attribute instanceof IntegerValue || attribute instanceof NullValue)) { + throw new Error("attribute must be a string, integer, or null"); } - - const stop = prepared_stopping_criteria(all_input_ids); - if (stop.every(x => x)) { - break; + const getSortValue = (item) => { + if (attribute instanceof NullValue) { + return item; + } + const attrPath = attribute instanceof IntegerValue ? String(attribute.value) : attribute.value; + return getAttributeValue(item, attrPath); + }; + return new ArrayValue( + operand.value.slice().sort((a, b) => { + const aVal = getSortValue(a); + const bVal = getSortValue(b); + const result = compareRuntimeValues(aVal, bVal, caseSensitive.value); + return reverse.value ? -result : result; + }) + ); + } + case "selectattr": + case "rejectattr": { + const select = filterName === "selectattr"; + if (operand.value.some((item) => !isAttributeContainer(item))) { + throw new Error(`\`${filterName}\` can only be applied to array of objects`); + } + if (filter.args.some((x) => x.type !== "StringLiteral")) { + throw new Error(`arguments of \`${filterName}\` must be strings`); + } + const [attr, testName, value] = filter.args.map((x) => this.evaluate(x, environment)); + let testFunction; + if (testName) { + const test = environment.tests.get(testName.value); + if (!test) { + throw new Error(`Unknown test: ${testName.value}`); + } + testFunction = test; + } else { + testFunction = (...x) => x[0].__bool__().value; } - - model_inputs = this._update_model_kwargs_for_generation({ - generated_input_ids, outputs, model_inputs, is_encoder_decoder, + const filtered = operand.value.filter((item) => { + const a = item.value.get(attr.value); + const result = a ? testFunction(a, value) : false; + return select ? result : !result; }); - } - - if (streamer) { - streamer.end(); - } - - // Retrieve and dispose all final past key values (including encoder attentions) - const past_key_values = this.getPastKeyValues(outputs, model_inputs.past_key_values, true); - - // TODO: ensure all_input_ids is padded correctly... - const sequences = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); - - if (generation_config.return_dict_in_generate) { - return { - sequences, - past_key_values, - ...attentions, - // TODO: - // scores, - // logits, - } - } else { - // Dispose all remaining tensors - for (const tensor of Object.values(outputs)) { - if (tensor.location === 'gpu-buffer') { - tensor.dispose(); + return new ArrayValue(filtered); + } + case "map": { + const [, kwargs] = this.evaluateArguments(filter.args, environment); + if (kwargs.has("attribute")) { + const attr = kwargs.get("attribute"); + if (!(attr instanceof StringValue)) { + throw new Error("attribute must be a string"); + } + const defaultValue = kwargs.get("default"); + const mapped = operand.value.map((item) => { + if (!isAttributeContainer(item)) { + throw new Error("items in map must be an object"); } + const value = getAttributeValue(item, attr.value); + return value instanceof UndefinedValue ? defaultValue ?? new UndefinedValue() : value; + }); + return new ArrayValue(mapped); + } else { + throw new Error("`map` expressions without `attribute` set are not currently supported."); } - return sequences; + } } - } - - /** - * Returns an object containing past key values from the given decoder results object. - * - * @param {Object} decoderResults The decoder results object. - * @param {Object} pastKeyValues The previous past key values. - * @returns {Object} An object containing past key values. - */ - getPastKeyValues(decoderResults, pastKeyValues, disposeEncoderPKVs = false) { - const pkvs = Object.create(null); - - for (const name in decoderResults) { - if (name.startsWith('present')) { - const newName = name - .replace('present_conv', 'past_conv') // Hybrid cache architecture (e.g., LFM2) - .replace('present', 'past_key_values'); - const is_encoder_pkv = name.includes('encoder'); - if (is_encoder_pkv && pastKeyValues) { - // Optimization introduced by optimum to reuse past key values. - // So, we just replace the constant outputs (`decoderResults[name]`) with the previous past key values. - // https://github.com/huggingface/optimum/blob/0bf2c05fb7e1182b52d21b703cfc95fd9e4ea3dc/optimum/onnxruntime/base.py#L677-L704 - pkvs[newName] = pastKeyValues[newName]; - } else { // decoder or using first encoder PKVs - pkvs[newName] = decoderResults[name]; - } - - if (pastKeyValues && (!is_encoder_pkv || disposeEncoderPKVs)) { - // - Always dispose decoder PKVs - // - Only dispose encoder past key values when requested (after generation) - const t = pastKeyValues[newName]; - if (t.location === 'gpu-buffer') { - t.dispose(); - } - } + throw new Error(`Unknown ArrayValue filter: ${filterName}`); + } else if (operand instanceof StringValue) { + switch (filterName) { + case "indent": { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + const width = args.at(0) ?? kwargs.get("width") ?? new IntegerValue(4); + if (!(width instanceof IntegerValue)) { + throw new Error("width must be a number"); } - } - return pkvs; - } - - /** - * Returns an object containing attentions from the given model output object. - * - * @param {Object} model_output The output of the model. - * @returns {{cross_attentions?: Tensor[]}} An object containing attentions. - */ - getAttentions(model_output) { - const attentions = {}; - - for (const attnName of ['cross_attentions', 'encoder_attentions', 'decoder_attentions']) { - for (const name in model_output) { - if (name.startsWith(attnName)) { - if (!(attnName in attentions)) { - attentions[attnName] = []; - } - attentions[attnName].push(model_output[name]); - } + const first = args.at(1) ?? kwargs.get("first") ?? new BooleanValue(false); + const blank = args.at(2) ?? kwargs.get("blank") ?? new BooleanValue(false); + const lines = operand.value.split("\n"); + const indent = " ".repeat(width.value); + const indented = lines.map( + (x, i) => !first.value && i === 0 || !blank.value && x.length === 0 ? x : indent + x + ); + return new StringValue(indented.join("\n")); + } + case "replace": { + const replaceFn = operand.builtins.get("replace"); + if (!(replaceFn instanceof FunctionValue)) { + throw new Error("replace filter not available"); } + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + return replaceFn.value([...args, new KeywordArgumentsValue(kwargs)], environment); + } } - return attentions; - } - - /** - * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values. - * - * @param {Object} decoderFeeds The decoder feeds object to add past key values to. - * @param {Object} pastKeyValues An object containing past key values. - */ - addPastKeyValues(decoderFeeds, pastKeyValues) { - if (pastKeyValues) { - Object.assign(decoderFeeds, pastKeyValues) - } else { - const session = this.sessions['decoder_model_merged'] ?? this.sessions['model']; - const batch_size = (decoderFeeds[this.main_input_name] ?? decoderFeeds.attention_mask)?.dims?.[0] ?? 1; - - const dtype = session?.config?.kv_cache_dtype ?? 'float32'; - const cls = (dtype === 'float16') ? _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.DataTypeMap.float16 : _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.DataTypeMap.float32; - const shapes = (0,_configs_js__WEBPACK_IMPORTED_MODULE_0__.getCacheShapes)(this.config, { batch_size }); - for (const name in shapes) { - const size = shapes[name].reduce((a, b) => a * b, 1); - decoderFeeds[name] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor(dtype, new cls(size), shapes[name]); - } + throw new Error(`Unknown StringValue filter: ${filterName}`); + } else if (operand instanceof ObjectValue) { + const builtin = operand.builtins.get(filterName); + if (builtin && builtin instanceof FunctionValue) { + const [args, kwargs] = this.evaluateArguments(filter.args, environment); + if (kwargs.size > 0) { + args.push(new KeywordArgumentsValue(kwargs)); + } + return builtin.value(args, environment); } + throw new Error(`Unknown ObjectValue filter: ${filterName}`); + } else { + throw new Error(`Cannot apply filter "${filterName}" to type: ${operand.type}`); + } } - - async encode_image({ pixel_values }) { - // image_inputs === { pixel_values } - return (await sessionRun(this.sessions['vision_encoder'], { pixel_values })).image_features; - } - - async encode_text({ input_ids }) { - // text_inputs === { input_ids, attention_mask } - return (await sessionRun(this.sessions['embed_tokens'], { input_ids })).inputs_embeds; - } - - async encode_audio({ audio_values }) { - // audio_inputs === { audio_values } - return (await sessionRun(this.sessions['audio_encoder'], { audio_values })).audio_features; - } -} - -////////////////////////////////////////////////// -// Base model output class -class ModelOutput { } - -/** - * Base class for model's outputs, with potential hidden states and attentions. - */ -class BaseModelOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model. - * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. - * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. - */ - constructor({ last_hidden_state, hidden_states = null, attentions = null }) { - super(); - this.last_hidden_state = last_hidden_state; - this.hidden_states = hidden_states; - this.attentions = attentions; - } -} -////////////////////////////////////////////////// -// Bert models -class BertPreTrainedModel extends PreTrainedModel { } -class BertModel extends BertPreTrainedModel { } - -/** - * BertForMaskedLM is a class representing a BERT model for masked language modeling. - */ -class BertForMaskedLM extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } -} - -/** - * BertForSequenceClassification is a class representing a BERT model for sequence classification. - */ -class BertForSequenceClassification extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * BertForTokenClassification is a class representing a BERT model for token classification. - */ -class BertForTokenClassification extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * BertForQuestionAnswering is a class representing a BERT model for question answering. - */ -class BertForQuestionAnswering extends BertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// NeoBert models -class NeoBertPreTrainedModel extends PreTrainedModel { } -class NeoBertModel extends NeoBertPreTrainedModel { } - -class NeoBertForMaskedLM extends NeoBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } -} - -class NeoBertForSequenceClassification extends NeoBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} - -class NeoBertForTokenClassification extends NeoBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} - -class NeoBertForQuestionAnswering extends NeoBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// ModernBert models -class ModernBertPreTrainedModel extends PreTrainedModel { } -class ModernBertModel extends ModernBertPreTrainedModel { } - -class ModernBertForMaskedLM extends ModernBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } -} - -class ModernBertForSequenceClassification extends ModernBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} - -class ModernBertForTokenClassification extends ModernBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// ModernBERT Decoder models -class ModernBertDecoderPreTrainedModel extends PreTrainedModel { } -class ModernBertDecoderModel extends ModernBertDecoderPreTrainedModel { } -class ModernBertDecoderForCausalLM extends ModernBertDecoderPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// NomicBert models -class NomicBertPreTrainedModel extends PreTrainedModel { } -class NomicBertModel extends NomicBertPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// RoFormer models -class RoFormerPreTrainedModel extends PreTrainedModel { } - -/** - * The bare RoFormer Model transformer outputting raw hidden-states without any specific head on top. - */ -class RoFormerModel extends RoFormerPreTrainedModel { } - -/** - * RoFormer Model with a `language modeling` head on top. - */ -class RoFormerForMaskedLM extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } -} - -/** - * RoFormer Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class RoFormerForSequenceClassification extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * RoFormer Model with a token classification head on top (a linear layer on top of the hidden-states output) - * e.g. for Named-Entity-Recognition (NER) tasks. - */ -class RoFormerForTokenClassification extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * RoFormer Model with a span classification head on top for extractive question-answering tasks like SQuAD - * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). - */ -class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } -} -// TODO: Add RoFormerForCausalLM and RoFormerForMultipleChoice -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// ConvBert models -class ConvBertPreTrainedModel extends PreTrainedModel { } - -/** - * The bare ConvBERT Model transformer outputting raw hidden-states without any specific head on top. - */ -class ConvBertModel extends ConvBertPreTrainedModel { } - -/** - * ConvBERT Model with a language modeling head on top. - */ -class ConvBertForMaskedLM extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } -} - -/** - * ConvBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class ConvBertForSequenceClassification extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * ConvBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) - * e.g. for Named-Entity-Recognition (NER) tasks. - */ -class ConvBertForTokenClassification extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * ConvBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD - * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`) - */ -class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Electra models -class ElectraPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Electra Model transformer outputting raw hidden-states without any specific head on top. - * Identical to the BERT model except that it uses an additional linear layer between the embedding - * layer and the encoder if the hidden size and embedding size are different. - */ -class ElectraModel extends ElectraPreTrainedModel { } -// TODO add ElectraForPreTraining -/** - * Electra model with a language modeling head on top. - */ -class ElectraForMaskedLM extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } -} - -/** - * ELECTRA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class ElectraForSequenceClassification extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + throw new Error(`Unknown filter: ${filterNode.type}`); + } + /** + * Evaluates expressions following the filter operation type. + */ + evaluateFilterExpression(node, environment) { + const operand = this.evaluate(node.operand, environment); + return this.applyFilter(operand, node.filter, environment); + } + /** + * Evaluates expressions following the test operation type. + */ + evaluateTestExpression(node, environment) { + const operand = this.evaluate(node.operand, environment); + const test = environment.tests.get(node.test.value); + if (!test) { + throw new Error(`Unknown test: ${node.test.value}`); } -} - -/** - * Electra model with a token classification head on top. - */ -class ElectraForTokenClassification extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + const result = test(operand); + return new BooleanValue(node.negate ? !result : result); + } + /** + * Evaluates expressions following the select operation type. + */ + evaluateSelectExpression(node, environment) { + const predicate = this.evaluate(node.test, environment); + if (!predicate.__bool__().value) { + return new UndefinedValue(); } -} - -/** - * LECTRA Model with a span classification head on top for extractive question-answering tasks like SQuAD - * (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). - */ -class ElectraForQuestionAnswering extends ElectraPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + return this.evaluate(node.lhs, environment); + } + /** + * Evaluates expressions following the unary operation type. + */ + evaluateUnaryExpression(node, environment) { + const argument = this.evaluate(node.argument, environment); + switch (node.operator.value) { + case "not": + return new BooleanValue(!argument.value); + case "+": + case "-": { + const sign = node.operator.value === "-" ? -1 : 1; + if (argument instanceof IntegerValue || argument instanceof FloatValue || argument instanceof BooleanValue) { + const value = argument instanceof BooleanValue ? argument.value ? 1 : 0 : argument.value; + const result = sign * value; + return argument instanceof FloatValue ? new FloatValue(result) : new IntegerValue(result); + } + throw new SyntaxError(`Unknown operator "${node.operator.value}" for ${argument.type}`); + } + default: + throw new SyntaxError(`Unknown operator: ${node.operator.value}`); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// CamemBERT models -class CamembertPreTrainedModel extends PreTrainedModel { } - -/** - * The bare CamemBERT Model transformer outputting raw hidden-states without any specific head on top. - */ -class CamembertModel extends CamembertPreTrainedModel { } - -/** - * CamemBERT Model with a `language modeling` head on top. - */ -class CamembertForMaskedLM extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + } + evaluateTernaryExpression(node, environment) { + const cond = this.evaluate(node.condition, environment); + return cond.__bool__().value ? this.evaluate(node.trueExpr, environment) : this.evaluate(node.falseExpr, environment); + } + evalProgram(program, environment) { + return this.evaluateBlock(program.body, environment); + } + evaluateBlock(statements, environment) { + let result = ""; + for (const statement of statements) { + const lastEvaluated = this.evaluate(statement, environment); + if (lastEvaluated.type !== "NullValue" && lastEvaluated.type !== "UndefinedValue") { + result += lastEvaluated.toString(); + } } -} - -/** - * CamemBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. - */ -class CamembertForSequenceClassification extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + return new StringValue(result); + } + evaluateIdentifier(node, environment) { + return environment.lookupVariable(node.value); + } + evaluateCallExpression(expr, environment) { + const [args, kwargs] = this.evaluateArguments(expr.args, environment); + if (kwargs.size > 0) { + args.push(new KeywordArgumentsValue(kwargs)); } -} - -/** - * CamemBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. - */ -class CamembertForTokenClassification extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + const fn2 = this.evaluate(expr.callee, environment); + if (fn2.type !== "FunctionValue") { + throw new Error(`Cannot call something that is not a function: got ${fn2.type}`); } -} - -/** - * CamemBERT Model with a span classification head on top for extractive question-answering tasks - */ -class CamembertForQuestionAnswering extends CamembertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + return fn2.value(args, environment); + } + evaluateSliceExpression(object, expr, environment) { + if (!(object instanceof ArrayValue || object instanceof StringValue)) { + throw new Error("Slice object must be an array or string"); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// DeBERTa models -class DebertaPreTrainedModel extends PreTrainedModel { } - -/** - * The bare DeBERTa Model transformer outputting raw hidden-states without any specific head on top. - */ -class DebertaModel extends DebertaPreTrainedModel { } - -/** - * DeBERTa Model with a `language modeling` head on top. - */ -class DebertaForMaskedLM extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + const start = this.evaluate(expr.start, environment); + const stop = this.evaluate(expr.stop, environment); + const step = this.evaluate(expr.step, environment); + if (!(start instanceof IntegerValue || start instanceof UndefinedValue)) { + throw new Error("Slice start must be numeric or undefined"); } -} - -/** - * DeBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class DebertaForSequenceClassification extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + if (!(stop instanceof IntegerValue || stop instanceof UndefinedValue)) { + throw new Error("Slice stop must be numeric or undefined"); } -} - -/** - * DeBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. - */ -class DebertaForTokenClassification extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + if (!(step instanceof IntegerValue || step instanceof UndefinedValue)) { + throw new Error("Slice step must be numeric or undefined"); } -} - -/** - * DeBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear - * layers on top of the hidden-states output to compute `span start logits` and `span end logits`). - */ -class DebertaForQuestionAnswering extends DebertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + if (object instanceof ArrayValue) { + return new ArrayValue(slice(object.value, start.value, stop.value, step.value)); + } else { + return new StringValue(slice(Array.from(object.value), start.value, stop.value, step.value).join("")); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// DeBERTa-v2 models -class DebertaV2PreTrainedModel extends PreTrainedModel { } - -/** - * The bare DeBERTa-V2 Model transformer outputting raw hidden-states without any specific head on top. - */ -class DebertaV2Model extends DebertaV2PreTrainedModel { } - -/** - * DeBERTa-V2 Model with a `language modeling` head on top. - */ -class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + } + evaluateMemberExpression(expr, environment) { + const object = this.evaluate(expr.object, environment); + let property; + if (expr.computed) { + if (expr.property.type === "SliceExpression") { + return this.evaluateSliceExpression(object, expr.property, environment); + } else { + property = this.evaluate(expr.property, environment); + } + } else if (expr.property.type === "IntegerLiteral") { + property = new IntegerValue(expr.property.value); + } else { + property = new StringValue(expr.property.value); } -} - -/** - * DeBERTa-V2 Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + let value; + if (isAttributeContainer(object)) { + if (!(property instanceof StringValue)) { + throw new Error(`Cannot access property with non-string: got ${property.type}`); + } + value = object.value.get(property.value) ?? (object instanceof ObjectValue ? object.builtins.get(property.value) : void 0); + } else if (object instanceof ArrayValue || object instanceof StringValue) { + if (property instanceof IntegerValue) { + value = object.value.at(property.value); + if (object instanceof StringValue) { + value = new StringValue(object.value.at(property.value)); + } + } else if (property instanceof StringValue) { + value = object.builtins.get(property.value); + } else { + throw new Error(`Cannot access property with non-string/non-number: got ${property.type}`); + } + } else { + if (!(property instanceof StringValue)) { + throw new Error(`Cannot access property with non-string: got ${property.type}`); + } + value = object.builtins.get(property.value); } -} - -/** - * DeBERTa-V2 Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks. - */ -class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + return value instanceof RuntimeValue ? value : new UndefinedValue(); + } + evaluateSet(node, environment) { + const rhs = node.value ? this.evaluate(node.value, environment) : this.evaluateBlock(node.body, environment); + if (node.assignee.type === "Identifier") { + const variableName = node.assignee.value; + environment.setVariable(variableName, rhs); + } else if (node.assignee.type === "TupleLiteral") { + const tuple = node.assignee; + if (!(rhs instanceof ArrayValue)) { + throw new Error(`Cannot unpack non-iterable type in set: ${rhs.type}`); + } + const arr = rhs.value; + if (arr.length !== tuple.value.length) { + throw new Error(`Too ${tuple.value.length > arr.length ? "few" : "many"} items to unpack in set`); + } + for (let i = 0; i < tuple.value.length; ++i) { + const elem = tuple.value[i]; + if (elem.type !== "Identifier") { + throw new Error(`Cannot unpack to non-identifier in set: ${elem.type}`); + } + environment.setVariable(elem.value, arr[i]); + } + } else if (node.assignee.type === "MemberExpression") { + const member = node.assignee; + const object = this.evaluate(member.object, environment); + if (!(object instanceof NamespaceValue)) { + throw new Error("cannot assign attribute on non-namespace object"); + } + if (member.property.type !== "Identifier") { + throw new Error("Cannot assign to member with non-identifier property"); + } + object.value.set(member.property.value, rhs); + } else { + throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(node.assignee)}`); } -} - -/** - * DeBERTa-V2 Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear - * layers on top of the hidden-states output to compute `span start logits` and `span end logits`). - */ -class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + return new NullValue(); + } + evaluateIf(node, environment) { + const test = this.evaluate(node.test, environment); + return this.evaluateBlock(test.__bool__().value ? node.body : node.alternate, environment); + } + evaluateFor(node, environment) { + const scope = new Environment(environment); + let test, iterable; + if (node.iterable.type === "SelectExpression") { + const select = node.iterable; + iterable = this.evaluate(select.lhs, scope); + test = select.test; + } else { + iterable = this.evaluate(node.iterable, scope); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// DistilBert models -class DistilBertPreTrainedModel extends PreTrainedModel { } -class DistilBertModel extends DistilBertPreTrainedModel { } - -/** - * DistilBertForSequenceClassification is a class representing a DistilBERT model for sequence classification. - */ -class DistilBertForSequenceClassification extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + if (!(iterable instanceof ArrayValue || iterable instanceof ObjectValue)) { + throw new Error(`Expected iterable or object type in for loop: got ${iterable.type}`); } -} - -/** - * DistilBertForTokenClassification is a class representing a DistilBERT model for token classification. - */ -class DistilBertForTokenClassification extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + if (iterable instanceof ObjectValue) { + iterable = iterable.keys(); } -} - - -/** - * DistilBertForQuestionAnswering is a class representing a DistilBERT model for question answering. - */ -class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + const items = []; + const scopeUpdateFunctions = []; + for (let i = 0; i < iterable.value.length; ++i) { + const loopScope = new Environment(scope); + const current = iterable.value[i]; + let scopeUpdateFunction; + if (node.loopvar.type === "Identifier") { + scopeUpdateFunction = (scope2) => scope2.setVariable(node.loopvar.value, current); + } else if (node.loopvar.type === "TupleLiteral") { + const loopvar = node.loopvar; + if (current.type !== "ArrayValue") { + throw new Error(`Cannot unpack non-iterable type: ${current.type}`); + } + const c = current; + if (loopvar.value.length !== c.value.length) { + throw new Error(`Too ${loopvar.value.length > c.value.length ? "few" : "many"} items to unpack`); + } + scopeUpdateFunction = (scope2) => { + for (let j2 = 0; j2 < loopvar.value.length; ++j2) { + if (loopvar.value[j2].type !== "Identifier") { + throw new Error(`Cannot unpack non-identifier type: ${loopvar.value[j2].type}`); + } + scope2.setVariable(loopvar.value[j2].value, c.value[j2]); + } + }; + } else { + throw new Error(`Invalid loop variable(s): ${node.loopvar.type}`); + } + if (test) { + scopeUpdateFunction(loopScope); + const testValue = this.evaluate(test, loopScope); + if (!testValue.__bool__().value) { + continue; + } + } + items.push(current); + scopeUpdateFunctions.push(scopeUpdateFunction); } -} - -/** - * DistilBertForMaskedLM is a class representing a DistilBERT model for masking task. - */ -class DistilBertForMaskedLM extends DistilBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + let result = ""; + let noIteration = true; + for (let i = 0; i < items.length; ++i) { + const loop = /* @__PURE__ */ new Map([ + ["index", new IntegerValue(i + 1)], + ["index0", new IntegerValue(i)], + ["revindex", new IntegerValue(items.length - i)], + ["revindex0", new IntegerValue(items.length - i - 1)], + ["first", new BooleanValue(i === 0)], + ["last", new BooleanValue(i === items.length - 1)], + ["length", new IntegerValue(items.length)], + ["previtem", i > 0 ? items[i - 1] : new UndefinedValue()], + ["nextitem", i < items.length - 1 ? items[i + 1] : new UndefinedValue()] + ]); + scope.setVariable("loop", new ObjectValue(loop)); + scopeUpdateFunctions[i](scope); + try { + const evaluated = this.evaluateBlock(node.body, scope); + result += evaluated.value; + } catch (err) { + if (err instanceof ContinueControl) { + continue; + } + if (err instanceof BreakControl) { + break; + } + throw err; + } + noIteration = false; } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// ESM models -class EsmPreTrainedModel extends PreTrainedModel { } - -/** - * The bare ESM Model transformer outputting raw hidden-states without any specific head on top. - */ -class EsmModel extends EsmPreTrainedModel { } - -/** - * ESM Model with a `language modeling` head on top. - */ -class EsmForMaskedLM extends EsmPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + if (noIteration) { + const defaultEvaluated = this.evaluateBlock(node.defaultBlock, scope); + result += defaultEvaluated.value; } -} - -/** - * ESM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class EsmForSequenceClassification extends EsmPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + return new StringValue(result); + } + /** + * Bind every parameter name and special argument before evaluating defaults, + * preventing unbound parameters from resolving in an outer scope. + */ + bindMacroArguments(displayName, parameters, specialArguments, args, scope) { + const positionalArguments = args.slice(); + let keywordArguments = /* @__PURE__ */ new Map(); + if (positionalArguments.at(-1) instanceof KeywordArgumentsValue) { + keywordArguments = new Map(positionalArguments.pop().value); + } + const pendingDefaults = []; + for (let i = 0; i < parameters.length; ++i) { + const { name, defaultValue } = getParameterDescriptor(parameters[i]); + let value = positionalArguments[i]; + if (value === void 0 && keywordArguments.has(name)) { + value = keywordArguments.get(name); + keywordArguments.delete(name); + } + if (value === void 0 && defaultValue !== void 0) { + pendingDefaults.push([name, defaultValue]); + } + scope.setVariable(name, value ?? new UndefinedValue()); } -} - -/** - * ESM Model with a token classification head on top (a linear layer on top of the hidden-states output) - * e.g. for Named-Entity-Recognition (NER) tasks. - */ -class EsmForTokenClassification extends EsmPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + if (specialArguments.has("kwargs")) { + scope.setVariable("kwargs", new ObjectValue(keywordArguments)); + } else if (keywordArguments.size > 0) { + throw new Error(`macro ${displayName} takes no keyword argument '${keywordArguments.keys().next().value}'`); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// MobileBert models -class MobileBertPreTrainedModel extends PreTrainedModel { } -class MobileBertModel extends MobileBertPreTrainedModel { } - -/** - * MobileBertForMaskedLM is a class representing a MobileBERT model for masking task. - */ -class MobileBertForMaskedLM extends MobileBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + if (specialArguments.has("varargs")) { + scope.setVariable("varargs", new ArrayValue(positionalArguments.slice(parameters.length))); + } else if (positionalArguments.length > parameters.length) { + throw new Error(`macro ${displayName} takes not more than ${parameters.length} argument(s)`); } -} - -/** - * MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class MobileBertForSequenceClassification extends MobileBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + for (const [name, defaultValue] of pendingDefaults) { + scope.setVariable(name, this.evaluate(defaultValue, scope)); } -} - -/** - * MobileBert Model with a span classification head on top for extractive question-answering tasks - */ -class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } + /** + * See https://jinja.palletsprojects.com/en/3.1.x/templates/#macros for more information. + */ + evaluateMacro(node, environment) { + const specialArguments = findAccessedSpecialMacroArguments(node.args, node.body); + environment.setVariable( + node.name.value, + new FunctionValue((args, scope) => { + const macroScope = new Environment(scope); + this.bindMacroArguments(`'${node.name.value}'`, node.args, specialArguments, args, macroScope); + return this.evaluateBlock(node.body, macroScope); + }) + ); + return new NullValue(); + } + evaluateCallStatement(node, environment) { + const parameters = node.callerArgs ?? []; + const specialArguments = findAccessedSpecialMacroArguments(parameters, node.body); + const callerFn = new FunctionValue((callerArguments) => { + const callBlockEnv = new Environment(environment); + this.bindMacroArguments("None", parameters, specialArguments, callerArguments, callBlockEnv); + return this.evaluateBlock(node.body, callBlockEnv); + }); + const [macroArgs, macroKwargs] = this.evaluateArguments(node.call.args, environment); + macroArgs.push(new KeywordArgumentsValue(macroKwargs)); + const fn2 = this.evaluate(node.call.callee, environment); + if (fn2.type !== "FunctionValue") { + throw new Error(`Cannot call something that is not a function: got ${fn2.type}`); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MPNet models -class MPNetPreTrainedModel extends PreTrainedModel { } - -/** - * The bare MPNet Model transformer outputting raw hidden-states without any specific head on top. - */ -class MPNetModel extends MPNetPreTrainedModel { } - -/** - * MPNetForMaskedLM is a class representing a MPNet model for masked language modeling. - */ -class MPNetForMaskedLM extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for masked language modeling. - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + const newEnv = new Environment(environment); + newEnv.setVariable("caller", callerFn); + return fn2.value(macroArgs, newEnv); + } + evaluateFilterStatement(node, environment) { + const rendered = this.evaluateBlock(node.body, environment); + return this.applyFilter(rendered, node.filter, environment); + } + evaluate(statement, environment) { + if (!statement) { + return new UndefinedValue(); } -} - -/** - * MPNetForSequenceClassification is a class representing a MPNet model for sequence classification. - */ -class MPNetForSequenceClassification extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + switch (statement.type) { + case "Program": + return this.evalProgram(statement, environment); + case "Set": + return this.evaluateSet(statement, environment); + case "If": + return this.evaluateIf(statement, environment); + case "For": + return this.evaluateFor(statement, environment); + case "Macro": + return this.evaluateMacro(statement, environment); + case "CallStatement": + return this.evaluateCallStatement(statement, environment); + case "Break": + throw new BreakControl(); + case "Continue": + throw new ContinueControl(); + case "IntegerLiteral": + return new IntegerValue(statement.value); + case "FloatLiteral": + return new FloatValue(statement.value); + case "StringLiteral": + return new StringValue(statement.value); + case "ArrayLiteral": + return new ArrayValue(statement.value.map((x) => this.evaluate(x, environment))); + case "TupleLiteral": + return new TupleValue(statement.value.map((x) => this.evaluate(x, environment))); + case "ObjectLiteral": { + const mapping = /* @__PURE__ */ new Map(); + for (const [key, value] of statement.value) { + const evaluatedKey = this.evaluate(key, environment); + if (!(evaluatedKey instanceof StringValue)) { + throw new Error(`Object keys must be strings: got ${evaluatedKey.type}`); + } + mapping.set(evaluatedKey.value, this.evaluate(value, environment)); + } + return new ObjectValue(mapping); + } + case "Identifier": + return this.evaluateIdentifier(statement, environment); + case "CallExpression": + return this.evaluateCallExpression(statement, environment); + case "MemberExpression": + return this.evaluateMemberExpression(statement, environment); + case "UnaryExpression": + return this.evaluateUnaryExpression(statement, environment); + case "BinaryExpression": + return this.evaluateBinaryExpression(statement, environment); + case "FilterExpression": + return this.evaluateFilterExpression(statement, environment); + case "FilterStatement": + return this.evaluateFilterStatement(statement, environment); + case "TestExpression": + return this.evaluateTestExpression(statement, environment); + case "SelectExpression": + return this.evaluateSelectExpression(statement, environment); + case "Ternary": + return this.evaluateTernaryExpression(statement, environment); + case "Comment": + return new NullValue(); + default: + throw new SyntaxError(`Unknown node type: ${statement.type}`); } + } +}; +function convertToRuntimeValues(input) { + switch (typeof input) { + case "number": + return Number.isInteger(input) ? new IntegerValue(input) : new FloatValue(input); + case "string": + return new StringValue(input); + case "boolean": + return new BooleanValue(input); + case "undefined": + return new UndefinedValue(); + case "object": + if (input === null) { + return new NullValue(); + } else if (Array.isArray(input)) { + return new ArrayValue(input.map(convertToRuntimeValues)); + } else { + return new ObjectValue( + new Map(Object.entries(input).map(([key, value]) => [key, convertToRuntimeValues(value)])) + ); + } + case "function": + return new FunctionValue((args, _scope) => { + const result = input(...args.map((x) => x.value)) ?? null; + return convertToRuntimeValues(result); + }); + default: + throw new Error(`Cannot convert to runtime value: ${input}`); + } } - -/** - * MPNetForTokenClassification is a class representing a MPNet model for token classification. - */ -class MPNetForTokenClassification extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } +var NEWLINE = "\n"; +var OPEN_STATEMENT = "{%- "; +var CLOSE_STATEMENT = " -%}"; +var PRECEDENCE = Object.freeze({ + CONDITIONAL: 0, + // a if b else c + LOGICAL_OR: 1, + // or + LOGICAL_AND: 2, + // and + LOGICAL_NOT: 3, + // not a + COMPARISON: 4, + // == != < <= > >= in, not in + ADDITIVE: 5, + // + - + MULTIPLICATIVE: 6, + // * / // % + EXPONENTIATION: 7, + // ** + TEST: 8, + // is + FILTER: 9, + // | + UNARY_SIGN: 10, + // -a +a + ATOM: 11 + // literals, identifiers, calls, member accesses +}); +function getBinaryOperatorPrecedence(expr) { + switch (expr.operator.type) { + case "ExponentiationBinaryOperator": + return PRECEDENCE.EXPONENTIATION; + case "MultiplicativeBinaryOperator": + return PRECEDENCE.MULTIPLICATIVE; + case "AdditiveBinaryOperator": + return PRECEDENCE.ADDITIVE; + case "ComparisonBinaryOperator": + return PRECEDENCE.COMPARISON; + case "Identifier": + if (expr.operator.value === "and") { + return PRECEDENCE.LOGICAL_AND; + } + if (expr.operator.value === "in" || expr.operator.value === "not in") { + return PRECEDENCE.COMPARISON; + } + return PRECEDENCE.LOGICAL_OR; + } + return PRECEDENCE.LOGICAL_OR; } - -/** - * MPNetForQuestionAnswering is a class representing a MPNet model for question answering. - */ -class MPNetForQuestionAnswering extends MPNetPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for question answering. - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } +function getPrecedence(node) { + switch (node.type) { + case "SelectExpression": + case "Ternary": + return PRECEDENCE.CONDITIONAL; + case "BinaryExpression": + return getBinaryOperatorPrecedence(node); + case "UnaryExpression": + return node.operator.value === "not" ? PRECEDENCE.LOGICAL_NOT : PRECEDENCE.UNARY_SIGN; + case "TestExpression": + return PRECEDENCE.TEST; + case "FilterExpression": + return PRECEDENCE.FILTER; + default: + return PRECEDENCE.ATOM; + } } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// SqueezeBert models -class SqueezeBertPreTrainedModel extends PreTrainedModel { } -class SqueezeBertModel extends SqueezeBertPreTrainedModel { } -class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } +function formatOperand(node, minPrecedence) { + const expr = formatExpression(node); + return getPrecedence(node) < minPrecedence ? `(${expr})` : expr; } -class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } +function format(program, indent = " ") { + const indentStr = typeof indent === "number" ? " ".repeat(indent) : indent; + const body = formatStatements(program.body, 0, indentStr); + return body.replace(/\n$/, ""); +} +function createStatement(...text) { + return OPEN_STATEMENT + text.join(" ") + CLOSE_STATEMENT; } -class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } +function formatStatements(stmts, depth, indentStr) { + return stmts.map((stmt) => formatStatement(stmt, depth, indentStr)).join(NEWLINE); } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Albert models -class AlbertPreTrainedModel extends PreTrainedModel { } -class AlbertModel extends AlbertPreTrainedModel { } -class AlbertForSequenceClassification extends AlbertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } +function formatExpressionList(expressions) { + return expressions.map((expression) => formatExpression(expression)).join(", "); } -class AlbertForQuestionAnswering extends AlbertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } +function formatStatement(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + switch (node.type) { + case "Program": + return formatStatements(node.body, depth, indentStr); + case "If": + return formatIf(node, depth, indentStr); + case "For": + return formatFor(node, depth, indentStr); + case "Set": + return formatSet(node, depth, indentStr); + case "Macro": + return formatMacro(node, depth, indentStr); + case "Break": + return pad + createStatement("break"); + case "Continue": + return pad + createStatement("continue"); + case "CallStatement": + return formatCallStatement(node, depth, indentStr); + case "FilterStatement": + return formatFilterStatement(node, depth, indentStr); + case "Comment": + return pad + "{# " + node.value + " #}"; + default: + return pad + "{{- " + formatExpression(node) + " -}}"; + } } -class AlbertForMaskedLM extends AlbertPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); +function formatIf(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const clauses = []; + let current = node; + while (current) { + clauses.push({ test: current.test, body: current.body }); + if (current.alternate.length === 1 && current.alternate[0].type === "If") { + current = current.alternate[0]; + } else { + break; } + } + let out = pad + createStatement("if", formatExpression(clauses[0].test)) + NEWLINE + formatStatements(clauses[0].body, depth + 1, indentStr); + for (let i = 1; i < clauses.length; ++i) { + out += NEWLINE + pad + createStatement("elif", formatExpression(clauses[i].test)) + NEWLINE + formatStatements(clauses[i].body, depth + 1, indentStr); + } + if (current && current.alternate.length > 0) { + out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(current.alternate, depth + 1, indentStr); + } + out += NEWLINE + pad + createStatement("endif"); + return out; } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// T5 models -class T5PreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - 'attention_mask', - 'encoder_outputs', - 'decoder_input_ids', - 'decoder_attention_mask', - 'past_key_values', - ]; -}; - -class T5Model extends T5PreTrainedModel { } - -/** - * T5Model is a class representing a T5 model for conditional generation. - */ -class T5ForConditionalGeneration extends T5PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// LONGT5 models -/** - * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. - */ -class LongT5PreTrainedModel extends PreTrainedModel { }; - -/** - * The bare LONGT5 Model transformer outputting raw hidden-states without any specific head on top. - */ -class LongT5Model extends LongT5PreTrainedModel { } - -/** - * LONGT5 Model with a `language modeling` head on top. - */ -class LongT5ForConditionalGeneration extends LongT5PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// MT5 models -class MT5PreTrainedModel extends PreTrainedModel { }; - -class MT5Model extends MT5PreTrainedModel { } - -/** - * A class representing a conditional sequence-to-sequence model based on the MT5 architecture. - */ -class MT5ForConditionalGeneration extends MT5PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Bart models -class BartPretrainedModel extends PreTrainedModel { }; - -/** - * The bare BART Model outputting raw hidden-states without any specific head on top. - */ -class BartModel extends BartPretrainedModel { } - -/** - * The BART Model with a language modeling head. Can be used for summarization. - */ -class BartForConditionalGeneration extends BartPretrainedModel { } - -/** - * Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) - */ -class BartForSequenceClassification extends BartPretrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } +function formatFor(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + let formattedIterable = ""; + if (node.iterable.type === "SelectExpression") { + const n = node.iterable; + formattedIterable = `${formatExpression(n.lhs)} if ${formatExpression(n.test)}`; + } else { + formattedIterable = formatExpression(node.iterable); + } + let out = pad + createStatement("for", formatExpression(node.loopvar), "in", formattedIterable) + NEWLINE + formatStatements(node.body, depth + 1, indentStr); + if (node.defaultBlock.length > 0) { + out += NEWLINE + pad + createStatement("else") + NEWLINE + formatStatements(node.defaultBlock, depth + 1, indentStr); + } + out += NEWLINE + pad + createStatement("endfor"); + return out; } - -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MBart models -class MBartPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare MBART Model outputting raw hidden-states without any specific head on top. - */ -class MBartModel extends MBartPreTrainedModel { } - -/** - * The MBART Model with a language modeling head. Can be used for summarization, after fine-tuning the pretrained models. - */ -class MBartForConditionalGeneration extends MBartPreTrainedModel { } - -/** - * MBart model with a sequence classification/head on top (a linear layer on top of the pooled output). - */ -class MBartForSequenceClassification extends MBartPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } +function formatSet(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const left = formatExpression(node.assignee); + const right = node.value ? formatExpression(node.value) : ""; + const value = pad + createStatement("set", `${left}${node.value ? " = " + right : ""}`); + if (node.body.length === 0) { + return value; + } + return value + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endset"); } - - -class MBartForCausalLM extends MBartPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Blenderbot models -class BlenderbotPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare Blenderbot Model outputting raw hidden-states without any specific head on top. - */ -class BlenderbotModel extends BlenderbotPreTrainedModel { } - -/** - * The Blenderbot Model with a language modeling head. Can be used for summarization. - */ -class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Blenderbot models -class BlenderbotSmallPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top. - */ -class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel { } - -/** - * The BlenderbotSmall Model with a language modeling head. Can be used for summarization. - */ -class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Roberta models -class RobertaPreTrainedModel extends PreTrainedModel { } -class RobertaModel extends RobertaPreTrainedModel { } - -/** - * RobertaForMaskedLM class for performing masked language modeling on Roberta models. - */ -class RobertaForMaskedLM extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); - } +function formatMacro(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const args = formatExpressionList(node.args); + return pad + createStatement("macro", `${node.name.value}(${args})`) + NEWLINE + formatStatements(node.body, depth + 1, indentStr) + NEWLINE + pad + createStatement("endmacro"); } - -/** - * RobertaForSequenceClassification class for performing sequence classification on Roberta models. - */ -class RobertaForSequenceClassification extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } +function formatCallStatement(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const params = node.callerArgs && node.callerArgs.length > 0 ? `(${formatExpressionList(node.callerArgs)})` : ""; + const callExpr = formatExpression(node.call); + let out = pad + createStatement(`call${params}`, callExpr) + NEWLINE; + out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE; + out += pad + createStatement("endcall"); + return out; } - -/** - * RobertaForTokenClassification class for performing token classification on Roberta models. - */ -class RobertaForTokenClassification extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } +function formatFilterStatement(node, depth, indentStr) { + const pad = indentStr.repeat(depth); + const spec = node.filter.type === "Identifier" ? node.filter.value : formatExpression(node.filter); + let out = pad + createStatement("filter", spec) + NEWLINE; + out += formatStatements(node.body, depth + 1, indentStr) + NEWLINE; + out += pad + createStatement("endfilter"); + return out; } - -/** - * RobertaForQuestionAnswering class for performing question answering on Roberta models. - */ -class RobertaForQuestionAnswering extends RobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); +function formatExpression(node) { + switch (node.type) { + case "SpreadExpression": { + const n = node; + return `*${formatExpression(n.argument)}`; } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// XLM models -/** - * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. - */ -class XLMPreTrainedModel extends PreTrainedModel { } - -/** - * The bare XLM Model transformer outputting raw hidden-states without any specific head on top. - */ -class XLMModel extends XLMPreTrainedModel { } - -/** - * The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). - */ -class XLMWithLMHeadModel extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + case "KeywordSpreadExpression": { + const n = node; + return `**${formatExpression(n.argument)}`; } -} - -/** - * XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) - */ -class XLMForSequenceClassification extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + case "Identifier": + return node.value; + case "IntegerLiteral": + return `${node.value}`; + case "FloatLiteral": { + const value = node.value; + if (Object.is(value, -0)) { + return "-0.0"; + } + return value % 1 === 0 ? value.toFixed(1) : value.toString(); } -} - -/** - * XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) - */ -class XLMForTokenClassification extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + case "StringLiteral": + return JSON.stringify(node.value); + case "BinaryExpression": { + const n = node; + const thisPrecedence = getBinaryOperatorPrecedence(n); + const left = formatOperand(n.left, thisPrecedence); + const right = formatOperand(n.right, thisPrecedence + 1); + return `${left} ${n.operator.value} ${right}`; } -} - -/** - * XLM Model with a span classification head on top for extractive question-answering tasks - */ -class XLMForQuestionAnswering extends XLMPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + case "UnaryExpression": { + const n = node; + const operandPrecedence = n.argument.type === "UnaryExpression" ? getPrecedence(n) : PRECEDENCE.ATOM; + return n.operator.value + (n.operator.value === "not" ? " " : "") + formatOperand(n.argument, operandPrecedence); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// XLMRoberta models -class XLMRobertaPreTrainedModel extends PreTrainedModel { } -class XLMRobertaModel extends XLMRobertaPreTrainedModel { } - -/** - * XLMRobertaForMaskedLM class for performing masked language modeling on XLMRoberta models. - */ -class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new MaskedLMOutput(await super._call(model_inputs)); + case "CallExpression": { + const n = node; + const args = formatExpressionList(n.args); + return `${formatExpression(n.callee)}(${args})`; } -} - -/** - * XLMRobertaForSequenceClassification class for performing sequence classification on XLMRoberta models. - */ -class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + case "MemberExpression": { + const n = node; + const obj = formatOperand(n.object, PRECEDENCE.ATOM); + let prop = formatExpression(n.property); + if (!n.computed && n.property.type !== "Identifier" && n.property.type !== "IntegerLiteral") { + prop = `(${prop})`; + } + return n.computed ? `${obj}[${prop}]` : `${obj}.${prop}`; } -} - -/** - * XLMRobertaForTokenClassification class for performing token classification on XLMRoberta models. - */ -class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for token classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); + case "FilterExpression": { + const n = node; + const operand = formatOperand(n.operand, PRECEDENCE.FILTER); + if (n.filter.type === "CallExpression") { + return `${operand} | ${formatExpression(n.filter)}`; + } + return `${operand} | ${n.filter.value}`; } -} - -/** - * XLMRobertaForQuestionAnswering class for performing question answering on XLMRoberta models. - */ -class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel { - /** - * Calls the model on new inputs. - * - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} returned object - */ - async _call(model_inputs) { - return new QuestionAnsweringModelOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Audio Spectrogram Transformer (AST) models -class ASTPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare AST Model transformer outputting raw hidden-states without any specific head on top. - */ -class ASTModel extends ASTPreTrainedModel { } - -/** - * Audio Spectrogram Transformer model with an audio classification head on top - * (a linear layer on top of the pooled output) e.g. for datasets like AudioSet, Speech Commands v2. - */ -class ASTForAudioClassification extends ASTPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Whisper models -class WhisperPreTrainedModel extends PreTrainedModel { - - requires_attention_mask = false; - main_input_name = 'input_features'; - forward_params = [ - 'input_features', - 'attention_mask', - 'decoder_input_ids', - 'decoder_attention_mask', - 'past_key_values', - ]; -}; - -/** - * WhisperModel class for training Whisper models without a language model head. - */ -class WhisperModel extends WhisperPreTrainedModel { } - - -/** - * WhisperForConditionalGeneration class for generating conditional outputs from Whisper models. - */ -class WhisperForConditionalGeneration extends WhisperPreTrainedModel { - - _prepare_generation_config(generation_config, kwargs) { - return /** @type {WhisperGenerationConfig} */ (super._prepare_generation_config(generation_config, kwargs, _models_whisper_generation_whisper_js__WEBPACK_IMPORTED_MODULE_15__.WhisperGenerationConfig)); + case "SelectExpression": { + const n = node; + return `${formatOperand(n.lhs, PRECEDENCE.LOGICAL_OR)} if ${formatOperand(n.test, PRECEDENCE.LOGICAL_OR)}`; + } + case "TestExpression": { + const n = node; + return `${formatOperand(n.operand, PRECEDENCE.TEST)} is${n.negate ? " not" : ""} ${n.test.value}`; } - - /** - * - * @param {WhisperGenerationConfig} generation_config - */ - _retrieve_init_tokens(generation_config) { - // prefix tokens are of the form: - // - Multilingual: <|startoftranscript|> <|lang_id|> <|task|> [<|notimestamps|>] - // - English-only: <|startoftranscript|> [<|notimestamps|>] - - // 1. Handle <|startoftranscript|> token - const init_tokens = [generation_config.decoder_start_token_id]; - - // 2. Handle <|lang_id|> and <|task> tokens - let language = generation_config.language; - const task = generation_config.task; - if (generation_config.is_multilingual) { - if (!language) { - // TODO: Implement language detection - console.warn('No language specified - defaulting to English (en).'); - language = 'en'; - } - - // Add language token - const language_code = (0,_models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_16__.whisper_language_to_code)(language); - const language_token = `<|${language_code}|>`; - init_tokens.push(generation_config.lang_to_id[language_token]) - - // Add task token - // NOTE: Defaults to 'transcribe' if no task is specified - init_tokens.push(generation_config.task_to_id[task ?? 'transcribe']); - - } else if (language || task) { - 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." - ) - } - - // 3. Handle <|notimestamps|> token - if ( - !generation_config.return_timestamps - && generation_config.no_timestamps_token_id - && init_tokens.at(-1) !== generation_config.no_timestamps_token_id - ) { - init_tokens.push(generation_config.no_timestamps_token_id); - } else if ( - generation_config.return_timestamps - && - init_tokens.at(-1) === generation_config.no_timestamps_token_id - ) { - console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."); - init_tokens.pop(); - } - - // let's make sure we don't pass `null` tokens as prompt tokens - return init_tokens.filter(token => token != null); + case "ArrayLiteral": + case "TupleLiteral": { + const elems = formatExpressionList(node.value); + const brackets = node.type === "ArrayLiteral" ? "[]" : "()"; + return `${brackets[0]}${elems}${brackets[1]}`; } - - /** - * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids. - * @param {import('./models/whisper/generation_whisper.js').WhisperGenerationFunctionParameters} options - * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. - */ - async generate({ - inputs = null, - generation_config = null, - logits_processor = null, - stopping_criteria = null, - - // Whisper-specific options (passed to kwargs) - // prompt_ids = null, - // language = null, - // task = null, - - ...kwargs - }) { - generation_config = this._prepare_generation_config(generation_config, kwargs); - - const init_tokens = kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config); - - if (generation_config.return_timestamps) { - logits_processor ??= new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); - logits_processor.push( - new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.WhisperTimeStampLogitsProcessor(generation_config, init_tokens) - ); - } - - if (generation_config.begin_suppress_tokens) { - logits_processor ??= new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.LogitsProcessorList(); - logits_processor.push( - new _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_7__.SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length) - ); - } - - if (generation_config.return_token_timestamps) { - if (!generation_config.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." - ) - } - - if (generation_config.task === 'translate') { - console.warn("Token-level timestamps may not be reliable for task 'translate'.") - } - - generation_config.output_attentions = true; - generation_config.return_dict_in_generate = true; - } - - const outputs = await super.generate({ - inputs, - generation_config, - logits_processor, - decoder_input_ids: init_tokens, - ...kwargs - }); - - if (generation_config.return_token_timestamps) { - outputs["token_timestamps"] = this._extract_token_timestamps( - // @ts-expect-error TS2345 - outputs, - generation_config.alignment_heads, - generation_config.num_frames, - ); - } - - return outputs; + case "ObjectLiteral": { + const entries = Array.from(node.value.entries()).map( + ([k, v]) => `${formatExpression(k)}: ${formatExpression(v)}` + ); + return `{${entries.join(", ")}}`; } - - /** - * Calculates token-level timestamps using the encoder-decoder cross-attentions and - * dynamic time-warping (DTW) to map each output token to a position in the input audio. - * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW. - * @param {Object} generate_outputs Outputs generated by the model - * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model - * @param {Tensor} generate_outputs.sequences The sequences output by the model - * @param {number[][]} alignment_heads Alignment heads of the model - * @param {number} [num_frames=null] Number of frames in the input audio. - * @param {number} [time_precision=0.02] Precision of the timestamps in seconds - * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token - */ - _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) { - if (!generate_outputs.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`." - ) - } - if (num_frames == 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)." - ); - } - - // @ts-expect-error TS2339 - let median_filter_width = this.config.median_filter_width; - if (median_filter_width === undefined) { - console.warn("Model config has no `median_filter_width`, using default value of 7.") - median_filter_width = 7; - } - - // TODO: Improve batch processing - const batch = generate_outputs.cross_attentions; - // Create a list with `decoder_layers` elements, each a tensor of shape - // (batch size, attention_heads, output length, input length). - // @ts-expect-error TS2339 - const cross_attentions = Array.from({ length: this.config.decoder_layers }, - // Concatenate the cross attentions for each layer across sequence length dimension. - (_, i) => (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)(batch.map(x => x[i]), 2) - ); - - const weights = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.stack)(alignment_heads.map(([l, h]) => { - if (l >= cross_attentions.length) { - throw new Error(`Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).`) - } - return num_frames - ? cross_attentions[l].slice(null, h, null, [0, num_frames]) - : cross_attentions[l].slice(null, h); - })).transpose(1, 0, 2, 3); - - const [std, calculatedMean] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.std_mean)(weights, -2, 0, true); - - // Normalize and smoothen the weights. - const smoothedWeights = weights.clone(); // [1, 8, seqLength, 1500] - - for (let a = 0; a < smoothedWeights.dims[0]; ++a) { - const aTensor = smoothedWeights[a]; // [8, seqLength, 1500] - - for (let b = 0; b < aTensor.dims[0]; ++b) { - const bTensor = aTensor[b]; // [seqLength, 1500] - - const stdTensorData = std[a][b][0].data; // [1500] - const meanTensorData = calculatedMean[a][b][0].data; // [1500] - - for (let c = 0; c < bTensor.dims[0]; ++c) { - - let cTensorData = bTensor[c].data; // [1500] - for (let d = 0; d < cTensorData.length; ++d) { - cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d] - } - - // Apply median filter. - cTensorData.set((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.medianFilter)(cTensorData, median_filter_width)) - } - } - } - - // Average the different cross-attention heads. - const batchedMatrices = [(0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.mean)(smoothedWeights, 1)]; - - const timestampsShape = generate_outputs.sequences.dims; - - const timestamps = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - 'float32', - new Float32Array(timestampsShape[0] * timestampsShape[1]), - timestampsShape - ); - - // Perform dynamic time warping on each element of the batch. - for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { - // NOTE: Since we run only one batch at a time, we can squeeze to get the same dimensions - // as the python implementation - const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); - const [text_indices, time_indices] = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.dynamic_time_warping)(matrix.tolist()); - - const diffs = Array.from({ length: text_indices.length - 1 }, (v, i) => text_indices[i + 1] - text_indices[i]); - const jumps = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.mergeArrays)([1], diffs).map(x => !!x); // convert to boolean - - const jump_times = []; - for (let i = 0; i < jumps.length; ++i) { - if (jumps[i]) { - // NOTE: No point in rounding here, since we set to Float32Array later - jump_times.push(time_indices[i] * time_precision); - } - } - timestamps[batch_idx].data.set(jump_times, 1) - } - - return timestamps; + case "SliceExpression": { + const n = node; + const s = n.start ? formatExpression(n.start) : ""; + const t = n.stop ? formatExpression(n.stop) : ""; + const st = n.step ? `:${formatExpression(n.step)}` : ""; + return `${s}:${t}${st}`; } -} -////////////////////////////////////////////////// - -class LiteWhisperForConditionalGeneration extends WhisperForConditionalGeneration { } - -////////////////////////////////////////////////// -// Moonshine models -class MoonshinePreTrainedModel extends PreTrainedModel { - - requires_attention_mask = false; - main_input_name = 'input_values'; - forward_params = [ - 'input_values', - 'decoder_input_ids', - 'past_key_values', - ]; -}; - -/** - * MoonshineModel class for training Moonshine models without a language model head. - */ -class MoonshineModel extends MoonshinePreTrainedModel { } - -class MoonshineForConditionalGeneration extends MoonshinePreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -/** - * Vision Encoder-Decoder model based on OpenAI's GPT architecture for image captioning and other vision tasks - */ -class VisionEncoderDecoderModel extends PreTrainedModel { - main_input_name = 'pixel_values'; - forward_params = [ - // Encoder inputs - 'pixel_values', - - // Decoder inpputs - 'decoder_input_ids', - 'encoder_hidden_states', - 'past_key_values', - ]; -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// LLaVa Models -class LlavaPreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - 'attention_mask', - 'pixel_values', - 'position_ids', - 'past_key_values', - ]; -} - -/** - * The LLAVA model which consists of a vision backbone and a language model. - */ -class LlavaForConditionalGeneration extends LlavaPreTrainedModel { - _merge_input_ids_with_image_features(kwargs) { - const vision_hidden_size = kwargs.image_features.dims.at(-1); - const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); - - return default_merge_input_ids_with_image_features({ - // @ts-ignore - image_token_id: this.config.image_token_index, - ...kwargs, - image_features: reshaped_image_hidden_states, - }) + case "KeywordArgumentExpression": { + const n = node; + return `${n.key.value}=${formatExpression(n.value)}`; } + case "Ternary": { + const n = node; + return `${formatOperand(n.trueExpr, PRECEDENCE.LOGICAL_OR)} if ${formatOperand( + n.condition, + PRECEDENCE.LOGICAL_OR + )} else ${formatOperand(n.falseExpr, PRECEDENCE.CONDITIONAL)}`; + } + default: + throw new Error(`Unknown expression type: ${node.type}`); + } } -////////////////////////////////////////////////// - -class LlavaOnevisionForConditionalGeneration extends LlavaForConditionalGeneration { } // NOTE: extends LlavaForConditionalGeneration -class Moondream1ForConditionalGeneration extends LlavaForConditionalGeneration { } // NOTE: extends LlavaForConditionalGeneration - -class Florence2PreTrainedModel extends PreTrainedModel { - forward_params = [ - // Encoder inputs - 'input_ids', - 'inputs_embeds', - 'attention_mask', - 'pixel_values', - - // Decoder inputs - 'encoder_outputs', - 'decoder_input_ids', - 'decoder_inputs_embeds', - 'decoder_attention_mask', - 'past_key_values', - ]; - main_input_name = 'inputs_embeds'; -} - -class Florence2ForConditionalGeneration extends Florence2PreTrainedModel { - - _merge_input_ids_with_image_features({ - inputs_embeds, - image_features, - input_ids, - attention_mask, - }) { - return { - inputs_embeds: (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - image_features, // image embeds - inputs_embeds, // task prefix embeds - ], 1), - attention_mask: (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)([ - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)(image_features.dims.slice(0, 2)), // image attention mask - attention_mask, // task prefix attention mask - ], 1), - } +var Template = class { + parsed; + /** + * @param {string} template The template string + */ + constructor(template) { + const tokens = tokenize(template, { + lstrip_blocks: true, + trim_blocks: true + }); + this.parsed = parse(tokens); + } + render(items) { + const env3 = new Environment(); + setupGlobals(env3); + if (items) { + for (const [key, value] of Object.entries(items)) { + env3.set(key, value); + } } + const interpreter = new Interpreter(env3); + const result = interpreter.run(this.parsed); + return result.value; + } + format(options) { + return format(this.parsed, options?.indent || " "); + } +}; - async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) { - if (!input_ids && !pixel_values) { - throw new Error('Either `input_ids` or `pixel_values` should be provided.'); - } - - // 1. Possibly, extract the input embeddings - let text_features, image_features; - if (input_ids) { - text_features = await this.encode_text({ input_ids }); - } - if (pixel_values) { - image_features = await this.encode_image({ pixel_values }); - } - - // 2. Possibly, merge text and images - if (text_features && image_features) { - ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({ - inputs_embeds: text_features, - image_features, - input_ids, - attention_mask, - })); - } else { - inputs_embeds = text_features || image_features; +// src/utils/hub/FileResponse.js +var CONTENT_TYPE_MAP = { + 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" +}; +var FileResponse = class _FileResponse { + /** + * Creates a new `FileResponse` object. + * @param {string} filePath + */ + constructor(filePath) { + this.filePath = filePath; + this.headers = new Headers(); + this.exists = node_fs_default.existsSync(filePath); + if (this.exists) { + this.status = 200; + this.statusText = "OK"; + let stats = node_fs_default.statSync(filePath); + this.headers.set("content-length", stats.size.toString()); + this.updateContentType(); + const stream = node_fs_default.createReadStream(filePath); + this.body = new ReadableStream({ + start(controller) { + stream.on("data", (chunk2) => controller.enqueue(chunk2)); + stream.on("end", () => controller.close()); + stream.on("error", (err) => controller.error(err)); + }, + cancel() { + stream.destroy(); } - - return { inputs_embeds, attention_mask }; + }); + } else { + this.status = 404; + this.statusText = "Not Found"; + this.body = null; } + } + /** + * Updates the 'content-type' header property of the response based on the extension of + * the file specified by the filePath property of the current object. + * @returns {void} + */ + updateContentType() { + const extension = this.filePath.toString().split(".").pop().toLowerCase(); + this.headers.set("content-type", CONTENT_TYPE_MAP[extension] ?? "application/octet-stream"); + } + /** + * Clone the current FileResponse object. + * @returns {FileResponse} A new FileResponse object with the same properties as the current object. + */ + clone() { + let response = new _FileResponse(this.filePath); + response.exists = this.exists; + response.status = this.status; + response.statusText = this.statusText; + response.headers = new Headers(this.headers); + return response; + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with an ArrayBuffer containing the file's contents. + * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async arrayBuffer() { + const data = await node_fs_default.promises.readFile(this.filePath); + return ( + /** @type {ArrayBuffer} */ + data.buffer + ); + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a Blob containing the file's contents. + * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async blob() { + const data = await node_fs_default.promises.readFile(this.filePath); + return new Blob([ + /** @type {any} */ + data + ], { type: this.headers.get("content-type") }); + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a string containing the file's contents. + * @returns {Promise} A Promise that resolves with a string containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async text() { + return await node_fs_default.promises.readFile(this.filePath, "utf8"); + } + /** + * Reads the contents of the file specified by the filePath property and returns a Promise that + * resolves with a parsed JavaScript object containing the file's contents. + * + * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. + * @throws {Error} If the file cannot be read. + */ + async json() { + return JSON.parse(await this.text()); + } +}; - async forward({ - input_ids, - pixel_values, - attention_mask, - decoder_input_ids, - decoder_attention_mask, - encoder_outputs, - past_key_values, - - inputs_embeds, - decoder_inputs_embeds, - }) { - if (!inputs_embeds) { - ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask })); - } - - if (!encoder_outputs) { - // Must compute encoder outputs - let { last_hidden_state } = await encoderForward(this, { inputs_embeds, attention_mask }); - encoder_outputs = last_hidden_state; - } - - if (!decoder_inputs_embeds) { - if (!decoder_input_ids) { - throw new Error('Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.'); - } - decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids }); - } - - const decoderFeeds = { - inputs_embeds: decoder_inputs_embeds, - attention_mask: decoder_attention_mask, - encoder_attention_mask: attention_mask, - encoder_hidden_states: encoder_outputs, - past_key_values, - }; - const decoder_outputs = await decoderForward(this, decoderFeeds, true); - return decoder_outputs; +// src/utils/random.js +var Random = class { + constructor(seed) { + this._mt = new Uint32Array(624); + this._idx = 625; + this._gauss_next = null; + this._random_fn = this.random.bind(this); + this.seed(seed); + } + /** + * Seeds this instance's PRNG. + * + * When called with a number, initializes the state deterministically from that value. + * When called with no arguments (or `undefined`/`null`), seeds from OS entropy + * via `crypto.getRandomValues`, matching Python's `random.seed()` behavior. + * + * @param {number} [n] The seed value. Omit to seed from OS entropy. + */ + seed(n) { + if (n === void 0 || n === null) { + if (apis.IS_CRYPTO_AVAILABLE) { + const buf = new Uint32Array(1); + crypto.getRandomValues(buf); + n = buf[0]; + } else { + n = Date.now() >>> 0; + } } -} - -class PaliGemmaPreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - // 'inputs_embeds', - 'attention_mask', - 'pixel_values', - 'position_ids', - 'past_key_values', - ]; -} - -class PaliGemmaForConditionalGeneration extends PaliGemmaPreTrainedModel { - _merge_input_ids_with_image_features(kwargs) { - const vision_hidden_size = kwargs.image_features.dims.at(-1); - const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); - - return default_merge_input_ids_with_image_features({ - // @ts-ignore - image_token_id: this.config.image_token_index, - ...kwargs, - image_features: reshaped_image_hidden_states, - }) + if (Number.isSafeInteger(n)) n = Math.abs(n); + const mt = this._mt; + const u = (a, b) => Math.imul(a, b) >>> 0, key = []; + for (let v = n || 0; v > 0; v = Math.floor(v / 4294967296)) key.push(v & 4294967295); + if (!key.length) key.push(0); + mt[0] = 19650218; + for (let k = 1; k < 624; ++k) mt[k] = u(1812433253, mt[k - 1] ^ mt[k - 1] >>> 30) + k >>> 0; + let i = 1, j2 = 0; + for (let k = Math.max(624, key.length); k > 0; --k, ++i, ++j2) { + if (i >= 624) { + mt[0] = mt[623]; + i = 1; + } + if (j2 >= key.length) j2 = 0; + mt[i] = (mt[i] ^ u(mt[i - 1] ^ mt[i - 1] >>> 30, 1664525)) + key[j2] + j2 >>> 0; } -} - -class LlavaQwen2ForCausalLM extends LlavaPreTrainedModel { - _merge_input_ids_with_image_features(kwargs) { - const vision_hidden_size = kwargs.image_features.dims.at(-1); - const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); - - return default_merge_input_ids_with_image_features({ - // @ts-ignore - image_token_id: this.config.image_token_index, - ...kwargs, - image_features: reshaped_image_hidden_states, - }) + for (let k = 623; k > 0; --k, ++i) { + if (i >= 624) { + mt[0] = mt[623]; + i = 1; + } + mt[i] = (mt[i] ^ u(mt[i - 1] ^ mt[i - 1] >>> 30, 1566083941)) - i >>> 0; } -} - -class Gemma3nPreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - 'attention_mask', - 'inputs_embeds', - 'per_layer_inputs', - - 'position_ids', - 'pixel_values', - 'input_features', - 'input_features_mask', - 'past_key_values', - ]; -} -class Gemma3nForConditionalGeneration extends Gemma3nPreTrainedModel { - - async forward({ - // Produced by the tokenizer/processor: - input_ids = null, - attention_mask = null, - pixel_values = null, - input_features = null, - input_features_mask = null, - - // Used during generation: - position_ids = null, - inputs_embeds = null, - per_layer_inputs=null, - past_key_values = null, - - // Generic generation parameters - generation_config = null, - logits_processor = null, - - // TODO: needed? - ...kwargs - }) { - if (!inputs_embeds || !per_layer_inputs) { - // 1. Extract the text embeddings. - ({ inputs_embeds, per_layer_inputs} = await sessionRun(this.sessions['embed_tokens'], { - input_ids, - })); - if (input_ids.dims[1] !== 1) { - if (pixel_values) { - // Encode the image - const { image_features } = await sessionRun(this.sessions['vision_encoder'], { - pixel_values, - }); - ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({ - image_features, - inputs_embeds, - input_ids, - attention_mask, - })); - } + mt[0] = 2147483648; + this._idx = 624; + this._gauss_next = null; + } + /** + * Generates a random unsigned 32-bit integer. + * + * Performs the "twist" step when the state buffer is exhausted, + * then applies the standard MT19937 tempering transform. + * + * @returns {number} A random integer in the range [0, 2^32 - 1]. + * @internal + */ + _int32() { + const mt = this._mt; + if (this._idx >= 624) { + for (let k = 0; k < 624; ++k) { + const y2 = mt[k] & 2147483648 | mt[(k + 1) % 624] & 2147483647; + mt[k] = (mt[(k + 397) % 624] ^ y2 >>> 1 ^ (y2 & 1 ? 2567483615 : 0)) >>> 0; + } + this._idx = 0; + } + let y = mt[this._idx++]; + y ^= y >>> 11; + y ^= y << 7 & 2636928640; + y ^= y << 15 & 4022730752; + y ^= y >>> 18; + return y >>> 0; + } + /** + * Generates a random floating-point number in the half-open interval [0, 1). + * + * Combines two 32-bit integers (using 53 bits of precision) to produce + * a uniformly distributed double, matching Python's `random.random()`. + * + * @returns {number} A random float in [0, 1). + */ + random() { + return ((this._int32() >>> 5) * 67108864 + (this._int32() >>> 6)) / 9007199254740992; + } + /** + * Generates a random number from a Gaussian (normal) distribution. + * + * Uses the Box-Muller transform with a cached spare value, + * matching Python's `random.gauss()` output for the same seed. + * + * @param {number} [mu=0] The mean of the distribution. + * @param {number} [sigma=1] The standard deviation of the distribution. + * @returns {number} A normally distributed random value. + */ + gauss(mu = 0, sigma = 1) { + let z = this._gauss_next; + this._gauss_next = null; + if (z === null) { + const x2pi = this.random() * 2 * Math.PI, g2rad = Math.sqrt(-2 * Math.log(1 - this.random())); + z = Math.cos(x2pi) * g2rad; + this._gauss_next = Math.sin(x2pi) * g2rad; + } + return mu + z * sigma; + } + /** + * Shuffles an array in-place using the Fisher-Yates algorithm. + * + * Uses rejection sampling via `getrandbits`-style bit masking to ensure + * a uniform distribution, matching Python's `random.shuffle()`. + * + * @param {any[]} arr The array to shuffle in-place. + */ + shuffle(arr) { + for (let i = arr.length - 1; i > 0; --i) { + const k = 32 - Math.clz32(i + 1); + let r = this._int32() >>> 32 - k; + while (r > i) r = this._int32() >>> 32 - k; + const t = arr[i]; + arr[i] = arr[r]; + arr[r] = t; + } + } + /** + * Selects a single element from a weighted population. + * + * Matches Python's `random.choices(population, weights=weights, k=1)[0]` + * + * @param {any[]} population The array of items to choose from. + * @param {number[]} weights An array of non-negative weights, one per population element. + * @returns {*} A single randomly selected element from the population. + */ + choices(population, weights) { + return population[_weightedIndexWith(this._random_fn, weights)]; + } +}; +function _weightedIndexWith(randomFn, weights) { + let sum = 0; + for (let i = 0; i < weights.length; ++i) sum += weights[i]; + let x = randomFn() * sum; + for (let i = 0; i < weights.length; ++i) { + x -= weights[i]; + if (x < 0) return i; + } + return weights.length - 1; +} +var _default = new Random(); +var random = Object.freeze({ + Random, + seed: _default.seed.bind(_default), + random: _default.random.bind(_default), + gauss: _default.gauss.bind(_default), + shuffle: _default.shuffle.bind(_default), + choices: _default.choices.bind(_default) +}); +var _weightedIndex = (weights) => _weightedIndexWith(random.random, weights); - if (input_features) { - // Encode the audio - const { audio_features } = await sessionRun(this.sessions['audio_encoder'], { - input_features, - input_features_mask, - }); - ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_audio_features({ - audio_features, - inputs_embeds, - input_ids, - attention_mask, - })); - } - } +// src/utils/cache/FileCache.js +var rng = new Random(); +var FileCache = class { + /** + * Instantiate a `FileCache` object. + * @param {string} path + */ + constructor(path) { + this.path = path; + } + /** + * Checks whether the given request is in the cache. + * @param {string} request + * @returns {Promise} + */ + async match(request) { + let filePath = node_path_default.join(this.path, request); + let file = new FileResponse(filePath); + if (file.exists) { + return file; + } else { + return void 0; + } + } + /** + * Adds the given response to the cache. + * @param {string} request + * @param {Response} response + * @param {(data: {progress: number, loaded: number, total: number}) => void} [progress_callback] Optional. + * The function to call with progress updates + * @returns {Promise} + */ + async put(request, response, progress_callback = void 0) { + const filePath = node_path_default.join(this.path, request); + const id = apis.IS_PROCESS_AVAILABLE ? process.pid : Date.now(); + const randomSuffix = rng._int32().toString(36); + const tmpPath = filePath + `.tmp.${id}.${randomSuffix}`; + try { + const contentLength = response.headers.get("Content-Length"); + const total = parseInt(contentLength ?? "0"); + let loaded = 0; + await node_fs_default.promises.mkdir(node_path_default.dirname(filePath), { recursive: true }); + const fileStream = node_fs_default.createWriteStream(tmpPath); + const reader = response.body.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; } - - const outputs = await decoderForward(this, { - inputs_embeds, - per_layer_inputs, - past_key_values, - attention_mask, - position_ids, - generation_config, - logits_processor, - }, true); - return outputs; - } - - _merge_input_ids_with_image_features(kwargs) { - const vision_hidden_size = kwargs.image_features.dims.at(-1); - const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); - return default_merge_input_ids_with_image_features({ - // @ts-ignore - image_token_id: this.config.image_token_id, - ...kwargs, - image_features: reshaped_image_hidden_states, + await new Promise((resolve, reject) => { + fileStream.write(value, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); }); + loaded += value.length; + const progress = total ? loaded / total * 100 : 0; + progress_callback?.({ progress, loaded, total }); + } + await new Promise((resolve, reject) => { + fileStream.close((err) => err ? reject(err) : resolve()); + }); + await node_fs_default.promises.rename(tmpPath, filePath); + } catch (error) { + try { + await node_fs_default.promises.unlink(tmpPath); + } catch { + } + throw error; } - _merge_input_ids_with_audio_features(kwargs) { - const audio_hidden_size = kwargs.audio_features.dims.at(-1); - const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); - - return default_merge_input_ids_with_audio_features({ - // @ts-ignore - audio_token_id: this.config.audio_token_id, - ...kwargs, - audio_features: reshaped_audio_features, - }) - } -} - - -////////////////////////////////////////////////// -// Idefics3 Models -class Idefics3PreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - 'attention_mask', - 'pixel_values', - 'pixel_attention_mask', - 'position_ids', - 'past_key_values', - ]; -} - -/** - * The Idefics3 model which consists of a vision backbone and a language model. - */ -class Idefics3ForConditionalGeneration extends Idefics3PreTrainedModel { - - async encode_image({ pixel_values, pixel_attention_mask }) { - const features = (await sessionRun(this.sessions['vision_encoder'], { pixel_values, pixel_attention_mask })).image_features; - return features; + } + /** + * Deletes the cache entry for the given request. + * @param {string} request + * @returns {Promise} A Promise that resolves to `true` if the cache entry was deleted, `false` otherwise. + */ + async delete(request) { + let filePath = node_path_default.join(this.path, request); + try { + await node_fs_default.promises.unlink(filePath); + return true; + } catch (error) { + return false; } + } + // TODO add the rest? + // addAll(requests: RequestInfo[]): Promise; + // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; + // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; + // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; +}; - _merge_input_ids_with_image_features(kwargs) { - const vision_hidden_size = kwargs.image_features.dims.at(-1); - const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); +// src/utils/hub/constants.js +var ERROR_MAPPING = { + // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) + 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", + // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) + 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" +}; +var MAX_EXTERNAL_DATA_CHUNKS = 100; +var REPO_ID_REGEX = /^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/; - return default_merge_input_ids_with_image_features({ - // @ts-ignore - image_token_id: this.config.image_token_id, - ...kwargs, - image_features: reshaped_image_hidden_states, - }) +// src/utils/hub/utils.js +function pathJoin(...parts) { + parts = parts.map((part, index) => { + if (index) { + part = part.replace(new RegExp("^/"), ""); } -} -////////////////////////////////////////////////// - -/** - * The SmolVLM Model with a language modeling head. - * It is made up a SigLIP vision encoder, with a language modeling head on top. - */ -class SmolVLMForConditionalGeneration extends Idefics3ForConditionalGeneration { } - -////////////////////////////////////////////////// -class Phi3VPreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - 'inputs_embeds', - 'attention_mask', - 'position_ids', - 'pixel_values', - 'image_sizes', - 'past_key_values', - ]; -} -class Phi3VForCausalLM extends Phi3VPreTrainedModel { - - async forward({ - // Produced by the tokenizer/processor: - input_ids = null, - attention_mask = null, - pixel_values = null, - image_sizes = null, - - // Used during generation: - position_ids = null, - inputs_embeds = null, - past_key_values = null, - - // Generic generation parameters - generation_config = null, - logits_processor = null, - - // TODO: needed? - ...kwargs - }) { - if (!inputs_embeds) { - let image_features; - if (pixel_values && input_ids.dims[1] !== 1) { - if (!image_sizes) { - throw new Error('`image_sizes` must be provided when `pixel_values` is provided.'); - } - - // Encode the image - ({ image_features } = await sessionRun(this.sessions['vision_encoder'], { - pixel_values, - image_sizes, - })); - } else { - const hidden_size = this.config.normalized_config.hidden_size; - image_features = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - 'float32', - [], - [0, hidden_size], - ); - } - - ({ inputs_embeds } = await sessionRun(this.sessions['prepare_inputs_embeds'], { - input_ids, - image_features, - })); - } - - const outputs = await decoderForward(this, { - inputs_embeds, - past_key_values, - attention_mask, - position_ids, - generation_config, - logits_processor, - }, false); - return outputs; - } -} - -////////////////////////////////////////////////// -class CLIPPreTrainedModel extends PreTrainedModel { } - -/** - * CLIP Text and Vision Model with a projection layers on top - * - * **Example:** Perform zero-shot image classification with a `CLIPModel`. - * - * ```javascript - * import { AutoTokenizer, AutoProcessor, CLIPModel, RawImage } from '@huggingface/transformers'; - * - * // Load tokenizer, processor, and model - * let tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16'); - * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); - * let model = await CLIPModel.from_pretrained('Xenova/clip-vit-base-patch16'); - * - * // Run tokenization - * let texts = ['a photo of a car', 'a photo of a football match'] - * let text_inputs = tokenizer(texts, { padding: true, truncation: true }); - * - * // Read image and run processor - * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); - * let image_inputs = await processor(image); - * - * // Run model with both text and pixel inputs - * let output = await model({ ...text_inputs, ...image_inputs }); - * // { - * // logits_per_image: Tensor { - * // dims: [ 1, 2 ], - * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ], - * // }, - * // logits_per_text: Tensor { - * // dims: [ 2, 1 ], - * // data: Float32Array(2) [ 18.579734802246094, 24.31830596923828 ], - * // }, - * // text_embeds: Tensor { - * // dims: [ 2, 512 ], - * // data: Float32Array(1024) [ ... ], - * // }, - * // image_embeds: Tensor { - * // dims: [ 1, 512 ], - * // data: Float32Array(512) [ ... ], - * // } - * // } - * ``` - */ -class CLIPModel extends CLIPPreTrainedModel { } - -/** - * The text model from CLIP without any head or projection on top. - */ -class CLIPTextModel extends CLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'text_model', - }); + if (index !== parts.length - 1) { + part = part.replace(new RegExp("/$"), ""); } + return part; + }); + return parts.join("/"); } - -/** - * CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output) - * - * **Example:** Compute text embeddings with `CLIPTextModelWithProjection`. - * - * ```javascript - * import { AutoTokenizer, CLIPTextModelWithProjection } from '@huggingface/transformers'; - * - * // Load tokenizer and text model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clip-vit-base-patch16'); - * const text_model = await CLIPTextModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16'); - * - * // Run tokenization - * let texts = ['a photo of a car', 'a photo of a football match']; - * let text_inputs = tokenizer(texts, { padding: true, truncation: true }); - * - * // Compute embeddings - * const { text_embeds } = await text_model(text_inputs); - * // Tensor { - * // dims: [ 2, 512 ], - * // type: 'float32', - * // data: Float32Array(1024) [ ... ], - * // size: 1024 - * // } - * ``` - */ -class CLIPTextModelWithProjection extends CLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'text_model', - }); - } +function isValidUrl(string, protocols = null, validHosts = null) { + let url; + try { + url = new URL(string); + } catch (_) { + return false; + } + if (protocols && !protocols.includes(url.protocol)) { + return false; + } + if (validHosts && !validHosts.includes(url.hostname)) { + return false; + } + return true; } - -/** - * The vision model from CLIP without any head or projection on top. - */ -class CLIPVisionModel extends CLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'vision_model', - }); - } +function isValidHfModelId(string) { + if (!REPO_ID_REGEX.test(string)) return false; + if (string.includes("..") || string.includes("--")) return false; + if (string.endsWith(".git") || string.endsWith(".ipynb")) return false; + return true; +} +function makePretrainedOptionsKey(model_id, options = {}, ...parts) { + return JSON.stringify([ + model_id, + options.revision ?? "main", + options.cache_dir ?? null, + options.local_files_only ?? false, + ...parts + ]); } - -/** - * CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output) - * - * **Example:** Compute vision embeddings with `CLIPVisionModelWithProjection`. - * - * ```javascript - * import { AutoProcessor, CLIPVisionModelWithProjection, RawImage} from '@huggingface/transformers'; - * - * // Load processor and vision model - * const processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); - * const vision_model = await CLIPVisionModelWithProjection.from_pretrained('Xenova/clip-vit-base-patch16'); - * - * // Read image and run processor - * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); - * let image_inputs = await processor(image); - * - * // Compute embeddings - * const { image_embeds } = await vision_model(image_inputs); - * // Tensor { - * // dims: [ 1, 512 ], - * // type: 'float32', - * // data: Float32Array(512) [ ... ], - * // size: 512 - * // } - * ``` - */ -class CLIPVisionModelWithProjection extends CLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'vision_model', - }); - } +var ModelFileNotFoundError = class extends Error { + /** + * @param {string} message The error message. + * @param {Object} [options] Additional error information. + * @param {number|null} [options.status=null] The HTTP status code, when the failure came from a Hub response. + */ + constructor(message, { status = null } = {}) { + super(message); + this.name = "ModelFileNotFoundError"; + this.status = status; + } +}; +var NOT_FOUND_STATUSES = /* @__PURE__ */ new Set([401, 403, 404]); +function handleError(status, remoteURL, fatal) { + if (!fatal) { + return null; + } + const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`; + const fullMessage = `${message}: "${remoteURL}".`; + if (NOT_FOUND_STATUSES.has(status)) { + throw new ModelFileNotFoundError(fullMessage, { status }); + } + throw Error(fullMessage); } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// SigLIP models -class SiglipPreTrainedModel extends PreTrainedModel { } - -/** - * SigLIP Text and Vision Model with a projection layers on top - * - * **Example:** Perform zero-shot image classification with a `SiglipModel`. - * - * ```javascript - * import { AutoTokenizer, AutoProcessor, SiglipModel, RawImage } from '@huggingface/transformers'; - * - * // Load tokenizer, processor, and model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224'); - * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224'); - * const model = await SiglipModel.from_pretrained('Xenova/siglip-base-patch16-224'); - * - * // Run tokenization - * const texts = ['a photo of 2 cats', 'a photo of 2 dogs']; - * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true }); - * - * // Read image and run processor - * const image = await RawImage.read('http://images.cocodataset.org/val2017/000000039769.jpg'); - * const image_inputs = await processor(image); - * - * // Run model with both text and pixel inputs - * const output = await model({ ...text_inputs, ...image_inputs }); - * // { - * // logits_per_image: Tensor { - * // dims: [ 1, 2 ], - * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ], - * // }, - * // logits_per_text: Tensor { - * // dims: [ 2, 1 ], - * // data: Float32Array(2) [ -1.6019744873046875, -10.720091819763184 ], - * // }, - * // text_embeds: Tensor { - * // dims: [ 2, 768 ], - * // data: Float32Array(1536) [ ... ], - * // }, - * // image_embeds: Tensor { - * // dims: [ 1, 768 ], - * // data: Float32Array(768) [ ... ], - * // } - * // } - * ``` - */ -class SiglipModel extends SiglipPreTrainedModel { } - -/** - * The text model from SigLIP without any head or projection on top. - * - * **Example:** Compute text embeddings with `SiglipTextModel`. - * - * ```javascript - * import { AutoTokenizer, SiglipTextModel } from '@huggingface/transformers'; - * - * // Load tokenizer and text model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/siglip-base-patch16-224'); - * const text_model = await SiglipTextModel.from_pretrained('Xenova/siglip-base-patch16-224'); - * - * // Run tokenization - * const texts = ['a photo of 2 cats', 'a photo of 2 dogs']; - * const text_inputs = tokenizer(texts, { padding: 'max_length', truncation: true }); - * - * // Compute embeddings - * const { pooler_output } = await text_model(text_inputs); - * // Tensor { - * // dims: [ 2, 768 ], - * // type: 'float32', - * // data: Float32Array(1536) [ ... ], - * // size: 1536 - * // } - * ``` - */ -class SiglipTextModel extends SiglipPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'text_model', - }); +async function readResponse(response, progress_callback, expectedSize) { + const contentLength = response.headers.get("Content-Length"); + let total = contentLength ? parseInt(contentLength, 10) : expectedSize ?? 0; + if (contentLength === null && !expectedSize) { + logger.warn("Unable to determine content-length from response headers. Will expand buffer when needed."); + } + let buffer = new Uint8Array(total); + let loaded = 0; + const reader = response.body.getReader(); + async function read() { + const { done, value } = await reader.read(); + if (done) return; + const newLoaded = loaded + value.length; + if (newLoaded > total) { + total = newLoaded; + const newBuffer = new Uint8Array(total); + newBuffer.set(buffer); + buffer = newBuffer; + } + buffer.set(value, loaded); + loaded = newLoaded; + const progress = loaded / total * 100; + progress_callback({ progress, loaded, total }); + return read(); + } + await read(); + return buffer; +} +function isBlobURL(url) { + return isValidUrl(url, ["blob:"]); +} +function toAbsoluteURL(url, { allowUnresolved = false } = {}) { + let baseURL; + if (typeof location !== "undefined" && location.href) { + baseURL = location.href; + } else if (typeof import.meta !== "undefined" && import.meta.url) { + baseURL = import.meta.url; + } else { + return url; + } + try { + return new URL(url, baseURL).href; + } catch (error) { + if (!allowUnresolved) { + throw error; } + return url; + } } -/** - * The vision model from SigLIP without any head or projection on top. - * - * **Example:** Compute vision embeddings with `SiglipVisionModel`. - * - * ```javascript - * import { AutoProcessor, SiglipVisionModel, RawImage} from '@huggingface/transformers'; - * - * // Load processor and vision model - * const processor = await AutoProcessor.from_pretrained('Xenova/siglip-base-patch16-224'); - * const vision_model = await SiglipVisionModel.from_pretrained('Xenova/siglip-base-patch16-224'); - * - * // Read image and run processor - * const image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); - * const image_inputs = await processor(image); - * - * // Compute embeddings - * const { pooler_output } = await vision_model(image_inputs); - * // Tensor { - * // dims: [ 1, 768 ], - * // type: 'float32', - * // data: Float32Array(768) [ ... ], - * // size: 768 - * // } - * ``` - */ -class SiglipVisionModel extends CLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'vision_model', - }); +// src/utils/cache/CrossOriginStorageCache.js +var HASH_ALGORITHM = "SHA-256"; +var HASH_CACHE_NAME = "experimental_transformers-hash-cache"; +var makeHashDescriptor = (value) => ({ algorithm: HASH_ALGORITHM, value }); +var CrossOriginStorage = class { + /** @type {Promise | null} */ + #hashCache = null; + /** + * Returns (and lazily opens) the hash cache, reusing the same promise across concurrent callers. + * @returns {Promise} + */ + _getHashCache = () => { + this.#hashCache ??= caches.open(HASH_CACHE_NAME); + return this.#hashCache; + }; + /** + * Returns whether the `navigator.crossOriginStorage` API is available in the current environment. + * @returns {boolean} + */ + static isAvailable = () => typeof navigator !== "undefined" && "crossOriginStorage" in navigator; + /** + * Looks up a cached response for the given URL by resolving its SHA-256 hash and requesting + * the corresponding file handle from cross-origin storage. + * + * Implements `CacheInterface.match`. + * + * @param {string} request The URL of the resource to look up. + * @returns {Promise} The cached `Response`, or `undefined` if not found. + */ + match = async (request) => { + const hashValue = await this._getFileHash(request); + if (!hashValue) { + return void 0; } -} -////////////////////////////////////////////////// -// ChineseCLIP models -class ChineseCLIPPreTrainedModel extends PreTrainedModel { } - -class ChineseCLIPModel extends ChineseCLIPPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// JinaCLIP models -class JinaCLIPPreTrainedModel extends PreTrainedModel { } - -class JinaCLIPModel extends JinaCLIPPreTrainedModel { - async forward(model_inputs) { - const missing_text_inputs = !model_inputs.input_ids; - const missing_image_inputs = !model_inputs.pixel_values; - - if (missing_text_inputs && missing_image_inputs) { - throw new Error('Either `input_ids` or `pixel_values` should be provided.'); - } - - // If either `input_ids` or `pixel_values` aren't passed, we need to create dummy input since the model requires a value to be specified. - if (missing_text_inputs) { - // NOTE: We cannot pass zero-dimension tensor as input for input_ids. - // Fortunately, the majority of time is spent in the vision encoder, so this shouldn't significantly impact performance. - model_inputs.input_ids = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones)([model_inputs.pixel_values.dims[0], 1]); - } - - if (missing_image_inputs) { - // NOTE: Since we create a zero-sized tensor, this does not increase computation time. - // @ts-ignore - const { image_size } = this.config.vision_config; - model_inputs.pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.full)([0, 3, image_size, image_size], 0.0); // (pass zero-dimension tensor) - } - - const { text_embeddings, image_embeddings, l2norm_text_embeddings, l2norm_image_embeddings } = await super.forward(model_inputs); - - const result = {}; - if (!missing_text_inputs) { - result.text_embeddings = text_embeddings; - result.l2norm_text_embeddings = l2norm_text_embeddings; - } - if (!missing_image_inputs) { - result.image_embeddings = image_embeddings; - result.l2norm_image_embeddings = l2norm_image_embeddings; + try { + const handle = await navigator.crossOriginStorage.requestFileHandle(makeHashDescriptor(hashValue)); + const blob = await handle.getFile(); + return new Response(blob, { + headers: { + "Content-Length": String(blob.size) } - return result + }); + } catch { + return void 0; } -} - -class JinaCLIPTextModel extends JinaCLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'text_model', - }); + }; + /** + * Stores a response in cross-origin storage, keyed by its SHA-256 hash. + * + * For LFS-backed URLs the hash is resolved cheaply via `_getFileHash` (which checks + * `HASH_CACHE_NAME` first, then falls back to fetching the Git LFS pointer file) + * without reading the response body a second time. + * + * For non-LFS resources the hash is unknown upfront. In that case the body is consumed + * in the background: the stream is read to compute the content hash, the file is written + * into cross-origin storage, and the computed hash is persisted to `HASH_CACHE_NAME` + * so that future `match` calls can resolve the file without a network round-trip. + * + * Implements `CacheInterface.put`. + * + * @param {string} request The URL of the resource (used as the hash-cache key). + * @param {Response} response The response whose body will be written to the cache. + * @returns {Promise} + */ + put = async (request, response) => { + const hashValue = await this._getFileHash(request); + if (hashValue) { + const blob = await response.blob(); + await this._storeBlobInCOS(blob, hashValue); + } else { + this._processAndStore(request, response.body); } -} - -class JinaCLIPVisionModel extends JinaCLIPPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'vision_model', - }); + }; + /** + * Writes a blob into cross-origin storage using the given pre-computed hex hash string. + * + * @param {Blob} blob + * @param {string} hashHex Hex-encoded SHA-256 hash of `blob`. + * @returns {Promise} + */ + _storeBlobInCOS = async (blob, hashHex) => { + const handle = await navigator.crossOriginStorage.requestFileHandle(makeHashDescriptor(hashHex), { + create: true, + origins: "*" + }); + const writableStream = await handle.createWritable(); + await writableStream.write(blob); + await writableStream.close(); + }; + /** + * Background task for non-LFS resources: consumes `stream`, computes the SHA-256 hash + * of the resulting blob, stores it in cross-origin storage, and persists the computed + * hash to `HASH_CACHE_NAME` keyed by `request` so future `match` calls can resolve the + * file without a network round-trip. + * + * Called fire-and-forget from `put` — errors are swallowed so failures never surface to + * the caller. + * + * @param {string} request The original resource URL. + * @param {ReadableStream} stream The response body stream to consume. + * @returns {Promise} + */ + _processAndStore = async (request, stream) => { + try { + const chunks = []; + for await (const chunk2 of stream) { + chunks.push(chunk2); + } + const blob = new Blob(chunks); + const hashHex = await this._getBlobHash(blob); + await this._storeBlobInCOS(blob, hashHex); + try { + const hashCache = await this._getHashCache(); + await hashCache.put(request, new Response(hashHex)); + } catch { + } + } catch { } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// CLIPSeg models -class CLIPSegPreTrainedModel extends PreTrainedModel { } - -class CLIPSegModel extends CLIPSegPreTrainedModel { } - -/** - * CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation. - * - * **Example:** Perform zero-shot image segmentation with a `CLIPSegForImageSegmentation` model. - * - * ```javascript - * import { AutoTokenizer, AutoProcessor, CLIPSegForImageSegmentation, RawImage } from '@huggingface/transformers'; - * - * // Load tokenizer, processor, and model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clipseg-rd64-refined'); - * const processor = await AutoProcessor.from_pretrained('Xenova/clipseg-rd64-refined'); - * const model = await CLIPSegForImageSegmentation.from_pretrained('Xenova/clipseg-rd64-refined'); - * - * // Run tokenization - * const texts = ['a glass', 'something to fill', 'wood', 'a jar']; - * const text_inputs = tokenizer(texts, { padding: true, truncation: true }); - * - * // Read image and run processor - * const image = await RawImage.read('https://github.com/timojl/clipseg/blob/master/example_image.jpg?raw=true'); - * const image_inputs = await processor(image); - * - * // Run model with both text and pixel inputs - * const { logits } = await model({ ...text_inputs, ...image_inputs }); - * // logits: Tensor { - * // dims: [4, 352, 352], - * // type: 'float32', - * // data: Float32Array(495616) [ ... ], - * // size: 495616 - * // } - * ``` - * - * You can visualize the predictions as follows: - * ```javascript - * const preds = logits - * .unsqueeze_(1) - * .sigmoid_() - * .mul_(255) - * .round_() - * .to('uint8'); - * - * for (let i = 0; i < preds.dims[0]; ++i) { - * const img = RawImage.fromTensor(preds[i]); - * img.save(`prediction_${i}.png`); - * } - * ``` - */ -class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// GPT2 models -class GPT2PreTrainedModel extends PreTrainedModel { } - -class GPT2Model extends GPT2PreTrainedModel { } - -/** - * GPT-2 language model head on top of the GPT-2 base model. This model is suitable for text generation tasks. - */ -class GPT2LMHeadModel extends GPT2PreTrainedModel { } -// export class GPT2ForSequenceClassification extends GPT2PreTrainedModel { -// TODO -// } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// JAIS models -class JAISPreTrainedModel extends PreTrainedModel { } - -/** - * The bare JAIS Model transformer outputting raw hidden-states without any specific head on top. - */ -class JAISModel extends JAISPreTrainedModel { } - -/** - * The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). - */ -class JAISLMHeadModel extends JAISPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// GPTNeo models -class GPTNeoPreTrainedModel extends PreTrainedModel { } -class GPTNeoModel extends GPTNeoPreTrainedModel { } - -class GPTNeoForCausalLM extends GPTNeoPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// GPTNeoX models -class GPTNeoXPreTrainedModel extends PreTrainedModel { } -class GPTNeoXModel extends GPTNeoXPreTrainedModel { } - -class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// GPT-J models -class GPTJPreTrainedModel extends PreTrainedModel { } - -class GPTJModel extends GPTJPreTrainedModel { } - -class GPTJForCausalLM extends GPTJPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// GPTBigCode models -class GPTBigCodePreTrainedModel extends PreTrainedModel { } - -class GPTBigCodeModel extends GPTBigCodePreTrainedModel { } - -class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// CodeGen models -class CodeGenPreTrainedModel extends PreTrainedModel { } -/** - * CodeGenModel is a class representing a code generation model without a language model head. - */ -class CodeGenModel extends CodeGenPreTrainedModel { } - -/** - * CodeGenForCausalLM is a class that represents a code generation model based on the GPT-2 architecture. It extends the `CodeGenPreTrainedModel` class. - */ -class CodeGenForCausalLM extends CodeGenPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// LLama models - -/** - * The bare LLama Model outputting raw hidden-states without any specific head on top. - */ -class LlamaPreTrainedModel extends PreTrainedModel { } -/** - * The bare LLaMA Model outputting raw hidden-states without any specific head on top. - */ -class LlamaModel extends LlamaPreTrainedModel { } - -class LlamaForCausalLM extends LlamaPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Arcee models -class ArceePreTrainedModel extends PreTrainedModel { } -class ArceeModel extends ArceePreTrainedModel { } -class ArceeForCausalLM extends ArceePreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// LFM2 models -class Lfm2PreTrainedModel extends PreTrainedModel { } -class Lfm2Model extends Lfm2PreTrainedModel { } -class Lfm2ForCausalLM extends Lfm2PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// SmolLM3 models -class SmolLM3PreTrainedModel extends PreTrainedModel { } -class SmolLM3Model extends SmolLM3PreTrainedModel { } -class SmolLM3ForCausalLM extends SmolLM3PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Helium models -class HeliumPreTrainedModel extends PreTrainedModel { } -class HeliumModel extends HeliumPreTrainedModel { } -class HeliumForCausalLM extends HeliumPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Glm models -class GlmPreTrainedModel extends PreTrainedModel { } -class GlmModel extends GlmPreTrainedModel { } -class GlmForCausalLM extends GlmPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// EXAONE models -class ExaonePreTrainedModel extends PreTrainedModel { } -class ExaoneModel extends ExaonePreTrainedModel { } -class ExaoneForCausalLM extends ExaonePreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// MobileLLM models -class MobileLLMPreTrainedModel extends PreTrainedModel { } -class MobileLLMModel extends MobileLLMPreTrainedModel { } -class MobileLLMForCausalLM extends MobileLLMPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// OLMo models -class OlmoPreTrainedModel extends PreTrainedModel { } -class OlmoModel extends OlmoPreTrainedModel { } -class OlmoForCausalLM extends OlmoPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// OLMo2 models -class Olmo2PreTrainedModel extends PreTrainedModel { } -class Olmo2Model extends Olmo2PreTrainedModel { } -class Olmo2ForCausalLM extends Olmo2PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Granite models -class GranitePreTrainedModel extends PreTrainedModel { } -class GraniteModel extends GranitePreTrainedModel { } -class GraniteForCausalLM extends GranitePreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Cohere models - -/** - * The bare Cohere Model outputting raw hidden-states without any specific head on top. - */ -class CoherePreTrainedModel extends PreTrainedModel { } -class CohereModel extends CoherePreTrainedModel { } - -class CohereForCausalLM extends CoherePreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Gemma models - -/** - * The bare Gemma Model outputting raw hidden-states without any specific head on top. - */ -class GemmaPreTrainedModel extends PreTrainedModel { } -/** - * The bare Gemma Model outputting raw hidden-states without any specific head on top. - */ -class GemmaModel extends GemmaPreTrainedModel { } - -class GemmaForCausalLM extends GemmaPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Gemma2 models - -/** - * The bare Gemma2 Model outputting raw hidden-states without any specific head on top. - */ -class Gemma2PreTrainedModel extends PreTrainedModel { } -/** - * The bare Gemma2 Model outputting raw hidden-states without any specific head on top. - */ -class Gemma2Model extends Gemma2PreTrainedModel { } - -class Gemma2ForCausalLM extends Gemma2PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Gemma3 models - -/** - * The bare Gemma3 Model outputting raw hidden-states without any specific head on top. - */ -class Gemma3PreTrainedModel extends PreTrainedModel { } -/** - * The bare Gemma3 Model outputting raw hidden-states without any specific head on top. - */ -class Gemma3Model extends Gemma3PreTrainedModel { } - -class Gemma3ForCausalLM extends Gemma3PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class OpenELMPreTrainedModel extends PreTrainedModel { } -class OpenELMModel extends OpenELMPreTrainedModel { } - -class OpenELMForCausalLM extends OpenELMPreTrainedModel { } - - -////////////////////////////////////////////////// -// Qwen2 models - -/** - * The bare Qwen2 Model outputting raw hidden-states without any specific head on top. - */ -class Qwen2PreTrainedModel extends PreTrainedModel { } -/** - * The bare Qwen2 Model outputting raw hidden-states without any specific head on top. - */ -class Qwen2Model extends Qwen2PreTrainedModel { } - -class Qwen2ForCausalLM extends Qwen2PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Qwen3 models - -/** - * The bare Qwen3 Model outputting raw hidden-states without any specific head on top. - */ -class Qwen3PreTrainedModel extends PreTrainedModel { } -/** - * The bare Qwen3 Model outputting raw hidden-states without any specific head on top. - */ -class Qwen3Model extends Qwen3PreTrainedModel { } - -class Qwen3ForCausalLM extends Qwen3PreTrainedModel { } -////////////////////////////////////////////////// - -class Qwen2VLPreTrainedModel extends PreTrainedModel { - forward_params = [ - // Text inputs - 'input_ids', - 'attention_mask', - 'position_ids', - 'past_key_values', - - // Vision inputs - 'pixel_values', - 'image_grid_thw', - ]; -} -class Qwen2VLForConditionalGeneration extends Qwen2VLPreTrainedModel { - - /** - * Calculate the 3D rope index based on image and video's temporal, height and width in LLM. - * - * Explanation: - * Each embedding sequence contains vision embedding and text embedding or just contains text embedding. - * - * For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs. - * Examples: - * input_ids: [T T T T T], here T is for text. - * temporal position_ids: [0, 1, 2, 3, 4] - * height position_ids: [0, 1, 2, 3, 4] - * width position_ids: [0, 1, 2, 3, 4] - * - * For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part - * and 1D rotary position embeddin for text part. - * Examples: - * Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches. - * input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. - * vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] - * vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] - * vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] - * text temporal position_ids: [3, 4, 5, 6, 7] - * text height position_ids: [3, 4, 5, 6, 7] - * text width position_ids: [3, 4, 5, 6, 7] - * Here we calculate the text start position_ids as the max vision position_ids plus 1. - * - * @param {Tensor} input_ids Indices of input sequence tokens in the vocabulary. Tensor of shape `(batch_size, sequence_length)`. - * @param {Tensor} image_grid_thw (Optional) The temporal, height and width of feature shape of each image in LLM. Tensor of shape `(num_images, 3)`. - * @param {Tensor} video_grid_thw (Optional) The temporal, height and width of feature shape of each video in LLM. Tensor of shape `(num_videos, 3)`. - * @param {Tensor} attention_mask (Optional) Mask to avoid performing attention on padding token indices. Tensor of shape `(batch_size, sequence_length)`. Mask values selected in `[0, 1]`: - * - 1 for tokens that are **not masked**, - * - 0 for tokens that are **masked**. - * @returns {[Tensor, Tensor]} [position_ids, mrope_position_deltas] with: - * - position_ids: Tensor of shape `(3, batch_size, sequence_length)`. - * - mrope_position_deltas: Tensor of shape `(batch_size)`. - */ - get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask) { - // @ts-ignore - const { vision_config, image_token_id, video_token_id, vision_start_token_id } = this.config; - const spatial_merge_size = vision_config.spatial_merge_size ?? 2; - - const mrope_position_deltas = []; - if (image_grid_thw || video_grid_thw) { - let total_input_ids = input_ids.tolist(); - if (!attention_mask) { - attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.ones_like)(input_ids); - } - - const attention_mask_list = attention_mask.tolist(); - const position_ids_list = Array.from({ length: 3 }, _ => Array.from({ length: input_ids.dims[0] }, _ => Array.from({ length: input_ids.dims[1] }, _ => 1))); - - const image_grid_thw_list = image_grid_thw ? image_grid_thw.tolist() : []; - const video_grid_thw_list = video_grid_thw ? video_grid_thw.tolist() : []; - - let image_index = 0; - let video_index = 0; - for (let i = 0; i < total_input_ids.length; ++i) { - const ids = total_input_ids[i].filter((_, j) => attention_mask_list[i][j] == 1); - - const vision_start_indices = ids.reduce((acc, x, idx) => { - if (x == vision_start_token_id) acc.push(idx); - return acc; - }, []); - - const vision_tokens = vision_start_indices.map(x => ids[x + 1]); - const image_nums = vision_tokens.filter(x => x == image_token_id).length; - const video_nums = vision_tokens.filter(x => x == video_token_id).length; - - /** @type {number[][]} */ - let llm_pos_ids_list = []; - let st = 0; - let remain_images = image_nums; - let remain_videos = video_nums; - for (let j = 0; j < vision_tokens.length; ++j) { - const next_image_token = ids.findIndex((x, i) => i > st && x == image_token_id); - const next_video_token = ids.findIndex((x, i) => i > st && x == video_token_id); - - const ed_image = (remain_images > 0 && next_image_token !== -1) - ? next_image_token - : ids.length + 1; - - const ed_video = (remain_videos > 0 && next_video_token !== -1) - ? next_video_token - : ids.length + 1; - - let ed; - let t, h, w; - if (ed_image < ed_video) { - ([t, h, w] = image_grid_thw_list[image_index]); - ++image_index; - --remain_images; - ed = ed_image; - } else { - ([t, h, w] = video_grid_thw_list[video_index]); - ++video_index; - --remain_videos; - ed = ed_video; - } - - const [llm_grid_t, llm_grid_h, llm_grid_w] = [ - Number(t), - Math.floor(Number(h) / spatial_merge_size), - Math.floor(Number(w) / spatial_merge_size) - ] - const text_len = ed - st; - const st_idx = llm_pos_ids_list.length > 0 - ? (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(llm_pos_ids_list.at(-1))[0] + 1 - : 0; - - llm_pos_ids_list.push( - Array.from({ length: 3 * text_len }, (_, i) => st_idx + (i % text_len)) - ) - - const offset = text_len + st_idx; - const grid_size = llm_grid_t * llm_grid_h * llm_grid_w; - const t_index = Array.from({ length: grid_size }, (_, i) => offset + Math.floor(i / (llm_grid_h * llm_grid_w))) - const h_index = Array.from({ length: grid_size }, (_, i) => offset + Math.floor(i / llm_grid_w) % llm_grid_h) - const w_index = Array.from({ length: grid_size }, (_, i) => offset + i % llm_grid_w) - - llm_pos_ids_list.push([t_index, h_index, w_index].flat()) - - st = ed + grid_size; - } - - if (st < ids.length) { - const st_idx = llm_pos_ids_list.length > 0 - ? (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(llm_pos_ids_list.at(-1))[0] + 1 - : 0; - const text_len = ids.length - st; - - llm_pos_ids_list.push( - Array.from({ length: 3 * text_len }, (_, i) => (st_idx + (i % text_len))) - ) - } - - // NOTE: Each item in llm_pos_ids_list is an array of shape (3, text_len), - // meaning to perform concatenation along dim=1, we can do the following: - const num_items = llm_pos_ids_list.reduce((acc, x) => acc + x.length, 0); - /** @type {number[]} */ - const llm_positions = new Array(num_items); - let index = 0; - for (let x = 0; x < 3; ++x) { - for (let y = 0; y < llm_pos_ids_list.length; ++y) { - const val = llm_pos_ids_list[y]; - const text_len = val.length / 3; - for (let z = x * text_len; z < (x + 1) * text_len; ++z) { - llm_positions[index++] = val[z]; - } - } - } - - let count = 0; - const attn_mask = attention_mask_list[i]; - for (let y = 0; y < attn_mask.length; ++y) { - if (attn_mask[y] == 1) { - for (let x = 0; x < 3; ++x) { - position_ids_list[x][i][y] = llm_positions[x * num_items / 3 + count]; - } - ++count; - } - } - - const max_llm_positions = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(llm_positions)[0]; - mrope_position_deltas.push(max_llm_positions + 1 - total_input_ids[i].length); - } - - return [ - new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', position_ids_list.flat(Infinity), [3, input_ids.dims[0], input_ids.dims[1]]), - new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', mrope_position_deltas, [mrope_position_deltas.length, 1]), - ]; - - } else { // Text-only - if (attention_mask) { - const { data, dims } = cumsum_masked_fill(attention_mask); - - const position_ids = BigInt64Array.from( - { length: 3 * data.length }, - (_, i) => data[i % data.length] - ); - /** @type {bigint[]} */ - const mrope_position_deltas = Array.from( - { length: dims[0] }, - (_, i) => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_11__.max)(data.subarray(dims[1] * i, dims[1] * (i + 1)))[0] + 1n + BigInt(dims[1]) - ); - - return [ - new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', position_ids, [3, ...dims]), - new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', mrope_position_deltas, [mrope_position_deltas.length, 1]), - ] - } else { - const [batch_size, seq_length] = input_ids.dims; - const position_ids = BigInt64Array.from( - { length: 3 * batch_size * seq_length }, - (_, i) => BigInt(Math.floor(i % seq_length / batch_size)), - ); - - return [ - new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor('int64', position_ids, [3, ...input_ids.dims]), - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.zeros)([batch_size, 1]), - ] - } - } + }; + /** + * Deletes the cache entry for the given request. + * + * Removes the hash entry from `HASH_CACHE_NAME`. Note: cross-origin storage itself does not + * expose a delete API, so only the local hash mapping is removed. For non-LFS URLs this + * permanently prevents `match` from resolving the file. For LFS-backed URLs, `match` will + * re-fetch the LFS pointer file on the next call and repopulate the hash cache automatically. + * + * Implements `CacheInterface.delete`. + * + * @param {string} request + * @returns {Promise} Resolves to `true` if the hash entry was deleted, `false` otherwise. + */ + delete = async (request) => { + try { + const hashCache = await this._getHashCache(); + return await hashCache.delete(request); + } catch { + return false; } - - async encode_image({ pixel_values, image_grid_thw }) { - const features = (await sessionRun(this.sessions['vision_encoder'], { pixel_values, grid_thw: image_grid_thw })).image_features; - return features; + }; + /** + * Resolves the SHA-256 hash for a given URL. + * + * Returns the cached hash immediately if one has been persisted to `HASH_CACHE_NAME`. + * Otherwise falls back to `_getLfsFileHash` to retrieve the hash from the Hugging Face + * LFS pointer file, persisting the result to `HASH_CACHE_NAME` for future lookups. + * + * Returns `null` if the hash cannot be determined (e.g. non-LFS URL with no cached entry). + * + * @param {string} url The resource URL to resolve a hash for. + * @returns {Promise} The hex-encoded SHA-256 hash, or `null` if unavailable. + */ + _getFileHash = async (url) => { + try { + const hashCache = await this._getHashCache(); + const cached = await hashCache.match(url); + if (cached) { + return cached.text(); + } + const hash = await this._getLfsFileHash(url); + if (hash) { + await hashCache.put(url, new Response(hash)); + return hash; + } + return null; + } catch { + return null; } - - _merge_input_ids_with_image_features(kwargs) { - return default_merge_input_ids_with_image_features({ - // @ts-ignore - image_token_id: this.config.image_token_id, - ...kwargs - }) + }; + /** + * Attempts to retrieve the SHA-256 hash for a Hugging Face resource URL from its raw + * Git LFS pointer file. + * + * Only applicable to URLs containing `/resolve/` (i.e. Hugging Face resolved file URLs). + * The `/resolve/` segment is rewritten to `/raw/` to fetch the LFS pointer directly. + * Returns `null` for non-LFS URLs or when the network request fails. + * + * @see https://huggingface.co/docs/hub/en/storage-backends#xet + * @param {string} url The resolved Hugging Face URL of the resource. + * @returns {Promise} The hex-encoded SHA-256 hash, or `null` if unavailable. + */ + _getLfsFileHash = async (url) => { + if (!url.includes("/resolve/")) { + return null; } - - prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { - // Overwritten -- in specific circumstances we don't want to forward image inputs to the model - if (model_inputs.attention_mask && !model_inputs.position_ids) { - // Calculate position_ids and rope_deltas - if (!model_inputs.past_key_values) { - ([model_inputs.position_ids, model_inputs.rope_deltas] = this.get_rope_index( - model_inputs.input_ids, - model_inputs.image_grid_thw, - model_inputs.video_grid_thw, - model_inputs.attention_mask, - )); - - } else { - model_inputs.pixel_values = null; - // model_inputs.pixel_values_videos = null; - - const delta = BigInt(Object.values(model_inputs.past_key_values)[0].dims.at(-2)); - const rope_deltas_list = model_inputs.rope_deltas.map(x => delta + x); - model_inputs.position_ids = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.stack)([rope_deltas_list, rope_deltas_list, rope_deltas_list], 0) - } - } - - return model_inputs; + const rawUrl = url.replace("/resolve/", "/raw/"); + try { + const text = await fetch(rawUrl).then((r) => r.text()); + const match = text.match(/^oid sha256:([0-9a-f]+)$/m); + return match ? match[1] : null; + } catch { + return null; } -} - - -////////////////////////////////////////////////// -// Phi models -class PhiPreTrainedModel extends PreTrainedModel { } -/** - * The bare Phi Model outputting raw hidden-states without any specific head on top. - */ -class PhiModel extends PhiPreTrainedModel { } - -class PhiForCausalLM extends PhiPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Phi3 models -class Phi3PreTrainedModel extends PreTrainedModel { } - -/** - * The bare Phi3 Model outputting raw hidden-states without any specific head on top. - */ -class Phi3Model extends Phi3PreTrainedModel { } - -class Phi3ForCausalLM extends Phi3PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Bloom models -/** - * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). - */ -class BloomPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Bloom Model transformer outputting raw hidden-states without any specific head on top. - */ -class BloomModel extends BloomPreTrainedModel { } - -/** - * The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). - */ -class BloomForCausalLM extends BloomPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MPT models -class MptPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Mpt Model transformer outputting raw hidden-states without any specific head on top. - */ -class MptModel extends MptPreTrainedModel { } - -/** - * The MPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). - */ -class MptForCausalLM extends MptPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// OPT models -class OPTPreTrainedModel extends PreTrainedModel { } - -/** - * The bare OPT Model outputting raw hidden-states without any specific head on top. - */ -class OPTModel extends OPTPreTrainedModel { } - -/** - * The OPT Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings). - */ -class OPTForCausalLM extends OPTPreTrainedModel { } -////////////////////////////////////////////////// + }; + /** + * Computes the SHA-256 hash of a `Blob`'s contents. + * + * @param {Blob} blob The blob to hash. + * @returns {Promise} The lowercase hex-encoded SHA-256 hash. + */ + _getBlobHash = async (blob) => { + const arrayBuffer = await blob.arrayBuffer(); + const hashBuffer = await crypto.subtle.digest(HASH_ALGORITHM, arrayBuffer); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join(""); + }; +}; -////////////////////////////////////////////////// -class ViTPreTrainedModel extends PreTrainedModel { } -class ViTModel extends ViTPreTrainedModel { } -class ViTForImageClassification extends ViTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +// src/utils/cache.js +async function getCache(file_cache_dir = null) { + let cache2 = null; + if (env.useCustomCache) { + if (!env.customCache) { + throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined."); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class IJepaPreTrainedModel extends PreTrainedModel { } -class IJepaModel extends IJepaPreTrainedModel { } -class IJepaForImageClassification extends IJepaPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + if (!env.customCache.match || !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" + ); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class VitPosePreTrainedModel extends PreTrainedModel { } - -/** - * The VitPose model with a pose estimation head on top. - */ -class VitPoseForPoseEstimation extends VitPosePreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class PvtPreTrainedModel extends PreTrainedModel { } -class PvtModel extends PvtPreTrainedModel { } -class PvtForImageClassification extends PvtPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + cache2 = env.customCache; + } + if (!cache2 && env.experimental_useCrossOriginStorage && CrossOriginStorage.isAvailable()) { + cache2 = new CrossOriginStorage(); + } + if (!cache2 && env.useBrowserCache) { + if (typeof caches === "undefined") { + throw Error("Browser cache is not available in this environment."); + } + try { + cache2 = await caches.open(env.cacheKey); + } catch (e) { + logger.warn("An error occurred while opening the browser cache:", e); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class ViTMAEPreTrainedModel extends PreTrainedModel { } -class ViTMAEModel extends ViTMAEPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class ViTMSNPreTrainedModel extends PreTrainedModel { } -class ViTMSNModel extends ViTMSNPreTrainedModel { } -class ViTMSNForImageClassification extends ViTMSNPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + } + if (!cache2 && env.useFSCache) { + if (!apis.IS_FS_AVAILABLE) { + throw Error("File System Cache is not available in this environment."); } + cache2 = new FileCache(file_cache_dir ?? env.cacheDir); + } + return cache2; } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class GroupViTPreTrainedModel extends PreTrainedModel { } -class GroupViTModel extends GroupViTPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class FastViTPreTrainedModel extends PreTrainedModel { } -class FastViTModel extends FastViTPreTrainedModel { } -class FastViTForImageClassification extends FastViTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class VitMattePreTrainedModel extends PreTrainedModel { } - -/** - * ViTMatte framework leveraging any vision backbone e.g. for ADE20k, CityScapes. - * - * **Example:** Perform image matting with a `VitMatteForImageMatting` model. - * ```javascript - * import { AutoProcessor, VitMatteForImageMatting, RawImage } from '@huggingface/transformers'; - * - * // Load processor and model - * const processor = await AutoProcessor.from_pretrained('Xenova/vitmatte-small-distinctions-646'); - * const model = await VitMatteForImageMatting.from_pretrained('Xenova/vitmatte-small-distinctions-646'); - * - * // Load image and trimap - * const image = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_image.png'); - * const trimap = await RawImage.fromURL('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/vitmatte_trimap.png'); - * - * // Prepare image + trimap for the model - * const inputs = await processor(image, trimap); - * - * // Predict alpha matte - * const { alphas } = await model(inputs); - * // Tensor { - * // dims: [ 1, 1, 640, 960 ], - * // type: 'float32', - * // size: 614400, - * // data: Float32Array(614400) [ 0.9894027709960938, 0.9970508813858032, ... ] - * // } - * ``` - * - * You can visualize the alpha matte as follows: - * ```javascript - * import { Tensor, cat } from '@huggingface/transformers'; - * - * // Visualize predicted alpha matte - * const imageTensor = image.toTensor(); - * - * // Convert float (0-1) alpha matte to uint8 (0-255) - * const alphaChannel = alphas - * .squeeze(0) - * .mul_(255) - * .clamp_(0, 255) - * .round_() - * .to('uint8'); - * - * // Concatenate original image with predicted alpha - * const imageData = cat([imageTensor, alphaChannel], 0); - * - * // Save output image - * const outputImage = RawImage.fromTensor(imageData); - * outputImage.save('output.png'); - * ``` - */ -class VitMatteForImageMatting extends VitMattePreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new ImageMattingOutput(await super._call(model_inputs)); +async function tryCache(cache2, ...names) { + for (let name of names) { + try { + let result = await cache2.match(name); + if (result) return result; + } catch (e) { + continue; } + } + return void 0; } -////////////////////////////////////////////////// -////////////////////////////////////////////////// -class MobileViTPreTrainedModel extends PreTrainedModel { } -class MobileViTModel extends MobileViTPreTrainedModel { } -class MobileViTForImageClassification extends MobileViTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +// src/utils/lru_cache.js +var LRUCache2 = class { + /** @type {number} */ + #capacity; + /** @type {Map} */ + #cache; + /** + * Creates an LRUCache instance. + * @param {number} capacity The maximum number of items the cache can hold. + */ + constructor(capacity) { + this.#capacity = capacity; + this.#cache = /* @__PURE__ */ new Map(); + } + /** + * Retrieves the value associated with the given key and marks the key as recently used. + * @param {any} key The key to retrieve. + * @returns {any} The value associated with the key, or undefined if the key does not exist. + */ + get(key) { + if (!this.#cache.has(key)) return void 0; + const value = this.#cache.get(key); + this.#cache.delete(key); + this.#cache.set(key, value); + return value; + } + /** + * Inserts or updates the key-value pair in the cache. + * If the key already exists, it is updated and marked as recently used. + * If the cache exceeds its capacity, the least recently used item is evicted. + * @param {any} key The key to add or update. + * @param {any} value The value to associate with the key. + */ + put(key, value) { + if (this.#cache.has(key)) { + this.#cache.delete(key); } -} -// TODO: MobileViTForSemanticSegmentation - -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class MobileViTV2PreTrainedModel extends PreTrainedModel { } -class MobileViTV2Model extends MobileViTV2PreTrainedModel { } -class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + this.#cache.set(key, value); + if (this.#cache.size > this.#capacity) { + this.#cache.delete(this.#cache.keys().next().value); } -} -// TODO: MobileViTV2ForSemanticSegmentation - -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class OwlViTPreTrainedModel extends PreTrainedModel { } -class OwlViTModel extends OwlViTPreTrainedModel { } -class OwlViTForObjectDetection extends OwlViTPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Owlv2PreTrainedModel extends PreTrainedModel { } -class Owlv2Model extends Owlv2PreTrainedModel { } -class Owlv2ForObjectDetection extends Owlv2PreTrainedModel { } -////////////////////////////////////////////////// + } + /** + * Removes the entry for the given key from the cache. + * @param {any} key The key to delete. + * @returns {boolean} `true` if the entry existed and was removed, `false` otherwise. + */ + delete(key) { + return this.#cache.delete(key); + } + /** + * Clears the cache. + */ + clear() { + this.#cache.clear(); + } +}; -////////////////////////////////////////////////// -// Beit Models -class BeitPreTrainedModel extends PreTrainedModel { } -class BeitModel extends BeitPreTrainedModel { } -class BeitForImageClassification extends BeitPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +// src/utils/memoize_promise.js +var MAX_CACHE_SIZE = 100; +var cache = new LRUCache2(MAX_CACHE_SIZE); +function memoizePromise(key, factory) { + const cached = cache.get(key); + if (cached !== void 0) { + return cached; + } + const promise = factory().then( + (value) => value, + (err) => { + cache.delete(key); + return Promise.reject(err); } + ); + cache.put(key, promise); + return promise; } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DetrPreTrainedModel extends PreTrainedModel { } -class DetrModel extends DetrPreTrainedModel { } -class DetrForObjectDetection extends DetrPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new DetrObjectDetectionOutput(await super._call(model_inputs)); +// src/utils/model_registry/get_file_metadata.js +async function fetch_file_head(urlOrPath) { + if (!isValidUrl(urlOrPath, ["http:", "https:"])) { + return null; + } + const headers = getFetchHeaders(urlOrPath); + headers.set("Range", "bytes=0-0"); + return env.fetch(urlOrPath, { method: "GET", headers, cache: "no-store" }); +} +function get_file_metadata(path_or_repo_id, filename, options = {}) { + const key = makePretrainedOptionsKey(path_or_repo_id, options, filename); + return memoizePromise(key, () => _get_file_metadata(path_or_repo_id, filename, options)); +} +async function _get_file_metadata(path_or_repo_id, filename, options) { + const cache2 = await getCache(options?.cache_dir); + const { localPath, remoteURL, proposedCacheKey, validModelId } = buildResourcePaths( + path_or_repo_id, + filename, + options, + cache2 + ); + const cachedResponse = await checkCachedResource(cache2, localPath, proposedCacheKey); + if (cachedResponse !== void 0 && typeof cachedResponse !== "string") { + const size = cachedResponse.headers.get("content-length"); + const contentType = cachedResponse.headers.get("content-type"); + return { + exists: true, + size: size ? parseInt(size, 10) : void 0, + contentType: contentType || void 0, + fromCache: true + }; + } + if (env.allowLocalModels) { + const isURL = isValidUrl(localPath, ["http:", "https:"]); + if (!isURL) { + try { + const response = await getFile(localPath); + if (typeof response !== "string" && response.status !== 404) { + const size = response.headers.get("content-length"); + const contentType = response.headers.get("content-type"); + return { + exists: true, + size: size ? parseInt(size, 10) : void 0, + contentType: contentType || void 0, + fromCache: false + }; + } + } catch (e) { + } } -} - -class DetrForSegmentation extends DetrPreTrainedModel { - /** - * Runs the model with the provided inputs - * @param {Object} model_inputs Model inputs - * @returns {Promise} Object containing segmentation outputs - */ - async _call(model_inputs) { - return new DetrSegmentationOutput(await super._call(model_inputs)); + } + if (env.allowRemoteModels && !options.local_files_only && validModelId) { + const rangeResponse = await fetch_file_head(remoteURL); + if (rangeResponse && rangeResponse.status >= 200 && rangeResponse.status < 300) { + let size; + const contentType = rangeResponse.headers.get("content-type"); + if (rangeResponse.status === 206) { + const contentRange = rangeResponse.headers.get("content-range"); + if (contentRange) { + const match = contentRange.match(/bytes \d+-\d+\/(\d+)/); + if (match) { + size = parseInt(match[1], 10); + } + } + } else if (rangeResponse.status === 200) { + try { + await rangeResponse.body?.cancel(); + } catch (cancelError) { + } + } + if (size === void 0) { + const contentLength = rangeResponse.headers.get("content-length"); + size = contentLength ? parseInt(contentLength, 10) : void 0; + } + return { + exists: true, + size, + contentType: contentType || void 0, + fromCache: false + }; } -} - -class DetrObjectDetectionOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification logits (including no-object) for all queries. - * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). - * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). - */ - constructor({ logits, pred_boxes }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; + if (rangeResponse && rangeResponse.status !== 404 && rangeResponse.status !== 416) { + handleError(rangeResponse.status, remoteURL, true); } + } + return { exists: false, fromCache: false }; } -class DetrSegmentationOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits The output logits of the model. - * @param {Tensor} output.pred_boxes Predicted boxes. - * @param {Tensor} output.pred_masks Predicted masks. - */ - constructor({ logits, pred_boxes, pred_masks }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; - this.pred_masks = pred_masks; - } +// src/utils/hub.js +async function getFile(urlOrPath) { + if (env.useFS && !isValidUrl(urlOrPath, ["http:", "https:", "blob:"])) { + return new FileResponse( + urlOrPath instanceof URL ? urlOrPath.protocol === "file:" ? urlOrPath.pathname : urlOrPath.toString() : urlOrPath + ); + } else { + return env.fetch(urlOrPath, { + headers: getFetchHeaders(urlOrPath) + }); + } } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class RTDetrPreTrainedModel extends PreTrainedModel { } -class RTDetrModel extends RTDetrPreTrainedModel { } -class RTDetrForObjectDetection extends RTDetrPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new RTDetrObjectDetectionOutput(await super._call(model_inputs)); +function getFetchHeaders(urlOrPath) { + const isNode = typeof process !== "undefined" && process?.release?.name === "node"; + const headers = new Headers(); + if (isNode) { + const IS_CI = !!process.env?.TESTING_REMOTELY; + const version2 = env.version; + headers.set("User-Agent", `transformers.js/${version2}; is_ci/${IS_CI};`); + const isHFURL = isValidUrl(urlOrPath, ["http:", "https:"], ["huggingface.co", "hf.co"]); + if (isHFURL) { + const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; + if (token) { + headers.set("Authorization", `Bearer ${token}`); + } } + } else { + } + return headers; +} +function buildResourcePaths(path_or_repo_id, filename, options = {}, cache2 = null) { + const revision = options.revision ?? "main"; + const requestURL = pathJoin(path_or_repo_id, filename); + const validModelId = isValidHfModelId(path_or_repo_id); + const localPath = validModelId ? pathJoin(env.localModelPath, requestURL) : requestURL; + const remoteURL = pathJoin( + env.remoteHost, + env.remotePathTemplate.replaceAll("{model}", path_or_repo_id).replaceAll("{revision}", encodeURIComponent(revision)), + filename + ); + const proposedCacheKey = cache2 instanceof FileCache ? ( + // Choose cache key for filesystem cache + // When using the main revision (default), we use the request URL as the cache key. + // If a specific revision is requested, we account for this in the cache key. + revision === "main" ? requestURL : pathJoin(path_or_repo_id, revision, filename) + ) : remoteURL; + return { + requestURL, + localPath, + remoteURL, + proposedCacheKey, + validModelId + }; } - -class RTDetrObjectDetectionOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification logits (including no-object) for all queries. - * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). - * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). - */ - constructor({ logits, pred_boxes }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; - } +async function checkCachedResource(cache2, localPath, proposedCacheKey) { + if (!cache2) { + return void 0; + } + return await tryCache(cache2, localPath, proposedCacheKey); } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class RTDetrV2PreTrainedModel extends PreTrainedModel { } -class RTDetrV2Model extends RTDetrV2PreTrainedModel { } -class RTDetrV2ForObjectDetection extends RTDetrV2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new RTDetrV2ObjectDetectionOutput(await super._call(model_inputs)); - } +async function storeCachedResource(path_or_repo_id, filename, cache2, cacheKey, response, result, options = {}) { + if (await cache2.match(cacheKey) !== void 0) { + return; + } + if (typeof Cache !== "undefined" && cache2 instanceof Cache && !isValidUrl(toAbsoluteURL(cacheKey, { allowUnresolved: true }), ["http:", "https:"])) { + return; + } + if (!result) { + const wrapped_progress = options.progress_callback ? (data) => dispatchCallback(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + ...data + }) : void 0; + await cache2.put( + cacheKey, + /** @type {Response} */ + response, + wrapped_progress + ); + } else if (typeof response !== "string") { + const headers = new Headers(response.headers); + headers.set("content-length", result.byteLength.toString()); + await cache2.put( + cacheKey, + new Response( + /** @type {any} */ + result, + { + headers + } + ) + ).catch((err) => { + logger.warn(`Unable to add response to browser cache: ${err}.`); + }); + } } - -class RTDetrV2ObjectDetectionOutput extends RTDetrObjectDetectionOutput { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class RFDetrPreTrainedModel extends PreTrainedModel { } -class RFDetrModel extends RFDetrPreTrainedModel { } -class RFDetrForObjectDetection extends RFDetrPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new RFDetrObjectDetectionOutput(await super._call(model_inputs)); +async function loadResourceFile(path_or_repo_id, filename, fatal = true, options = {}, return_path = false, cache2 = null) { + const { requestURL, localPath, remoteURL, proposedCacheKey, validModelId } = buildResourcePaths( + path_or_repo_id, + filename, + options, + cache2 + ); + let cacheKey; + let toCacheResponse = false; + let response; + response = await checkCachedResource(cache2, localPath, proposedCacheKey); + const cacheHit = response !== void 0; + if (cacheHit) { + cacheKey = proposedCacheKey; + } else { + if (env.allowLocalModels) { + const isURL = isValidUrl(requestURL, ["http:", "https:"]); + if (!isURL) { + try { + response = await getFile(localPath); + cacheKey = localPath; + } catch (e) { + logger.warn(`Unable to load from local path "${localPath}": "${e}"`); + } + } else if (options.local_files_only) { + throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`); + } else if (!env.allowRemoteModels) { + throw new Error( + `\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.` + ); + } } -} - -class RFDetrObjectDetectionOutput extends RTDetrObjectDetectionOutput { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DFinePreTrainedModel extends PreTrainedModel { } -class DFineModel extends DFinePreTrainedModel { } -class DFineForObjectDetection extends DFinePreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new RTDetrObjectDetectionOutput(await super._call(model_inputs)); + if (response === void 0 || typeof response !== "string" && response.status === 404) { + if (options.local_files_only || !env.allowRemoteModels) { + if (fatal) { + throw new ModelFileNotFoundError( + `\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".` + ); + } else { + return null; + } + } + if (!validModelId) { + throw new ModelFileNotFoundError( + `Local file missing at "${localPath}" and download aborted due to invalid model ID "${path_or_repo_id}".` + ); + } + response = await getFile(remoteURL); + if (response.status !== 200) { + return handleError(response.status, remoteURL, fatal); + } + cacheKey = proposedCacheKey; + } + toCacheResponse = cache2 && // 1. A caching system is available + typeof Response !== "undefined" && // 2. `Response` is defined (i.e., we are in a browser-like environment) + response instanceof Response && // 3. result is a `Response` object (i.e., not a `FileResponse`) + response.status === 200; + } + dispatchCallback(options.progress_callback, { + status: "download", + name: path_or_repo_id, + file: filename + }); + let result; + if (apis.IS_NODE_ENV && return_path) { + } else { + let buffer; + if (typeof response !== "string") { + if (!options.progress_callback) { + buffer = new Uint8Array(await response.arrayBuffer()); + } else if (cacheHit && // The item is being read from the cache + typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)) { + buffer = new Uint8Array(await response.arrayBuffer()); + dispatchCallback(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + progress: 100, + loaded: buffer.length, + total: buffer.length + }); + } else { + let expectedSize; + const contentLength = response.headers.get("content-length"); + if (contentLength) { + expectedSize = parseInt(contentLength, 10); + } else { + try { + const metadata = await get_file_metadata(path_or_repo_id, filename, options); + if (metadata.size) { + expectedSize = metadata.size; + } + } catch (e) { + } + } + buffer = await readResponse( + response, + (data) => { + dispatchCallback(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + ...data + }); + }, + expectedSize + ); + } + } + result = buffer; + } + if ( + // Only cache web responses + // i.e., do not cache FileResponses (prevents duplication) + toCacheResponse && cacheKey && typeof response !== "string" + ) { + await storeCachedResource(path_or_repo_id, filename, cache2, cacheKey, response, result, options); + } + if (apis.IS_NODE_ENV && return_path && options.progress_callback && typeof response !== "string") { + const size = parseInt(response.headers.get("content-length"), 10) || 0; + dispatchCallback(options.progress_callback, { + status: "progress", + name: path_or_repo_id, + file: filename, + progress: 100, + loaded: size, + total: size + }); + } + dispatchCallback(options.progress_callback, { + status: "done", + name: path_or_repo_id, + file: filename + }); + if (result) { + if (!apis.IS_NODE_ENV && return_path) { + throw new Error("Cannot return path in a browser environment."); } + return result; + } + if (response instanceof FileResponse) { + return response.filePath; + } + const cachedResponse = await cache2?.match(cacheKey); + if (cachedResponse instanceof FileResponse) { + return cachedResponse.filePath; + } else if (cachedResponse instanceof Response) { + return new Uint8Array(await cachedResponse.arrayBuffer()); + } else if (typeof cachedResponse === "string") { + return cachedResponse; + } + throw new Error("Unable to get model file path or buffer."); } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class TableTransformerPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) - * outputting raw hidden-states without any specific head on top. - */ -class TableTransformerModel extends TableTransformerPreTrainedModel { } - -/** - * Table Transformer Model (consisting of a backbone and encoder-decoder Transformer) - * with object detection heads on top, for tasks such as COCO detection. - */ -class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new TableTransformerObjectDetectionOutput(await super._call(model_inputs)); +var INFLIGHT_LOADS = /* @__PURE__ */ new Map(); +async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}, return_path = false) { + if (!env.allowLocalModels) { + if (options.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`)." + ); + } else if (!env.allowRemoteModels) { + throw Error( + "Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`." + ); + } + } + const key = makePretrainedOptionsKey(path_or_repo_id, options, filename, fatal, return_path); + const { progress_callback } = options; + const loads = progress_callback instanceof DefaultProgressCallback ? progress_callback.loads : INFLIGHT_LOADS; + let pending = loads.get(key); + if (!pending) { + dispatchCallback(progress_callback, { + status: "initiate", + name: path_or_repo_id, + file: filename + }); + pending = getCache(options.cache_dir).then( + (cache2) => loadResourceFile(path_or_repo_id, filename, fatal, options, return_path, cache2) + ); + if (loads === INFLIGHT_LOADS) { + pending = pending.finally(() => INFLIGHT_LOADS.delete(key)); } + loads.set(key, pending); + } + return await pending; } -class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class DeiTPreTrainedModel extends PreTrainedModel { } -class DeiTModel extends DeiTPreTrainedModel { } -class DeiTForImageClassification extends DeiTPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +async function getModelText(modelPath, fileName, fatal = true, options = {}) { + const buffer = await getModelFile(modelPath, fileName, fatal, options, false); + if (buffer === null) { + return null; + } + const decoder = new TextDecoder("utf-8"); + return decoder.decode( + /** @type {Uint8Array} */ + buffer + ); +} +async function getModelJSON(modelPath, fileName, fatal = true, options = {}) { + const text = await getModelText(modelPath, fileName, fatal, options); + if (text === null) { + return {}; + } + return JSON.parse(text); +} + +// src/utils/maths.js +function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = "bilinear", align_corners = false) { + const x_scale = out_width / in_width; + const y_scale = out_height / in_height; + const out_img = new input.constructor(out_height * out_width * in_channels); + const inStride = in_height * in_width; + const outStride = out_height * out_width; + for (let i = 0; i < out_height; ++i) { + for (let j2 = 0; j2 < out_width; ++j2) { + const outOffset = i * out_width + j2; + const x = (j2 + 0.5) / x_scale - 0.5; + const y = (i + 0.5) / y_scale - 0.5; + let x1 = Math.floor(x); + let y1 = Math.floor(y); + const x2 = Math.min(x1 + 1, in_width - 1); + const y2 = Math.min(y1 + 1, in_height - 1); + x1 = Math.max(x1, 0); + y1 = Math.max(y1, 0); + const s = x - x1; + const t = y - y1; + const w1 = (1 - s) * (1 - t); + const w2 = s * (1 - t); + const w3 = (1 - s) * t; + const w4 = s * t; + const yStride = y1 * in_width; + const xStride = y2 * in_width; + const idx1 = yStride + x1; + const idx2 = yStride + x2; + const idx3 = xStride + x1; + const idx4 = xStride + x2; + for (let k = 0; k < in_channels; ++k) { + const cOffset = k * inStride; + out_img[k * outStride + outOffset] = w1 * input[cOffset + idx1] + w2 * input[cOffset + idx2] + w3 * input[cOffset + idx3] + w4 * input[cOffset + idx4]; + } } + } + return out_img; } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class HieraPreTrainedModel extends PreTrainedModel { } -class HieraModel extends HieraPreTrainedModel { } -class HieraForImageClassification extends HieraPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +function permute_data(array, dims, axes) { + const shape = new Array(axes.length); + const stride = new Array(axes.length); + for (let i = axes.length - 1, s = 1; i >= 0; --i) { + stride[i] = s; + shape[i] = dims[axes[i]]; + s *= shape[i]; + } + const invStride = axes.map((_, i) => stride[axes.indexOf(i)]); + const permutedData = new array.constructor(array.length); + for (let i = 0; i < array.length; ++i) { + let newIndex = 0; + for (let j2 = dims.length - 1, k = i; j2 >= 0; --j2) { + newIndex += k % dims[j2] * invStride[j2]; + k = Math.floor(k / dims[j2]); + } + permutedData[newIndex] = array[i]; + } + return [permutedData, shape]; +} +function softmax(arr) { + const maxVal = max(arr)[0]; + const exps = arr.map((x) => Math.exp(x - maxVal)); + const sumExps = exps.reduce((acc, val) => acc + val, 0); + const softmaxArr = exps.map((x) => x / sumExps); + return ( + /** @type {T} */ + softmaxArr + ); +} +function log_softmax(arr) { + const maxVal = max(arr)[0]; + let sumExps = 0; + for (let i = 0; i < arr.length; ++i) { + sumExps += Math.exp(arr[i] - maxVal); + } + const logSum = Math.log(sumExps); + const logSoftmaxArr = arr.map((x) => x - maxVal - logSum); + return ( + /** @type {T} */ + logSoftmaxArr + ); +} +function dot(arr1, arr2) { + let result = 0; + for (let i = 0; i < arr1.length; ++i) { + result += arr1[i] * arr2[i]; + } + return result; +} +function cos_sim(arr1, arr2) { + const dotProduct = dot(arr1, arr2); + const magnitudeA = magnitude(arr1); + const magnitudeB = magnitude(arr2); + const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB); + return cosineSimilarity; +} +function magnitude(arr) { + return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0)); +} +function min2(arr) { + if (arr.length === 0) throw Error("Array must not be empty"); + let min3 = arr[0]; + let indexOfMin = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] < min3) { + min3 = arr[i]; + indexOfMin = i; } + } + return ( + /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */ + [min3, indexOfMin] + ); } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -/** - * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. - */ -class ResNetPreTrainedModel extends PreTrainedModel { } - -/** - * The bare ResNet model outputting raw features without any specific head on top. - */ -class ResNetModel extends ResNetPreTrainedModel { } - -/** - * ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. - */ -class ResNetForImageClassification extends ResNetPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +function max(arr) { + if (arr.length === 0) throw Error("Array must not be empty"); + let max2 = arr[0]; + let indexOfMax = 0; + for (let i = 1; i < arr.length; ++i) { + if (arr[i] > max2) { + max2 = arr[i]; + indexOfMax = i; } + } + return ( + /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */ + [max2, indexOfMax] + ); } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class SwinPreTrainedModel extends PreTrainedModel { } -class SwinModel extends SwinPreTrainedModel { } -class SwinForImageClassification extends SwinPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} -class SwinForSemanticSegmentation extends SwinPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Swin2SRPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Swin2SR Model transformer outputting raw hidden-states without any specific head on top. - */ -class Swin2SRModel extends Swin2SRPreTrainedModel { } - -/** - * Swin2SR Model transformer with an upsampler head on top for image super resolution and restoration. - * - * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64`. - * - * ```javascript - * import { AutoProcessor, Swin2SRForImageSuperResolution, RawImage } from '@huggingface/transformers'; - * - * // Load processor and model - * const model_id = 'Xenova/swin2SR-classical-sr-x2-64'; - * const processor = await AutoProcessor.from_pretrained(model_id); - * const model = await Swin2SRForImageSuperResolution.from_pretrained(model_id); - * - * // Prepare model inputs - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg'; - * const image = await RawImage.fromURL(url); - * const inputs = await processor(image); - * - * // Run model - * const outputs = await model(inputs); - * - * // Convert Tensor to RawImage - * const output = outputs.reconstruction.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8'); - * const outputImage = RawImage.fromTensor(output); - * // RawImage { - * // data: Uint8Array(786432) [ 41, 31, 24, ... ], - * // width: 512, - * // height: 512, - * // channels: 3 - * // } - * ``` - */ -class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DPTPreTrainedModel extends PreTrainedModel { } - -/** - * The bare DPT Model transformer outputting raw hidden-states without any specific head on top. - */ -class DPTModel extends DPTPreTrainedModel { } - -/** - * DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2. - * - * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas`. - * ```javascript - * import { DPTForDepthEstimation, AutoProcessor, RawImage, interpolate_4d } from '@huggingface/transformers'; - * - * // Load model and processor - * const model_id = 'Xenova/dpt-hybrid-midas'; - * const model = await DPTForDepthEstimation.from_pretrained(model_id); - * const processor = await AutoProcessor.from_pretrained(model_id); - * - * // Load image from URL - * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg'; - * const image = await RawImage.read(url); - * - * // Prepare image for the model - * const inputs = await processor(image); - * - * // Run model - * const { predicted_depth } = await model(inputs); - * - * // Interpolate to original size - * const prediction = (await interpolate_4d(predicted_depth.unsqueeze(1), { - * size: image.size.reverse(), - * mode: 'bilinear', - * })).squeeze(1); - * - * // Visualize the prediction - * const min = prediction.min().item(); - * const max = prediction.max().item(); - * const formatted = prediction.sub_(min).div_(max - min).mul_(255).to('uint8'); - * const depth = RawImage.fromTensor(formatted); - * // RawImage { - * // data: Uint8Array(307200) [ 85, 85, 84, ... ], - * // width: 640, - * // height: 480, - * // channels: 1 - * // } - * ``` - */ -class DPTForDepthEstimation extends DPTPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DepthAnythingPreTrainedModel extends PreTrainedModel { } - -/** - * Depth Anything Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2. - */ -class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class SapiensPreTrainedModel extends PreTrainedModel { } -class SapiensForSemanticSegmentation extends SapiensPreTrainedModel { } -class SapiensForDepthEstimation extends SapiensPreTrainedModel { } -class SapiensForNormalEstimation extends SapiensPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DepthProPreTrainedModel extends PreTrainedModel { } -class DepthProForDepthEstimation extends DepthProPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Metric3DPreTrainedModel extends PreTrainedModel { } -class Metric3DForDepthEstimation extends Metric3DPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Metric3Dv2PreTrainedModel extends PreTrainedModel { } -class Metric3Dv2ForDepthEstimation extends Metric3Dv2PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class MaskFormerPreTrainedModel extends PreTrainedModel { } -class MaskFormerModel extends MaskFormerPreTrainedModel { } -class MaskFormerForInstanceSegmentation extends MaskFormerPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class GLPNPreTrainedModel extends PreTrainedModel { } - -/** - * The bare GLPN encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top. - */ -class GLPNModel extends GLPNPreTrainedModel { } - -/** - * import { GLPNForDepthEstimation, AutoProcessor, RawImage, interpolate_4d } from '@huggingface/transformers'; - * - * // Load model and processor - * const model_id = 'Xenova/glpn-kitti'; - * const model = await GLPNForDepthEstimation.from_pretrained(model_id); - * const processor = await AutoProcessor.from_pretrained(model_id); - * - * // Load image from URL - * const url = 'http://images.cocodataset.org/val2017/000000039769.jpg'; - * const image = await RawImage.read(url); - * - * // Prepare image for the model - * const inputs = await processor(image); - * - * // Run model - * const { predicted_depth } = await model(inputs); - * - * // Interpolate to original size - * const prediction = (await interpolate_4d(predicted_depth.unsqueeze(1), { - * size: image.size.reverse(), - * mode: 'bilinear', - * })).squeeze(1); - * - * // Visualize the prediction - * const min = prediction.min().item(); - * const max = prediction.max().item(); - * const formatted = prediction.sub_(min).div_(max - min).mul_(255).to('uint8'); - * const depth = RawImage.fromTensor(formatted); - * // RawImage { - * // data: Uint8Array(307200) [ 85, 85, 84, ... ], - * // width: 640, - * // height: 480, - * // channels: 1 - * // } - * ``` - */ -class GLPNForDepthEstimation extends GLPNPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DonutSwinPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top. - * - * **Example:** Step-by-step Document Parsing. - * - * ```javascript - * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers'; - * - * // Choose model to use - * const model_id = 'Xenova/donut-base-finetuned-cord-v2'; - * - * // Prepare image inputs - * const processor = await AutoProcessor.from_pretrained(model_id); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/receipt.png'; - * const image = await RawImage.read(url); - * const image_inputs = await processor(image); - * - * // Prepare decoder inputs - * const tokenizer = await AutoTokenizer.from_pretrained(model_id); - * const task_prompt = ''; - * const decoder_input_ids = tokenizer(task_prompt, { - * add_special_tokens: false, - * }).input_ids; - * - * // Create the model - * const model = await AutoModelForVision2Seq.from_pretrained(model_id); - * - * // Run inference - * const output = await model.generate(image_inputs.pixel_values, { - * decoder_input_ids, - * max_length: model.config.decoder.max_position_embeddings, - * }); - * - * // Decode output - * const decoded = tokenizer.batch_decode(output)[0]; - * // CINNAMON SUGAR 17,000 1 x 17,000 17,000 17,000 20,000 3,000 - * ``` - * - * **Example:** Step-by-step Document Visual Question Answering (DocVQA) - * - * ```javascript - * import { AutoProcessor, AutoTokenizer, AutoModelForVision2Seq, RawImage } from '@huggingface/transformers'; - * - * // Choose model to use - * const model_id = 'Xenova/donut-base-finetuned-docvqa'; - * - * // Prepare image inputs - * const processor = await AutoProcessor.from_pretrained(model_id); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png'; - * const image = await RawImage.read(url); - * const image_inputs = await processor(image); - * - * // Prepare decoder inputs - * const tokenizer = await AutoTokenizer.from_pretrained(model_id); - * const question = 'What is the invoice number?'; - * const task_prompt = `${question}`; - * const decoder_input_ids = tokenizer(task_prompt, { - * add_special_tokens: false, - * }).input_ids; - * - * // Create the model - * const model = await AutoModelForVision2Seq.from_pretrained(model_id); - * - * // Run inference - * const output = await model.generate(image_inputs.pixel_values, { - * decoder_input_ids, - * max_length: model.config.decoder.max_position_embeddings, - * }); - * - * // Decode output - * const decoded = tokenizer.batch_decode(output)[0]; - * // What is the invoice number? us-001 - * ``` - */ -class DonutSwinModel extends DonutSwinPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class ConvNextPreTrainedModel extends PreTrainedModel { } - -/** - * The bare ConvNext model outputting raw features without any specific head on top. - */ -class ConvNextModel extends ConvNextPreTrainedModel { } - -/** - * ConvNext Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. - */ -class ConvNextForImageClassification extends ConvNextPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); +function isPowerOfTwo(number) { + return number > 0 && (number & number - 1) === 0; +} +var P2FFT = class { + /** + * @param {number} size The size of the input array. Must be a power of two larger than 1. + * @throws {Error} FFT size must be a power of two larger than 1. + */ + constructor(size) { + this.size = size | 0; + if (this.size <= 1 || !isPowerOfTwo(this.size)) + throw new Error("FFT size must be a power of two larger than 1"); + this._csize = size << 1; + this.table = new Float64Array(this.size * 2); + for (let i = 0; i < this.table.length; i += 2) { + const angle = Math.PI * i / this.size; + this.table[i] = Math.cos(angle); + this.table[i + 1] = -Math.sin(angle); + } + let power = 0; + for (let t = 1; this.size > t; t <<= 1) ++power; + this._width = power % 2 === 0 ? power - 1 : power; + this._bitrev = new Int32Array(1 << this._width); + for (let j2 = 0; j2 < this._bitrev.length; ++j2) { + this._bitrev[j2] = 0; + for (let shift = 0; shift < this._width; shift += 2) { + const revShift = this._width - shift - 2; + this._bitrev[j2] |= (j2 >>> shift & 3) << revShift; + } + } + } + /** + * Create a complex number array with size `2 * size` + * + * @returns {Float64Array} A complex number array with size `2 * size` + */ + createComplexArray() { + return new Float64Array(this._csize); + } + /** + * Converts a complex number representation stored in a Float64Array to an array of real numbers. + * + * @param {Float64Array} complex The complex number representation to be converted. + * @param {number[]} [storage] An optional array to store the result in. + * @returns {number[]} An array of real numbers representing the input complex number representation. + */ + fromComplexArray(complex, storage) { + const res = storage || new Array(complex.length >>> 1); + for (let i = 0; i < complex.length; i += 2) res[i >>> 1] = complex[i]; + return res; + } + /** + * Convert a real-valued input array to a complex-valued output array. + * @param {Float64Array} input The real-valued input array. + * @param {Float64Array} [storage] Optional buffer to store the output array. + * @returns {Float64Array} The complex-valued output array. + */ + toComplexArray(input, storage) { + const res = storage || this.createComplexArray(); + for (let i = 0; i < res.length; i += 2) { + res[i] = input[i >>> 1]; + res[i + 1] = 0; + } + return res; + } + /** + * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. + * + * @param {Float64Array} out The output buffer to store the result. + * @param {Float64Array} data The input data to transform. + * + * @throws {Error} Input and output buffers must be different. + * + * @returns {void} + */ + transform(out, data) { + if (out === data) throw new Error("Input and output buffers must be different"); + this._transform4( + out, + data, + 1 + /* DONE */ + ); + } + /** + * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. + * The input buffer must contain real values only, while the output buffer will contain complex values. The input and + * output buffers must be different. + * + * @param {Float64Array} out The output buffer. + * @param {Float64Array} data The input buffer containing real values. + * + * @throws {Error} If the input and output buffers are the same. + */ + realTransform(out, data) { + if (out === data) throw new Error("Input and output buffers must be different"); + this._realTransform4( + out, + data, + 1 + /* DONE */ + ); + } + /** + * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. + * The `out` array must be a different buffer than the `data` array. The `out` array will contain the + * result of the transformation. The `data` array will not be modified. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input data to transform. + * @throws {Error} If `out` and `data` refer to the same buffer. + * @returns {void} + */ + inverseTransform(out, data) { + if (out === data) throw new Error("Input and output buffers must be different"); + this._transform4( + out, + data, + -1 + /* DONE */ + ); + for (let i = 0; i < out.length; ++i) out[i] /= this.size; + } + /** + * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} out The output buffer for the transformed data. + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {number} inv A scaling factor to apply to the transform. + * @returns {void} + */ + _transform4(out, data, inv) { + const size = this._csize; + const width = this._width; + let step = 1 << width; + let len2 = size / step << 1; + let outOff; + let t; + const bitrev = this._bitrev; + if (len2 === 4) { + for (outOff = 0, t = 0; outOff < size; outOff += len2, ++t) { + const off = bitrev[t]; + this._singleTransform2(data, out, outOff, off, step); + } + } else { + for (outOff = 0, t = 0; outOff < size; outOff += len2, ++t) { + const off = bitrev[t]; + this._singleTransform4(data, out, outOff, off, step, inv); + } } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class ConvNextV2PreTrainedModel extends PreTrainedModel { } - -/** - * The bare ConvNextV2 model outputting raw features without any specific head on top. - */ -class ConvNextV2Model extends ConvNextV2PreTrainedModel { } - -/** - * ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. - */ -class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + const table = this.table; + for (step >>= 2; step >= 2; step >>= 2) { + len2 = size / step << 1; + const quarterLen = len2 >>> 2; + for (outOff = 0; outOff < size; outOff += len2) { + const limit = outOff + quarterLen - 1; + for (let i = outOff, k = 0; i < limit; i += 2, k += step) { + const A = i; + const B = A + quarterLen; + const C = B + quarterLen; + const D = C + quarterLen; + const Ar = out[A]; + const Ai = out[A + 1]; + const Br = out[B]; + const Bi = out[B + 1]; + const Cr = out[C]; + const Ci = out[C + 1]; + const Dr = out[D]; + const Di = out[D + 1]; + const tableBr = table[k]; + const tableBi = inv * table[k + 1]; + const MBr = Br * tableBr - Bi * tableBi; + const MBi = Br * tableBi + Bi * tableBr; + const tableCr = table[2 * k]; + const tableCi = inv * table[2 * k + 1]; + const MCr = Cr * tableCr - Ci * tableCi; + const MCi = Cr * tableCi + Ci * tableCr; + const tableDr = table[3 * k]; + const tableDi = inv * table[3 * k + 1]; + const MDr = Dr * tableDr - Di * tableDi; + const MDi = Dr * tableDi + Di * tableDr; + const T0r = Ar + MCr; + const T0i = Ai + MCi; + const T1r = Ar - MCr; + const T1i = Ai - MCi; + const T2r = MBr + MDr; + const T2i = MBi + MDi; + const T3r = inv * (MBr - MDr); + const T3i = inv * (MBi - MDi); + out[A] = T0r + T2r; + out[A + 1] = T0i + T2i; + out[B] = T1r + T3i; + out[B + 1] = T1i - T3r; + out[C] = T0r - T2r; + out[C + 1] = T0i - T2i; + out[D] = T1r - T3i; + out[D + 1] = T1i + T3r; + } + } } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Dinov2PreTrainedModel extends PreTrainedModel { } - -/** - * The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top. - */ -class Dinov2Model extends Dinov2PreTrainedModel { } - -/** - * Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. - */ -class Dinov2ForImageClassification extends Dinov2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + } + /** + * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. + * + * @param {Float64Array} data The input buffer of data to be transformed. + * @param {Float64Array} out The output buffer for the transformed data. + * @param {number} outOff The offset at which to write the output data. + * @param {number} off The offset at which to begin reading the input data. + * @param {number} step The step size for indexing the input data. + * @returns {void} + */ + _singleTransform2(data, out, outOff, off, step) { + const evenR = data[off]; + const evenI = data[off + 1]; + const oddR = data[off + step]; + const oddI = data[off + step + 1]; + out[outOff] = evenR + oddR; + out[outOff + 1] = evenI + oddI; + out[outOff + 2] = evenR - oddR; + out[outOff + 3] = evenI - oddI; + } + /** + * Performs radix-4 transformation on input data of length 8 + * + * @param {Float64Array} data Input data array of length 8 + * @param {Float64Array} out Output data array of length 8 + * @param {number} outOff Index of output array to start writing from + * @param {number} off Index of input array to start reading from + * @param {number} step Step size between elements in input array + * @param {number} inv Scaling factor for inverse transform + * + * @returns {void} + */ + _singleTransform4(data, out, outOff, off, step, inv) { + const step2 = step * 2; + const step3 = step * 3; + const Ar = data[off]; + const Ai = data[off + 1]; + const Br = data[off + step]; + const Bi = data[off + step + 1]; + const Cr = data[off + step2]; + const Ci = data[off + step2 + 1]; + const Dr = data[off + step3]; + const Di = data[off + step3 + 1]; + const T0r = Ar + Cr; + const T0i = Ai + Ci; + const T1r = Ar - Cr; + const T1i = Ai - Ci; + const T2r = Br + Dr; + const T2i = Bi + Di; + const T3r = inv * (Br - Dr); + const T3i = inv * (Bi - Di); + out[outOff] = T0r + T2r; + out[outOff + 1] = T0i + T2i; + out[outOff + 2] = T1r + T3i; + out[outOff + 3] = T1i - T3r; + out[outOff + 4] = T0r - T2r; + out[outOff + 5] = T0i - T2i; + out[outOff + 6] = T1r - T3i; + out[outOff + 7] = T1i + T3r; + } + /** + * Real input radix-4 implementation + * @param {Float64Array} out Output array for the transformed data + * @param {Float64Array} data Input array of real data to be transformed + * @param {number} inv The scale factor used to normalize the inverse transform + */ + _realTransform4(out, data, inv) { + const size = this._csize; + const width = this._width; + let step = 1 << width; + let len2 = size / step << 1; + let outOff; + let t; + const bitrev = this._bitrev; + if (len2 === 4) { + for (outOff = 0, t = 0; outOff < size; outOff += len2, ++t) { + const off = bitrev[t]; + this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1); + } + } else { + for (outOff = 0, t = 0; outOff < size; outOff += len2, ++t) { + const off = bitrev[t]; + this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv); + } } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Dinov2WithRegistersPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Dinov2WithRegisters Model transformer outputting raw hidden-states without any specific head on top. - */ -class Dinov2WithRegistersModel extends Dinov2WithRegistersPreTrainedModel { } - -/** - * Dinov2WithRegisters Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet. - */ -class Dinov2WithRegistersForImageClassification extends Dinov2WithRegistersPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + const table = this.table; + for (step >>= 2; step >= 2; step >>= 2) { + len2 = size / step << 1; + const halfLen = len2 >>> 1; + const quarterLen = halfLen >>> 1; + const hquarterLen = quarterLen >>> 1; + for (outOff = 0; outOff < size; outOff += len2) { + for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) { + const A = outOff + i; + const B = A + quarterLen; + const C = B + quarterLen; + const D = C + quarterLen; + const Ar = out[A]; + const Ai = out[A + 1]; + const Br = out[B]; + const Bi = out[B + 1]; + const Cr = out[C]; + const Ci = out[C + 1]; + const Dr = out[D]; + const Di = out[D + 1]; + const MAr = Ar; + const MAi = Ai; + const tableBr = table[k]; + const tableBi = inv * table[k + 1]; + const MBr = Br * tableBr - Bi * tableBi; + const MBi = Br * tableBi + Bi * tableBr; + const tableCr = table[2 * k]; + const tableCi = inv * table[2 * k + 1]; + const MCr = Cr * tableCr - Ci * tableCi; + const MCi = Cr * tableCi + Ci * tableCr; + const tableDr = table[3 * k]; + const tableDi = inv * table[3 * k + 1]; + const MDr = Dr * tableDr - Di * tableDi; + const MDi = Dr * tableDi + Di * tableDr; + const T0r = MAr + MCr; + const T0i = MAi + MCi; + const T1r = MAr - MCr; + const T1i = MAi - MCi; + const T2r = MBr + MDr; + const T2i = MBi + MDi; + const T3r = inv * (MBr - MDr); + const T3i = inv * (MBi - MDi); + out[A] = T0r + T2r; + out[A + 1] = T0i + T2i; + out[B] = T1r + T3i; + out[B + 1] = T1i - T3r; + if (i === 0) { + out[C] = T0r - T2r; + out[C + 1] = T0i - T2i; + continue; + } + if (i === hquarterLen) continue; + const SA = outOff + quarterLen - i; + const SB = outOff + halfLen - i; + out[SA] = T1r - inv * T3i; + out[SA + 1] = -T1i - inv * T3r; + out[SB] = T0r - inv * T2r; + out[SB + 1] = -T0i + inv * T2i; + } + } } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DINOv3ViTPreTrainedModel extends PreTrainedModel { } -class DINOv3ViTModel extends DINOv3ViTPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class DINOv3ConvNextPreTrainedModel extends PreTrainedModel { } -class DINOv3ConvNextModel extends DINOv3ConvNextPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class GroundingDinoPreTrainedModel extends PreTrainedModel { } -class GroundingDinoForObjectDetection extends GroundingDinoPreTrainedModel { } - -////////////////////////////////////////////////// -class YolosPreTrainedModel extends PreTrainedModel { } -class YolosModel extends YolosPreTrainedModel { } -class YolosForObjectDetection extends YolosPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new YolosObjectDetectionOutput(await super._call(model_inputs)); + const half = size >>> 1; + for (let i = 2; i < half; i += 2) { + out[size - i] = out[i]; + out[size - i + 1] = -out[i + 1]; } -} - -class YolosObjectDetectionOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification logits (including no-object) for all queries. - * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). - * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). - */ - constructor({ logits, pred_boxes }) { - super(); - this.logits = logits; - this.pred_boxes = pred_boxes; - } -} -////////////////////////////////////////////////// - - - - -////////////////////////////////////////////////// -class SamPreTrainedModel extends PreTrainedModel { } - -/** - * Segment Anything Model (SAM) for generating segmentation masks, given an input image - * and optional 2D location and bounding boxes. - * - * **Example:** Perform mask generation w/ `Xenova/sam-vit-base`. - * ```javascript - * import { SamModel, AutoProcessor, RawImage } from '@huggingface/transformers'; - * - * const model = await SamModel.from_pretrained('Xenova/sam-vit-base'); - * const processor = await AutoProcessor.from_pretrained('Xenova/sam-vit-base'); - * - * const img_url = 'https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'; - * const raw_image = await RawImage.read(img_url); - * const input_points = [[[450, 600]]] // 2D localization of a window - * - * const inputs = await processor(raw_image, { input_points }); - * const outputs = await model(inputs); - * - * const masks = await processor.post_process_masks(outputs.pred_masks, inputs.original_sizes, inputs.reshaped_input_sizes); - * // [ - * // Tensor { - * // dims: [ 1, 3, 1764, 2646 ], - * // type: 'bool', - * // data: Uint8Array(14002632) [ ... ], - * // size: 14002632 - * // } - * // ] - * const scores = outputs.iou_scores; - * // Tensor { - * // dims: [ 1, 1, 3 ], - * // type: 'float32', - * // data: Float32Array(3) [ - * // 0.8892380595207214, - * // 0.9311248064041138, - * // 0.983696699142456 - * // ], - * // size: 3 - * // } - * ``` - */ -class SamModel extends SamPreTrainedModel { - - /** - * Compute image embeddings and positional image embeddings, given the pixel values of an image. - * @param {Object} model_inputs Object containing the model inputs. - * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`. - * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings. - */ - async get_image_embeddings({ pixel_values }) { - // in: - // - pixel_values: tensor.float32[batch_size,3,1024,1024] - // - // out: - // - image_embeddings: tensor.float32[batch_size,256,64,64] - // - image_positional_embeddings: tensor.float32[batch_size,256,64,64] - return await encoderForward(this, { pixel_values }) + } + /** + * Performs a single real input radix-2 transformation on the provided data + * + * @param {Float64Array} data The input data array + * @param {Float64Array} out The output data array + * @param {number} outOff The output offset + * @param {number} off The input offset + * @param {number} step The step + * + * @returns {void} + */ + _singleRealTransform2(data, out, outOff, off, step) { + const evenR = data[off]; + const oddR = data[off + step]; + out[outOff] = evenR + oddR; + out[outOff + 1] = 0; + out[outOff + 2] = evenR - oddR; + out[outOff + 3] = 0; + } + /** + * Computes a single real-valued transform using radix-4 algorithm. + * This method is only called for len=8. + * + * @param {Float64Array} data The input data array. + * @param {Float64Array} out The output data array. + * @param {number} outOff The offset into the output array. + * @param {number} off The offset into the input array. + * @param {number} step The step size for the input array. + * @param {number} inv The value of inverse. + */ + _singleRealTransform4(data, out, outOff, off, step, inv) { + const step2 = step * 2; + const step3 = step * 3; + const Ar = data[off]; + const Br = data[off + step]; + const Cr = data[off + step2]; + const Dr = data[off + step3]; + const T0r = Ar + Cr; + const T1r = Ar - Cr; + const T2r = Br + Dr; + const T3r = inv * (Br - Dr); + out[outOff] = T0r + T2r; + out[outOff + 1] = 0; + out[outOff + 2] = T1r; + out[outOff + 3] = -T3r; + out[outOff + 4] = T0r - T2r; + out[outOff + 5] = 0; + out[outOff + 6] = T1r; + out[outOff + 7] = T3r; + } +}; +var NP2FFT = class { + /** + * Constructs a new NP2FFT object. + * @param {number} fft_length The length of the FFT + */ + constructor(fft_length) { + const a = 2 * (fft_length - 1); + const b = 2 * (2 * fft_length - 1); + const nextP2 = 2 ** Math.ceil(Math.log2(b)); + this.bufferSize = nextP2; + this._a = a; + const chirp = new Float64Array(b); + const ichirp = new Float64Array(nextP2); + this._chirpBuffer = new Float64Array(nextP2); + this._buffer1 = new Float64Array(nextP2); + this._buffer2 = new Float64Array(nextP2); + this._outBuffer1 = new Float64Array(nextP2); + this._outBuffer2 = new Float64Array(nextP2); + const theta = -2 * Math.PI / fft_length; + const baseR = Math.cos(theta); + const baseI = Math.sin(theta); + for (let i = 0; i < b >> 1; ++i) { + const e = (i + 1 - fft_length) ** 2 / 2; + const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e; + const result_arg = e * Math.atan2(baseI, baseR); + const i2 = 2 * i; + chirp[i2] = result_mod * Math.cos(result_arg); + chirp[i2 + 1] = result_mod * Math.sin(result_arg); + ichirp[i2] = chirp[i2]; + ichirp[i2 + 1] = -chirp[i2 + 1]; + } + this._slicedChirpBuffer = chirp.subarray(a, b); + this._f = new P2FFT(nextP2 >> 1); + this._f.transform(this._chirpBuffer, ichirp); + } + _transform(output, input, real) { + const ib1 = this._buffer1; + const ib2 = this._buffer2; + const ob2 = this._outBuffer1; + const ob3 = this._outBuffer2; + const cb = this._chirpBuffer; + const sb = this._slicedChirpBuffer; + const a = this._a; + if (real) { + for (let j2 = 0; j2 < sb.length; j2 += 2) { + const j22 = j2 + 1; + const j3 = j2 >> 1; + const a_real = input[j3]; + ib1[j2] = a_real * sb[j2]; + ib1[j22] = a_real * sb[j22]; + } + } else { + for (let j2 = 0; j2 < sb.length; j2 += 2) { + const j22 = j2 + 1; + ib1[j2] = input[j2] * sb[j2] - input[j22] * sb[j22]; + ib1[j22] = input[j2] * sb[j22] + input[j22] * sb[j2]; + } } - - /** - * @typedef {Object} SamModelInputs Object containing the model inputs. - * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. - * These can be obtained using a `SamProcessor`. - * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`. - * This is used by the prompt encoder to encode the prompt. - * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. - * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: - * - `1`: the point is a point that contains the object of interest - * - `0`: the point is a point that does not contain the object of interest - * - `-1`: the point corresponds to the background - * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder - * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`. - * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder. - * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder. - */ - - /** - * @param {SamModelInputs} model_inputs Object containing the model inputs. - * @returns {Promise} The output of the model. - */ - async forward(model_inputs) { - if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) { - // Compute the image embeddings if they are missing - model_inputs = { - ...model_inputs, - ...(await this.get_image_embeddings(model_inputs)) - } - } - - if (!model_inputs.input_labels && model_inputs.input_points) { - // Set default input labels if they are missing - const shape = model_inputs.input_points.dims.slice(0, -1); - const numElements = shape.reduce((a, b) => a * b, 1); - model_inputs.input_labels = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - 'int64', - new BigInt64Array(numElements).fill(1n), - shape - ); - } - - const decoder_inputs = { - image_embeddings: model_inputs.image_embeddings, - image_positional_embeddings: model_inputs.image_positional_embeddings, - }; - if (model_inputs.input_points) { - decoder_inputs.input_points = model_inputs.input_points; - } - if (model_inputs.input_labels) { - decoder_inputs.input_labels = model_inputs.input_labels; - } - if (model_inputs.input_boxes) { - decoder_inputs.input_boxes = model_inputs.input_boxes; - } - - // Returns: - // - iou_scores: tensor.float32[batch_size,point_batch_size,3] - // - pred_masks: tensor.float32[batch_size,point_batch_size,3,256,256] - return await sessionRun(this.sessions['prompt_encoder_mask_decoder'], decoder_inputs); + this._f.transform(ob2, ib1); + for (let j2 = 0; j2 < cb.length; j2 += 2) { + const j22 = j2 + 1; + ib2[j2] = ob2[j2] * cb[j2] - ob2[j22] * cb[j22]; + ib2[j22] = ob2[j2] * cb[j22] + ob2[j22] * cb[j2]; + } + this._f.inverseTransform(ob3, ib2); + for (let j2 = 0; j2 < ob3.length; j2 += 2) { + const a_real = ob3[j2 + a]; + const a_imag = ob3[j2 + a + 1]; + const b_real = sb[j2]; + const b_imag = sb[j2 + 1]; + output[j2] = a_real * b_real - a_imag * b_imag; + output[j2 + 1] = a_real * b_imag + a_imag * b_real; } - - /** - * Runs the model with the provided inputs - * @param {Object} model_inputs Model inputs - * @returns {Promise} Object containing segmentation outputs - */ - async _call(model_inputs) { - return new SamImageSegmentationOutput(await super._call(model_inputs)); + } + transform(output, input) { + this._transform(output, input, false); + } + realTransform(output, input) { + this._transform(output, input, true); + } +}; +var FFT = class { + constructor(fft_length) { + this.fft_length = fft_length; + this.isPowerOfTwo = isPowerOfTwo(fft_length); + if (this.isPowerOfTwo) { + this.fft = new P2FFT(fft_length); + this.outputBufferSize = 2 * fft_length; + } else { + this.fft = new NP2FFT(fft_length); + this.outputBufferSize = this.fft.bufferSize; } -} - - -/** - * Base class for Segment-Anything model's output. - */ -class SamImageSegmentationOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.iou_scores The output logits of the model. - * @param {Tensor} output.pred_masks Predicted boxes. - */ - constructor({ iou_scores, pred_masks }) { - super(); - this.iou_scores = iou_scores; - this.pred_masks = pred_masks; - } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// MarianMT models -class MarianPreTrainedModel extends PreTrainedModel { }; - -class MarianModel extends MarianPreTrainedModel { } - -class MarianMTModel extends MarianPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// M2M100 models -class M2M100PreTrainedModel extends PreTrainedModel { }; - -class M2M100Model extends M2M100PreTrainedModel { } - -class M2M100ForConditionalGeneration extends M2M100PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Wav2Vec2 models -class Wav2Vec2PreTrainedModel extends PreTrainedModel { }; - -/** - * The bare Wav2Vec2 Model transformer outputting raw hidden-states without any specific head on top. - * - * **Example:** Load and run a `Wav2Vec2Model` for feature extraction. - * - * ```javascript - * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers'; - * - * // Read and preprocess audio - * const processor = await AutoProcessor.from_pretrained('Xenova/mms-300m'); - * const audio = await read_audio('https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac', 16000); - * const inputs = await processor(audio); - * - * // Run model with inputs - * const model = await AutoModel.from_pretrained('Xenova/mms-300m'); - * const output = await model(inputs); - * // { - * // last_hidden_state: Tensor { - * // dims: [ 1, 1144, 1024 ], - * // type: 'float32', - * // data: Float32Array(1171456) [ ... ], - * // size: 1171456 - * // } - * // } - * ``` - */ -class Wav2Vec2Model extends Wav2Vec2PreTrainedModel { } - -class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); + } + realTransform(out, input) { + this.fft.realTransform(out, input); + } + transform(out, input) { + this.fft.transform(out, input); + } +}; +function medianFilter(data, windowSize) { + if (windowSize % 2 === 0 || windowSize <= 0) { + throw new Error("Window size must be a positive odd number"); + } + const outputArray = new data.constructor(data.length); + const buffer = new data.constructor(windowSize); + const halfWindowSize = Math.floor(windowSize / 2); + for (let i = 0; i < data.length; ++i) { + let valuesIndex = 0; + for (let j2 = -halfWindowSize; j2 <= halfWindowSize; ++j2) { + let index = i + j2; + if (index < 0) { + index = Math.abs(index); + } else if (index >= data.length) { + index = 2 * (data.length - 1) - index; + } + buffer[valuesIndex++] = data[index]; } + buffer.sort(); + outputArray[i] = buffer[halfWindowSize]; + } + return outputArray; } - -class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } +function round(num, decimals) { + const pow = Math.pow(10, decimals); + return Math.round(num * pow) / pow; } - -/** - * Wav2Vec2 Model with a frame classification head on top for tasks like Speaker Diarization. - */ -class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// PyAnnote models -class PyAnnotePreTrainedModel extends PreTrainedModel { }; - -/** - * The bare PyAnnote Model transformer outputting raw hidden-states without any specific head on top. - */ -class PyAnnoteModel extends PyAnnotePreTrainedModel { } - -/** - * PyAnnote Model with a frame classification head on top for tasks like Speaker Diarization. - * - * **Example:** Load and run a `PyAnnoteForAudioFrameClassification` for speaker diarization. - * - * ```javascript - * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers'; - * - * // Load model and processor - * const model_id = 'onnx-community/pyannote-segmentation-3.0'; - * const model = await AutoModelForAudioFrameClassification.from_pretrained(model_id); - * const processor = await AutoProcessor.from_pretrained(model_id); - * - * // Read and preprocess audio - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/mlk.wav'; - * const audio = await read_audio(url, processor.feature_extractor.config.sampling_rate); - * const inputs = await processor(audio); - * - * // Run model with inputs - * const { logits } = await model(inputs); - * // { - * // logits: Tensor { - * // dims: [ 1, 767, 7 ], // [batch_size, num_frames, num_classes] - * // type: 'float32', - * // data: Float32Array(5369) [ ... ], - * // size: 5369 - * // } - * // } - * - * const result = processor.post_process_speaker_diarization(logits, audio.length); - * // [ - * // [ - * // { id: 0, start: 0, end: 1.0512535626298245, confidence: 0.8220156481664611 }, - * // { id: 2, start: 1.0512535626298245, end: 2.3398869619825127, confidence: 0.9008811707860472 }, - * // ... - * // ] - * // ] - * - * // Display result - * console.table(result[0], ['start', 'end', 'id', 'confidence']); - * // ┌─────────┬────────────────────┬────────────────────┬────┬─────────────────────┐ - * // │ (index) │ start │ end │ id │ confidence │ - * // ├─────────┼────────────────────┼────────────────────┼────┼─────────────────────┤ - * // │ 0 │ 0 │ 1.0512535626298245 │ 0 │ 0.8220156481664611 │ - * // │ 1 │ 1.0512535626298245 │ 2.3398869619825127 │ 2 │ 0.9008811707860472 │ - * // │ 2 │ 2.3398869619825127 │ 3.5946089560890773 │ 0 │ 0.7521651315796233 │ - * // │ 3 │ 3.5946089560890773 │ 4.578039708226655 │ 2 │ 0.8491978128022479 │ - * // │ 4 │ 4.578039708226655 │ 4.594995410849717 │ 0 │ 0.2935352600416393 │ - * // │ 5 │ 4.594995410849717 │ 6.121008646925269 │ 3 │ 0.6788051309866024 │ - * // │ 6 │ 6.121008646925269 │ 6.256654267909762 │ 0 │ 0.37125512393851134 │ - * // │ 7 │ 6.256654267909762 │ 8.630452635138397 │ 2 │ 0.7467035186353542 │ - * // │ 8 │ 8.630452635138397 │ 10.088643060721703 │ 0 │ 0.7689364814666032 │ - * // │ 9 │ 10.088643060721703 │ 12.58113134631177 │ 2 │ 0.9123324509131324 │ - * // │ 10 │ 12.58113134631177 │ 13.005023911888312 │ 0 │ 0.4828358177572041 │ - * // └─────────┴────────────────────┴────────────────────┴────┴─────────────────────┘ - * ``` - */ -class PyAnnoteForAudioFrameClassification extends PyAnnotePreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } +function bankers_round(x) { + const r = Math.round(x); + const br2 = Math.abs(x) % 1 === 0.5 ? r % 2 === 0 ? r : r - 1 : r; + return br2; } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// WeSpeakerResNet models -class WeSpeakerResNetPreTrainedModel extends PreTrainedModel { }; -class WeSpeakerResNetModel extends WeSpeakerResNetPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// UniSpeech models -class UniSpeechPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare UniSpeech Model transformer outputting raw hidden-states without any specific head on top. - */ -class UniSpeechModel extends UniSpeechPreTrainedModel { } - -/** - * UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). - */ -class UniSpeechForCTC extends UniSpeechPreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); +function dynamic_time_warping(matrix) { + const output_length = matrix.length; + const input_length = matrix[0].length; + const outputShape = [output_length + 1, input_length + 1]; + const cost = Array.from({ length: outputShape[0] }, () => Array(outputShape[1]).fill(Infinity)); + cost[0][0] = 0; + const trace = Array.from({ length: outputShape[0] }, () => Array(outputShape[1]).fill(-1)); + for (let j3 = 1; j3 < outputShape[1]; ++j3) { + for (let i2 = 1; i2 < outputShape[0]; ++i2) { + const c0 = cost[i2 - 1][j3 - 1]; + const c1 = cost[i2 - 1][j3]; + const c2 = cost[i2][j3 - 1]; + let c, t; + if (c0 < c1 && c0 < c2) { + c = c0; + t = 0; + } else if (c1 < c0 && c1 < c2) { + c = c1; + t = 1; + } else { + c = c2; + t = 2; + } + cost[i2][j3] = matrix[i2 - 1][j3 - 1] + c; + trace[i2][j3] = t; } -} - -/** - * UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output). - */ -class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + } + for (let i2 = 0; i2 < outputShape[1]; ++i2) { + trace[0][i2] = 2; + } + for (let i2 = 0; i2 < outputShape[0]; ++i2) { + trace[i2][0] = 1; + } + let i = output_length; + let j2 = input_length; + let text_indices = []; + let time_indices = []; + while (i > 0 || j2 > 0) { + text_indices.push(i - 1); + time_indices.push(j2 - 1); + switch (trace[i][j2]) { + case 0: + --i; + --j2; + break; + case 1: + --i; + break; + case 2: + --j2; + break; + default: + throw new Error( + `Internal error in dynamic time warping. Unexpected trace[${i}, ${j2}]. Please file a bug report.` + ); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// UniSpeechSat models -class UniSpeechSatPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare UniSpeechSat Model transformer outputting raw hidden-states without any specific head on top. - */ -class UniSpeechSatModel extends UniSpeechSatPreTrainedModel { } - -/** - * UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). - */ -class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); + } + text_indices.reverse(); + time_indices.reverse(); + return [text_indices, time_indices]; +} +var uint16_to_float32 = /* @__PURE__ */ (function() { + let float16LUT = null; + return function(u16Array) { + if (!float16LUT) { + float16LUT = new Float32Array(65536); + const buffer = new ArrayBuffer(4); + const u32 = new Uint32Array(buffer); + const f32 = new Float32Array(buffer); + for (let i = 0; i < float16LUT.length; ++i) { + let outBits = 0; + const sign = (i & 32768) << 16; + const exp = (i & 31744) >> 10; + let mantissa = i & 1023; + if (exp === 31) { + outBits = sign | 2139095040 | mantissa << 13; + } else if (exp === 0) { + if (mantissa === 0) { + outBits = sign; + } else { + let renormExp = 113; + while ((mantissa & 1024) === 0) { + mantissa <<= 1; + --renormExp; + } + mantissa &= ~1024; + outBits = sign | renormExp << 23 | mantissa << 13; + } + } else { + outBits = sign | exp + 112 << 23 | mantissa << 13; + } + u32[0] = outBits; + float16LUT[i] = f32[0]; + } } -} - -/** - * UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output). - */ -class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + const length = u16Array.length; + const lut = float16LUT; + const out = new Float32Array(length); + for (let i = 0; i < length; ++i) { + out[i] = lut[u16Array[i]]; } -} + return out; + }; +})(); -/** - * UniSpeechSat Model with a frame classification head on top for tasks like Speaker Diarization. - */ -class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); +// ignore-modules:./onnx-node.js +var onnx_node_default = {}; + +// ../../node_modules/.pnpm/onnxruntime-web@1.31.0-dev.20260914-8d85527a0/node_modules/onnxruntime-web/dist/ort.webgpu.bundle.min.mjs +var ort_webgpu_bundle_min_exports = {}; +__export(ort_webgpu_bundle_min_exports, { + InferenceSession: () => bc, + TRACE: () => Qa, + TRACE_EVENT_BEGIN: () => $e, + TRACE_EVENT_END: () => ze, + TRACE_FUNC_BEGIN: () => ot, + TRACE_FUNC_END: () => at, + Tensor: () => Le, + default: () => $l, + env: () => ee, + registerBackend: () => rt +}); +var Jr = Object.defineProperty; +var dc = Object.getOwnPropertyDescriptor; +var lc = Object.getOwnPropertyNames; +var pc = Object.prototype.hasOwnProperty; +var Xr = ((a) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(a, { get: (r, s) => (typeof __require < "u" ? __require : r)[s] }) : a)(function(a) { + if (typeof __require < "u") return __require.apply(this, arguments); + throw Error('Dynamic require of "' + a + '" is not supported'); +}); +var G = (a, r, s) => () => { + if (s) throw s[0]; + try { + return a && (r = a(a = 0)), r; + } catch (f) { + throw s = [f], f; + } +}; +var At = (a, r) => { + for (var s in r) Jr(a, s, { get: r[s], enumerable: true }); +}; +var mc = (a, r, s, f) => { + if (r && typeof r == "object" || typeof r == "function") for (let i of lc(r)) !pc.call(a, i) && i !== s && Jr(a, i, { get: () => r[i], enumerable: !(f = dc(r, i)) || f.enumerable }); + return a; +}; +var Ht = (a) => mc(Jr({}, "__esModule", { value: true }), a); +var qt; +var tt; +var rt; +var hc; +var Da; +var Zr = G(() => { + "use strict"; + qt = /* @__PURE__ */ new Map(), tt = [], rt = (a, r, s) => { + if (r && typeof r.init == "function" && typeof r.createInferenceSessionHandler == "function") { + let f = qt.get(a); + if (f === void 0) qt.set(a, { backend: r, priority: s }); + else { + if (f.priority > s) return; + if (f.priority === s && f.backend !== r) throw new Error(`cannot register backend "${a}" using priority ${s}`); + } + if (s >= 0) { + let i = tt.indexOf(a); + i !== -1 && tt.splice(i, 1); + for (let p = 0; p < tt.length; p++) if (qt.get(tt[p]).priority <= s) { + tt.splice(p, 0, a); + return; + } + tt.push(a); + } + return; } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Wav2Vec2Bert models -class Wav2Vec2BertPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare Wav2Vec2Bert Model transformer outputting raw hidden-states without any specific head on top. - */ -class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel { } - -/** - * Wav2Vec2Bert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). - */ -class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); + throw new TypeError("not a valid backend"); + }, hc = async (a) => { + let r = qt.get(a); + if (!r) return "backend not found."; + if (r.initialized) return r.backend; + if (r.aborted) return r.error; + { + let s = !!r.initPromise; + try { + return s || (r.initPromise = r.backend.init(a)), await r.initPromise, r.initialized = true, r.backend; + } catch (f) { + return s || (r.error = `${f}`, r.aborted = true), r.error; + } finally { + delete r.initPromise; + } } -} - -/** - * Wav2Vec2Bert Model with a sequence classification head on top (a linear layer over the pooled output). - */ -class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Hubert models -class HubertPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Hubert Model transformer outputting raw hidden-states without any specific head on top. - * - * **Example:** Load and run a `HubertModel` for feature extraction. - * - * ```javascript - * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers'; - * - * // Read and preprocess audio - * const processor = await AutoProcessor.from_pretrained('Xenova/hubert-base-ls960'); - * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000); - * const inputs = await processor(audio); - * - * // Load and run model with inputs - * const model = await AutoModel.from_pretrained('Xenova/hubert-base-ls960'); - * const output = await model(inputs); - * // { - * // last_hidden_state: Tensor { - * // dims: [ 1, 549, 768 ], - * // type: 'float32', - * // data: Float32Array(421632) [0.0682469978928566, 0.08104046434164047, -0.4975186586380005, ...], - * // size: 421632 - * // } - * // } - * ``` - */ -class HubertModel extends Wav2Vec2PreTrainedModel { } - -/** - * Hubert Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). - */ -class HubertForCTC extends Wav2Vec2PreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); + }, Da = async (a) => { + let r = a.executionProviders || [], s = r.map((g) => typeof g == "string" ? g : g.name), f = s.length === 0 ? tt : s, i, p = [], l = /* @__PURE__ */ new Set(); + for (let g of f) { + let w = await hc(g); + typeof w == "string" ? p.push({ name: g, err: w }) : (i || (i = w), i === w && l.add(g)); } -} - -/** - * Hubert Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like SUPERB Keyword Spotting. - */ -class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// WavLM models -/** - * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. - */ -class WavLMPreTrainedModel extends PreTrainedModel { }; - -/** - * The bare WavLM Model transformer outputting raw hidden-states without any specific head on top. - * - * **Example:** Load and run a `WavLMModel` for feature extraction. - * - * ```javascript - * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers'; - * - * // Read and preprocess audio - * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base'); - * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav', 16000); - * const inputs = await processor(audio); - * - * // Run model with inputs - * const model = await AutoModel.from_pretrained('Xenova/wavlm-base'); - * const output = await model(inputs); - * // { - * // last_hidden_state: Tensor { - * // dims: [ 1, 549, 768 ], - * // type: 'float32', - * // data: Float32Array(421632) [-0.349443256855011, -0.39341306686401367, 0.022836603224277496, ...], - * // size: 421632 - * // } - * // } - * ``` - */ -class WavLMModel extends WavLMPreTrainedModel { } - -/** - * WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC). - */ -class WavLMForCTC extends WavLMPreTrainedModel { - /** - * @param {Object} model_inputs - * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. - * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] - */ - async _call(model_inputs) { - return new CausalLMOutput(await super._call(model_inputs)); + if (!i) throw new Error(`no available backend found. ERR: ${p.map((g) => `[${g.name}] ${g.err}`).join(", ")}`); + for (let { name: g, err: w } of p) s.includes(g) && console.warn(`removing requested execution provider "${g}" from session options because it is not available: ${w}`); + let b = r.filter((g) => l.has(typeof g == "string" ? g : g.name)); + return [i, new Proxy(a, { get: (g, w) => w === "executionProviders" ? b : Reflect.get(g, w) })]; + }; +}); +var Pa = G(() => { + "use strict"; + Zr(); +}); +var Ua; +var _a = G(() => { + "use strict"; + Ua = "1.31.0-dev.20260911-2a43ec07e"; +}); +var Ra; +var ie; +var Kr = G(() => { + "use strict"; + _a(); + Ra = "warning", ie = { wasm: {}, webgl: {}, webgpu: {}, versions: { common: Ua }, set logLevel(a) { + if (a !== void 0) { + if (typeof a != "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(a) === -1) throw new Error(`Unsupported logging level: ${a}`); + Ra = a; + } + }, get logLevel() { + return Ra; + } }; + Object.defineProperty(ie, "logLevel", { enumerable: true }); +}); +var ee; +var Na = G(() => { + "use strict"; + Kr(); + ee = ie; +}); +var Wa; +var ka; +var Fa = G(() => { + "use strict"; + Wa = (a, r) => { + let s = typeof document < "u" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); + s.width = a.dims[3], s.height = a.dims[2]; + let f = s.getContext("2d"); + if (f != null) { + let i, p; + r?.tensorLayout !== void 0 && r.tensorLayout === "NHWC" ? (i = a.dims[2], p = a.dims[3]) : (i = a.dims[3], p = a.dims[2]); + let l = r?.format !== void 0 ? r.format : "RGB", b = r?.norm, g, w; + b === void 0 || b.mean === void 0 ? g = [255, 255, 255, 255] : typeof b.mean == "number" ? g = [b.mean, b.mean, b.mean, b.mean] : (g = [b.mean[0], b.mean[1], b.mean[2], 0], b.mean[3] !== void 0 && (g[3] = b.mean[3])), b === void 0 || b.bias === void 0 ? w = [0, 0, 0, 0] : typeof b.bias == "number" ? w = [b.bias, b.bias, b.bias, b.bias] : (w = [b.bias[0], b.bias[1], b.bias[2], 0], b.bias[3] !== void 0 && (w[3] = b.bias[3])); + let S = p * i, v = 0, T = S, A = S * 2, C = -1; + l === "RGBA" ? (v = 0, T = S, A = S * 2, C = S * 3) : l === "RGB" ? (v = 0, T = S, A = S * 2) : l === "RBG" && (v = 0, A = S, T = S * 2); + for (let _ = 0; _ < p; _++) for (let k = 0; k < i; k++) { + let U = (a.data[v++] - w[0]) * g[0], M = (a.data[T++] - w[1]) * g[1], Y = (a.data[A++] - w[2]) * g[2], O = C === -1 ? 255 : (a.data[C++] - w[3]) * g[3]; + f.fillStyle = "rgba(" + U + "," + M + "," + Y + "," + O + ")", f.fillRect(k, _, 1, 1); + } + if ("toDataURL" in s) return s.toDataURL(); + throw new Error("toDataURL is not supported"); + } else throw new Error("Can not access image data"); + }, ka = (a, r) => { + let s = typeof document < "u" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"), f; + if (s != null) { + let i, p, l; + r?.tensorLayout !== void 0 && r.tensorLayout === "NHWC" ? (i = a.dims[2], p = a.dims[1], l = a.dims[3]) : (i = a.dims[3], p = a.dims[2], l = a.dims[1]); + let b = r !== void 0 && r.format !== void 0 ? r.format : "RGB", g = r?.norm, w, S; + g === void 0 || g.mean === void 0 ? w = [255, 255, 255, 255] : typeof g.mean == "number" ? w = [g.mean, g.mean, g.mean, g.mean] : (w = [g.mean[0], g.mean[1], g.mean[2], 255], g.mean[3] !== void 0 && (w[3] = g.mean[3])), g === void 0 || g.bias === void 0 ? S = [0, 0, 0, 0] : typeof g.bias == "number" ? S = [g.bias, g.bias, g.bias, g.bias] : (S = [g.bias[0], g.bias[1], g.bias[2], 0], g.bias[3] !== void 0 && (S[3] = g.bias[3])); + let v = p * i; + if (r !== void 0 && (r.format !== void 0 && l === 4 && r.format !== "RGBA" || l === 3 && r.format !== "RGB" && r.format !== "BGR")) throw new Error("Tensor format doesn't match input tensor dims"); + let T = 4, A = 0, C = 1, _ = 2, k = 3, U = 0, M = v, Y = v * 2, O = -1; + b === "RGBA" ? (U = 0, M = v, Y = v * 2, O = v * 3) : b === "RGB" ? (U = 0, M = v, Y = v * 2) : b === "RBG" && (U = 0, Y = v, M = v * 2), f = s.createImageData(i, p); + for (let $ = 0; $ < p * i; A += T, C += T, _ += T, k += T, $++) f.data[A] = (a.data[U++] - S[0]) * w[0], f.data[C] = (a.data[M++] - S[1]) * w[1], f.data[_] = (a.data[Y++] - S[2]) * w[2], f.data[k] = O === -1 ? 255 : (a.data[O++] - S[3]) * w[3]; + } else throw new Error("Can not access image data"); + return f; + }; +}); +var Qr; +var Ga; +var $a; +var za; +var Va; +var ja; +var Ha = G(() => { + "use strict"; + Yt(); + Qr = (a, r) => { + if (a === 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: s, width: f } = r, i = r.norm ?? { mean: 255, bias: 0 }, p, l; + typeof i.mean == "number" ? p = [i.mean, i.mean, i.mean, i.mean] : p = [i.mean[0], i.mean[1], i.mean[2], i.mean[3] ?? 255], typeof i.bias == "number" ? l = [i.bias, i.bias, i.bias, i.bias] : l = [i.bias[0], i.bias[1], i.bias[2], i.bias[3] ?? 0]; + let b = r.format !== void 0 ? r.format : "RGBA", g = r.tensorFormat !== void 0 && r.tensorFormat !== void 0 ? r.tensorFormat : "RGB", w = s * f, S = g === "RGBA" ? new Float32Array(w * 4) : new Float32Array(w * 3), v = 4, T = 0, A = 1, C = 2, _ = 3, k = 0, U = w, M = w * 2, Y = -1; + b === "RGB" && (v = 3, T = 0, A = 1, C = 2, _ = -1), g === "RGBA" ? Y = w * 3 : g === "RBG" ? (k = 0, M = w, U = w * 2) : g === "BGR" && (M = 0, U = w, k = w * 2); + for (let $ = 0; $ < w; $++, T += v, C += v, A += v, _ += v) S[k++] = (a[T] + l[0]) / p[0], S[U++] = (a[A] + l[1]) / p[1], S[M++] = (a[C] + l[2]) / p[2], Y !== -1 && _ !== -1 && (S[Y++] = (a[_] + l[3]) / p[3]); + return g === "RGBA" ? new ce("float32", S, [1, 4, s, f]) : new ce("float32", S, [1, 3, s, f]); + }, Ga = async (a, r) => { + let s = typeof HTMLImageElement < "u" && a instanceof HTMLImageElement, f = typeof ImageData < "u" && a instanceof ImageData, i = typeof ImageBitmap < "u" && a instanceof ImageBitmap, p = typeof a == "string", l, b = r ?? {}, g = () => { + if (typeof document < "u") return document.createElement("canvas"); + if (typeof OffscreenCanvas < "u") return new OffscreenCanvas(1, 1); + throw new Error("Canvas is not supported"); + }, w = (S) => typeof HTMLCanvasElement < "u" && S instanceof HTMLCanvasElement || S instanceof OffscreenCanvas ? S.getContext("2d") : null; + if (s) { + let S = g(); + S.width = a.width, S.height = a.height; + let v = w(S); + if (v != null) { + let T = a.height, A = a.width; + if (r !== void 0 && r.resizedHeight !== void 0 && r.resizedWidth !== void 0 && (T = r.resizedHeight, A = r.resizedWidth), r !== void 0) { + if (b = r, r.tensorFormat !== void 0) throw new Error("Image input config format must be RGBA for HTMLImageElement"); + b.tensorFormat = "RGBA", b.height = T, b.width = A; + } else b.tensorFormat = "RGBA", b.height = T, b.width = A; + v.drawImage(a, 0, 0), l = v.getImageData(0, 0, A, T).data; + } else throw new Error("Can not access image data"); + } else if (f) { + let S, v; + if (r !== void 0 && r.resizedWidth !== void 0 && r.resizedHeight !== void 0 ? (S = r.resizedHeight, v = r.resizedWidth) : (S = a.height, v = a.width), r !== void 0 && (b = r), b.format = "RGBA", b.height = S, b.width = v, r !== void 0) { + let T = g(); + T.width = v, T.height = S; + let A = w(T); + if (A != null) A.putImageData(a, 0, 0), l = A.getImageData(0, 0, v, S).data; + else throw new Error("Can not access image data"); + } else l = a.data; + } else if (i) { + if (r === void 0) throw new Error("Please provide image config with format for Imagebitmap"); + let S = g(); + S.width = a.width, S.height = a.height; + let v = w(S); + if (v != null) { + let T = a.height, A = a.width; + return v.drawImage(a, 0, 0, A, T), l = v.getImageData(0, 0, A, T).data, b.height = T, b.width = A, Qr(l, b); + } else throw new Error("Can not access image data"); + } else { + if (p) return new Promise((S, v) => { + let T = g(), A = w(T); + if (!a || !A) return v(); + let C = new Image(); + C.crossOrigin = "Anonymous", C.src = a, C.onload = () => { + T.width = C.width, T.height = C.height, A.drawImage(C, 0, 0, T.width, T.height); + let _ = A.getImageData(0, 0, T.width, T.height); + b.height = T.height, b.width = T.width, S(Qr(_.data, b)); + }; + }); + throw new Error("Input data provided is not supported - aborted tensor creation"); + } + if (l !== void 0) return Qr(l, b); + throw new Error("Input data provided is not supported - aborted tensor creation"); + }, $a = (a, r) => { + let { width: s, height: f, download: i, dispose: p } = r, l = [1, f, s, 4]; + return new ce({ location: "texture", type: "float32", texture: a, dims: l, download: i, dispose: p }); + }, za = (a, r) => { + let { dataType: s, dims: f, download: i, dispose: p } = r; + return new ce({ location: "gpu-buffer", type: s ?? "float32", gpuBuffer: a, dims: f, download: i, dispose: p }); + }, Va = (a, r) => { + let { dataType: s, dims: f, download: i, dispose: p } = r; + return new ce({ location: "ml-tensor", type: s ?? "float32", mlTensor: a, dims: f, download: i, dispose: p }); + }, ja = (a, r, s) => new ce({ location: "cpu-pinned", type: a, data: r, dims: s ?? [r.length] }); +}); +var nt; +var It; +var qa; +var Ya; +var Ja = G(() => { + "use strict"; + nt = /* @__PURE__ */ new Map([["float32", Float32Array], ["uint8", Uint8Array], ["int8", Int8Array], ["uint16", Uint16Array], ["int16", Int16Array], ["int32", Int32Array], ["bool", Uint8Array], ["float64", Float64Array], ["uint32", Uint32Array], ["int4", Uint8Array], ["uint4", Uint8Array]]), It = /* @__PURE__ */ new Map([[Float32Array, "float32"], [Uint8Array, "uint8"], [Int8Array, "int8"], [Uint16Array, "uint16"], [Int16Array, "int16"], [Int32Array, "int32"], [Float64Array, "float64"], [Uint32Array, "uint32"]]), qa = false, Ya = () => { + if (!qa) { + qa = true; + let a = typeof BigInt64Array < "u" && BigInt64Array.from, r = typeof BigUint64Array < "u" && BigUint64Array.from, s = globalThis.Float16Array, f = typeof s < "u" && s.from; + a && (nt.set("int64", BigInt64Array), It.set(BigInt64Array, "int64")), r && (nt.set("uint64", BigUint64Array), It.set(BigUint64Array, "uint64")), f ? (nt.set("float16", s), It.set(s, "float16")) : nt.set("float16", Uint16Array); } -} - -/** - * WavLM Model with a sequence classification head on top (a linear layer over the pooled output). - */ -class WavLMForSequenceClassification extends WavLMPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} - -/** - * WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification. - * - * **Example:** Extract speaker embeddings with `WavLMForXVector`. - * ```javascript - * import { AutoProcessor, AutoModel, read_audio } from '@huggingface/transformers'; - * - * // Read and preprocess audio - * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sv'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; - * const audio = await read_audio(url, 16000); - * const inputs = await processor(audio); - * - * // Run model with inputs - * const model = await AutoModel.from_pretrained('Xenova/wavlm-base-plus-sv'); - * const outputs = await model(inputs); - * // { - * // logits: Tensor { - * // dims: [ 1, 512 ], - * // type: 'float32', - * // data: Float32Array(512) [0.5847219228744507, ...], - * // size: 512 - * // }, - * // embeddings: Tensor { - * // dims: [ 1, 512 ], - * // type: 'float32', - * // data: Float32Array(512) [-0.09079201519489288, ...], - * // size: 512 - * // } - * // } - * ``` - */ -class WavLMForXVector extends WavLMPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits and speaker embeddings. - */ - async _call(model_inputs) { - return new XVectorOutput(await super._call(model_inputs)); - } -} - -/** - * WavLM Model with a frame classification head on top for tasks like Speaker Diarization. - * - * **Example:** Perform speaker diarization with `WavLMForAudioFrameClassification`. - * ```javascript - * import { AutoProcessor, AutoModelForAudioFrameClassification, read_audio } from '@huggingface/transformers'; - * - * // Read and preprocess audio - * const processor = await AutoProcessor.from_pretrained('Xenova/wavlm-base-plus-sd'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; - * const audio = await read_audio(url, 16000); - * const inputs = await processor(audio); - * - * // Run model with inputs - * const model = await AutoModelForAudioFrameClassification.from_pretrained('Xenova/wavlm-base-plus-sd'); - * const { logits } = await model(inputs); - * // { - * // logits: Tensor { - * // dims: [ 1, 549, 2 ], // [batch_size, num_frames, num_speakers] - * // type: 'float32', - * // data: Float32Array(1098) [-3.5301010608673096, ...], - * // size: 1098 - * // } - * // } - * - * const labels = logits[0].sigmoid().tolist().map( - * frames => frames.map(speaker => speaker > 0.5 ? 1 : 0) - * ); - * console.log(labels); // labels is a one-hot array of shape (num_frames, num_speakers) - * // [ - * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], - * // [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], - * // [0, 0], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], - * // ... - * // ] - * ``` - */ -class WavLMForAudioFrameClassification extends WavLMPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} An object containing the model's output logits for sequence classification. - */ - async _call(model_inputs) { - return new TokenClassifierOutput(await super._call(model_inputs)); - } -} - -class StyleTextToSpeech2PreTrainedModel extends PreTrainedModel { } -class StyleTextToSpeech2Model extends StyleTextToSpeech2PreTrainedModel { } - -////////////////////////////////////////////////// -// SpeechT5 models -/** - * An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. - */ -class SpeechT5PreTrainedModel extends PreTrainedModel { }; - -/** - * The bare SpeechT5 Encoder-Decoder Model outputting raw hidden-states without any specific pre- or post-nets. - */ -class SpeechT5Model extends SpeechT5PreTrainedModel { }; - -/** - * SpeechT5 Model with a speech encoder and a text decoder. - * - * **Example:** Generate speech from text with `SpeechT5ForSpeechToText`. - * ```javascript - * import { AutoTokenizer, AutoProcessor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, Tensor } from '@huggingface/transformers'; - * - * // Load the tokenizer and processor - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/speecht5_tts'); - * const processor = await AutoProcessor.from_pretrained('Xenova/speecht5_tts'); - * - * // Load the models - * // NOTE: We use the full-precision versions as they are more accurate - * const model = await SpeechT5ForTextToSpeech.from_pretrained('Xenova/speecht5_tts', { dtype: 'fp32' }); - * const vocoder = await SpeechT5HifiGan.from_pretrained('Xenova/speecht5_hifigan', { dtype: 'fp32' }); - * - * // Load speaker embeddings from URL - * const speaker_embeddings_data = new Float32Array( - * await (await fetch('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin')).arrayBuffer() - * ); - * const speaker_embeddings = new Tensor( - * 'float32', - * speaker_embeddings_data, - * [1, speaker_embeddings_data.length] - * ) - * - * // Run tokenization - * const { input_ids } = tokenizer('Hello, my dog is cute'); - * - * // Generate waveform - * const { waveform } = await model.generate_speech(input_ids, speaker_embeddings, { vocoder }); - * console.log(waveform) - * // Tensor { - * // dims: [ 26112 ], - * // type: 'float32', - * // size: 26112, - * // data: Float32Array(26112) [ -0.00043630177970044315, -0.00018082228780258447, ... ], - * // } - * ``` - */ -class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel { } - -/** - * SpeechT5 Model with a text encoder and a speech decoder. - */ -class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel { - - /** - * @typedef {Object} SpeechOutput - * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape - * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided - * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. - * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape - * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. - */ - - /** - * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. - * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. - * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. - * @param {Object} options Optional parameters for generating speech. - * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. - * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. - * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. - * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. - * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers. - * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. - */ - async generate_speech(input_values, speaker_embeddings, { - threshold = 0.5, - minlenratio = 0.0, - maxlenratio = 20.0, - vocoder = null, - // output_cross_attentions = false, // TODO add - } = {}) { - - const model_inputs = { - input_ids: input_values + }; +}); +var Xa; +var Za; +var Ka = G(() => { + "use strict"; + Yt(); + Xa = (a) => { + let r = 1; + for (let s = 0; s < a.length; s++) { + let f = a[s]; + if (typeof f != "number" || !Number.isSafeInteger(f)) throw new TypeError(`dims[${s}] must be an integer, got: ${f}`); + if (f < 0) throw new RangeError(`dims[${s}] must be a non-negative integer, got: ${f}`); + r *= f; + } + return r; + }, Za = (a, r) => { + switch (a.location) { + case "cpu": + return new ce(a.type, a.data, r); + case "cpu-pinned": + return new ce({ location: "cpu-pinned", data: a.data, type: a.type, dims: r }); + case "texture": + return new ce({ location: "texture", texture: a.texture, type: a.type, dims: r }); + case "gpu-buffer": + return new ce({ location: "gpu-buffer", gpuBuffer: a.gpuBuffer, type: a.type, dims: r }); + case "ml-tensor": + return new ce({ location: "ml-tensor", mlTensor: a.mlTensor, type: a.type, dims: r }); + default: + throw new Error(`tensorReshape: tensor location ${a.location} is not supported`); + } + }; +}); +var ce; +var Yt = G(() => { + "use strict"; + Fa(); + Ha(); + Ja(); + Ka(); + ce = class { + constructor(r, s, f) { + Ya(); + let i, p; + if (typeof r == "object" && "location" in r) switch (this.dataLocation = r.location, i = r.type, p = r.dims, r.location) { + case "cpu-pinned": { + let b = nt.get(i); + if (!b) throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`); + if (!(r.data instanceof b)) throw new TypeError(`buffer should be of type ${b.name}`); + this.cpuData = r.data; + break; } - - const { encoder_outputs, encoder_attention_mask } = await encoderForward(this, model_inputs); - - // @ts-expect-error TS2339 - const r = encoder_outputs.dims[1] / this.config.reduction_factor; - const maxlen = Math.floor(r * maxlenratio); - const minlen = Math.floor(r * minlenratio); - - // @ts-expect-error TS2339 - const num_mel_bins = this.config.num_mel_bins; - - let spectrogramParts = []; - let past_key_values = null; - let decoder_outputs = null; - let idx = 0; - - while (true) { - ++idx; - - const use_cache_branch = boolTensor(!!decoder_outputs); - let output_sequence; - if (decoder_outputs) { - output_sequence = decoder_outputs.output_sequence_out; - } else { - output_sequence = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - 'float32', - new Float32Array(num_mel_bins), - [1, 1, num_mel_bins], - ) - } - let decoderFeeds = { - use_cache_branch, - output_sequence, - encoder_attention_mask: encoder_attention_mask, - speaker_embeddings: speaker_embeddings, - encoder_hidden_states: encoder_outputs, - }; - - this.addPastKeyValues(decoderFeeds, past_key_values); - decoder_outputs = await sessionRun(this.sessions['decoder_model_merged'], decoderFeeds); - past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values); - - const { prob, spectrum } = decoder_outputs; - spectrogramParts.push(spectrum); - - if (idx >= minlen && ( - // Finished when stop token or maximum length is reached. - Array.from(prob.data).filter(p => p >= threshold).length > 0 || idx >= maxlen - )) { - 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; } - - const spectrogram = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.cat)(spectrogramParts); - const { waveform } = await sessionRun(vocoder.sessions['model'], { spectrogram }); - - return { - spectrogram, - waveform, - // cross_attentions: null, // TODO add + case "ml-tensor": { + if (i !== "float32" && i !== "float16" && i !== "int32" && i !== "int64" && i !== "uint32" && i !== "uint64" && i !== "int8" && i !== "uint8" && i !== "bool" && i !== "uint4" && i !== "int4") 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 b, g; + if (typeof r == "string") if (i = r, g = f, r === "string") { + if (!Array.isArray(s)) throw new TypeError("A string tensor's data must be a string array."); + b = s; + } else { + let w = nt.get(r); + if (w === void 0) throw new TypeError(`Unsupported tensor type: ${r}.`); + if (Array.isArray(s)) { + if (r === "float16" && w === Uint16Array || r === "uint4" || r === "int4") throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${w.name} as data.`); + r === "uint64" || r === "int64" ? b = w.from(s, BigInt) : b = w.from(s); + } else if (s instanceof w) b = s; + else if (s instanceof Uint8ClampedArray) if (r === "uint8") b = Uint8Array.from(s); + else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8"); + else if (r === "float16" && s instanceof Uint16Array && w !== Uint16Array) b = new globalThis.Float16Array(s.buffer, s.byteOffset, s.length); + else throw new TypeError(`A ${i} tensor's data must be type of ${w}`); + } + else if (g = s, Array.isArray(r)) { + if (r.length === 0) throw new TypeError("Tensor type cannot be inferred from an empty array."); + let w = typeof r[0]; + if (w === "string") i = "string", b = r; + else if (w === "boolean") i = "bool", b = Uint8Array.from(r); + else throw new TypeError(`Invalid element type of data array: ${w}.`); + } else if (r instanceof Uint8ClampedArray) i = "uint8", b = Uint8Array.from(r); + else { + let w = It.get(r.constructor); + if (w === void 0) throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`); + i = w, b = r; } + if (g === void 0) g = [b.length]; + else if (!Array.isArray(g)) throw new TypeError("A tensor's dims must be a number array"); + p = g, this.cpuData = b, this.dataLocation = "cpu"; + } + let l = Xa(p); + if (this.cpuData && l !== this.cpuData.length && !((i === "uint4" || i === "int4") && Math.ceil(l / 2) === this.cpuData.length)) throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`); + this.type = i, this.dims = p, this.size = l; } -} - -/** - * HiFi-GAN vocoder. - * - * See [SpeechT5ForSpeechToText](./models#module_models.SpeechT5ForSpeechToText) for example usage. - */ -class SpeechT5HifiGan extends PreTrainedModel { - main_input_name = 'spectrogram'; -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// TrOCR models -class TrOCRPreTrainedModel extends PreTrainedModel { } - -/** - * The TrOCR Decoder with a language modeling head. - */ -class TrOCRForCausalLM extends TrOCRPreTrainedModel { } - -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Mistral models -/** - * The bare Mistral Model outputting raw hidden-states without any specific head on top. - */ -class MistralPreTrainedModel extends PreTrainedModel { } - -class MistralModel extends MistralPreTrainedModel { } - -class MistralForCausalLM extends MistralPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// ERNIE-4.5 models -class Ernie4_5_PretrainedModel extends PreTrainedModel { } - -class Ernie4_5_Model extends Ernie4_5_PretrainedModel { } - -class Ernie4_5_ForCausalLM extends Ernie4_5_PretrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Starcoder2 models -/** - * The bare Starcoder2 Model outputting raw hidden-states without any specific head on top. - */ -class Starcoder2PreTrainedModel extends PreTrainedModel { } - -class Starcoder2Model extends Starcoder2PreTrainedModel { } - -class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Falcon models -/** - * The bare Falcon Model outputting raw hidden-states without any specific head on top. - */ -class FalconPreTrainedModel extends PreTrainedModel { } - -class FalconModel extends FalconPreTrainedModel { } - -class FalconForCausalLM extends FalconPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// CLAP models -class ClapPreTrainedModel extends PreTrainedModel { } - -class ClapModel extends ClapPreTrainedModel { } - -/** - * CLAP Text Model with a projection layer on top (a linear layer on top of the pooled output). - * - * **Example:** Compute text embeddings with `ClapTextModelWithProjection`. - * - * ```javascript - * import { AutoTokenizer, ClapTextModelWithProjection } from '@huggingface/transformers'; - * - * // Load tokenizer and text model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/clap-htsat-unfused'); - * const text_model = await ClapTextModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused'); - * - * // Run tokenization - * const texts = ['a sound of a cat', 'a sound of a dog']; - * const text_inputs = tokenizer(texts, { padding: true, truncation: true }); - * - * // Compute embeddings - * const { text_embeds } = await text_model(text_inputs); - * // Tensor { - * // dims: [ 2, 512 ], - * // type: 'float32', - * // data: Float32Array(1024) [ ... ], - * // size: 1024 - * // } - * ``` - */ -class ClapTextModelWithProjection extends ClapPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'text_model', - }); + static async fromImage(r, s) { + return Ga(r, s); } -} - -/** - * CLAP Audio Model with a projection layer on top (a linear layer on top of the pooled output). - * - * **Example:** Compute audio embeddings with `ClapAudioModelWithProjection`. - * - * ```javascript - * import { AutoProcessor, ClapAudioModelWithProjection, read_audio } from '@huggingface/transformers'; - * - * // Load processor and audio model - * const processor = await AutoProcessor.from_pretrained('Xenova/clap-htsat-unfused'); - * const audio_model = await ClapAudioModelWithProjection.from_pretrained('Xenova/clap-htsat-unfused'); - * - * // Read audio and run processor - * const audio = await read_audio('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav'); - * const audio_inputs = await processor(audio); - * - * // Compute embeddings - * const { audio_embeds } = await audio_model(audio_inputs); - * // Tensor { - * // dims: [ 1, 512 ], - * // type: 'float32', - * // data: Float32Array(512) [ ... ], - * // size: 512 - * // } - * ``` - */ -class ClapAudioModelWithProjection extends ClapPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'audio_model', - }); + static fromTexture(r, s) { + return $a(r, s); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// VITS models -class VitsPreTrainedModel extends PreTrainedModel { } - -/** - * The complete VITS model, for text-to-speech synthesis. - * - * **Example:** Generate speech from text with `VitsModel`. - * ```javascript - * import { AutoTokenizer, VitsModel } from '@huggingface/transformers'; - * - * // Load the tokenizer and model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/mms-tts-eng'); - * const model = await VitsModel.from_pretrained('Xenova/mms-tts-eng'); - * - * // Run tokenization - * const inputs = tokenizer('I love transformers'); - * - * // Generate waveform - * const { waveform } = await model(inputs); - * // Tensor { - * // dims: [ 1, 35328 ], - * // type: 'float32', - * // data: Float32Array(35328) [ ... ], - * // size: 35328, - * // } - * ``` - */ -class VitsModel extends VitsPreTrainedModel { - /** - * Calls the model on new inputs. - * @param {Object} model_inputs The inputs to the model. - * @returns {Promise} The outputs for the VITS model. - */ - async _call(model_inputs) { - return new VitsModelOutput(await super._call(model_inputs)); + static fromGpuBuffer(r, s) { + return za(r, s); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Segformer models -class SegformerPreTrainedModel extends PreTrainedModel { } - -/** - * The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top. - */ -class SegformerModel extends SegformerPreTrainedModel { } - -/** - * SegFormer Model transformer with an image classification head on top (a linear layer on top of the final hidden states) e.g. for ImageNet. - */ -class SegformerForImageClassification extends SegformerPreTrainedModel { } - -/** - * SegFormer Model transformer with an all-MLP decode head on top e.g. for ADE20k, CityScapes. - */ -class SegformerForSemanticSegmentation extends SegformerPreTrainedModel { } - -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// StableLm models -class StableLmPreTrainedModel extends PreTrainedModel { } - -/** - * The bare StableLm Model transformer outputting raw hidden-states without any specific head on top. - */ -class StableLmModel extends StableLmPreTrainedModel { } - -/** - * StableLm Model with a `language modeling` head on top for Causal Language Modeling (with past). - */ -class StableLmForCausalLM extends StableLmPreTrainedModel { } -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -class EfficientNetPreTrainedModel extends PreTrainedModel { } - -/** - * The bare EfficientNet model outputting raw features without any specific head on top. - */ -class EfficientNetModel extends EfficientNetPreTrainedModel { } - -/** - * EfficientNet Model with an image classification head on top (a linear layer on top of the pooled features). - */ -class EfficientNetForImageClassification extends EfficientNetPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Musicgen models -class MusicgenPreTrainedModel extends PreTrainedModel { } - -/** - * The bare Musicgen decoder model outputting raw hidden-states without any specific head on top. - */ -class MusicgenModel extends MusicgenPreTrainedModel { } - -/** - * The MusicGen decoder model with a language modelling head on top. - */ -class MusicgenForCausalLM extends MusicgenPreTrainedModel { } - -/** - * The composite MusicGen model with a text encoder, audio encoder and Musicgen decoder, - * for music generation tasks with one or both of text and audio prompts. - * - * **Example:** Generate music from text with `Xenova/musicgen-small`. - * ```javascript - * import { AutoTokenizer, MusicgenForConditionalGeneration } from '@huggingface/transformers'; - * - * // Load tokenizer and model - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/musicgen-small'); - * const model = await MusicgenForConditionalGeneration.from_pretrained( - * 'Xenova/musicgen-small', { dtype: 'fp32' } - * ); - * - * // Prepare text input - * const prompt = '80s pop track with bassy drums and synth'; - * const inputs = tokenizer(prompt); - * - * // Generate audio - * const audio_values = await model.generate({ - * ...inputs, - * max_new_tokens: 512, - * do_sample: true, - * guidance_scale: 3, - * }); - * - * // (Optional) Write the output to a WAV file - * import wavefile from 'wavefile'; - * import fs from 'fs'; - * - * const wav = new wavefile.WaveFile(); - * wav.fromScratch(1, model.config.audio_encoder.sampling_rate, '32f', audio_values.data); - * fs.writeFileSync('musicgen_out.wav', wav.toBuffer()); - * ``` - */ -class MusicgenForConditionalGeneration extends PreTrainedModel { // NOTE: not MusicgenPreTrainedModel - forward_params = [ - 'input_ids', - 'attention_mask', - 'encoder_outputs', - 'decoder_input_ids', - 'decoder_attention_mask', - 'past_key_values', - ]; - - /** - * Apply the pattern mask to the final ids, - * then revert the pattern delay mask by filtering the pad token id in a single step. - * @param {Tensor} outputs The output tensor from the model. - * @returns {Tensor} The filtered output tensor. - */ - _apply_and_filter_by_delay_pattern_mask(outputs) { - const [bs_x_codebooks, seqLength] = outputs.dims; - // @ts-expect-error TS2339 - const num_codebooks = this.config.decoder.num_codebooks; - const upperBound = (seqLength - num_codebooks); - - let newDataSize = 0; - for (let i = 0; i < outputs.size; ++i) { - // @ts-expect-error TS2339 - if (outputs.data[i] === this.config.decoder.pad_token_id) { - continue; - } - - const row = (i % seqLength); - const col = Math.floor(i / seqLength) % num_codebooks; - - const diff = row - col; - if (diff > 0 && diff <= upperBound) { - outputs.data[newDataSize++] = outputs.data[i]; - } - } - - const batch_size = Math.floor(bs_x_codebooks / num_codebooks); - const inferred = newDataSize / (batch_size * num_codebooks); - // TODO: assert `inferred` is an integer - return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_9__.Tensor( - outputs.type, - outputs.data.slice(0, newDataSize), - [batch_size, num_codebooks, inferred] - ); + static fromMLTensor(r, s) { + return Va(r, s); } - - - prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { - // apply the delay pattern mask - let clonedInputIds = structuredClone(input_ids); - for (let i = 0; i < clonedInputIds.length; ++i) { - for (let j = 0; j < clonedInputIds[i].length; ++j) { - // @ts-expect-error TS2339 - if ((i % this.config.decoder.num_codebooks) >= j) { - // @ts-expect-error TS2339 - clonedInputIds[i][j] = BigInt(this.config.decoder.pad_token_id); - } - } - } - // for classifier free guidance we need to replicate the decoder args across the batch dim - // (we'll split these before sampling) - if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { - // [batch, seqLength] -> [2 * batch, seqLength] - clonedInputIds = clonedInputIds.concat(clonedInputIds); - } - - const prepped = super.prepare_inputs_for_generation(clonedInputIds, model_inputs, generation_config); - return prepped; + static fromPinnedBuffer(r, s, f) { + return ja(r, s, f); } - - /** - * Generates sequences of token ids for models with a language modeling head. - * @param {import('./generation/parameters.js').GenerationFunctionParameters} options - * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. - */ - async generate(options) { - - const output_ids = await super.generate(options); - - // apply the pattern mask to the final ids - // tensor: int64[1,batch_size,4,chunk_length] - const audio_codes = this._apply_and_filter_by_delay_pattern_mask( - /** @type {Tensor} */(output_ids) - ).unsqueeze_(0); // append the frame dimension back to the audio codes - - const { audio_values } = await sessionRun(this.sessions['encodec_decode'], { audio_codes }) - - return audio_values; + toDataURL(r) { + return Wa(this, r); } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MobileNetV1 models -class MobileNetV1PreTrainedModel extends PreTrainedModel { } - -/** - * The bare MobileNetV1 model outputting raw hidden-states without any specific head on top. - */ -class MobileNetV1Model extends MobileNetV1PreTrainedModel { } - -/** - * MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), - * e.g. for ImageNet. - */ -class MobileNetV1ForImageClassification extends MobileNetV1PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + toImageData(r) { + return ka(this, r); } -} - -class MobileNetV1ForSemanticSegmentation extends MobileNetV1PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MobileNetV2 models -class MobileNetV2PreTrainedModel extends PreTrainedModel { } - -/** - * The bare MobileNetV2 model outputting raw hidden-states without any specific head on top. - */ -class MobileNetV2Model extends MobileNetV2PreTrainedModel { } - -/** - * MobileNetV2 model with an image classification head on top (a linear layer on top of the pooled features), - * e.g. for ImageNet. - */ -class MobileNetV2ForImageClassification extends MobileNetV2PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + 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; } -} -class MobileNetV2ForSemanticSegmentation extends MobileNetV2PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MobileNetV3 models -class MobileNetV3PreTrainedModel extends PreTrainedModel { } - -/** - * The bare MobileNetV3 model outputting raw hidden-states without any specific head on top. - */ -class MobileNetV3Model extends MobileNetV3PreTrainedModel { } - -/** - * MobileNetV3 model with an image classification head on top (a linear layer on top of the pooled features), - * e.g. for ImageNet. - */ -class MobileNetV3ForImageClassification extends MobileNetV3PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); + get location() { + return this.dataLocation; } -} -class MobileNetV3ForSemanticSegmentation extends MobileNetV3PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// MobileNetV4 models -class MobileNetV4PreTrainedModel extends PreTrainedModel { } - -/** - * The bare MobileNetV4 model outputting raw hidden-states without any specific head on top. - */ -class MobileNetV4Model extends MobileNetV4PreTrainedModel { } - -/** - * MobileNetV4 model with an image classification head on top (a linear layer on top of the pooled features), - * e.g. for ImageNet. - */ -class MobileNetV4ForImageClassification extends MobileNetV4PreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new SequenceClassifierOutput(await super._call(model_inputs)); - } -} -class MobileNetV4ForSemanticSegmentation extends MobileNetV4PreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// Decision Transformer models -class DecisionTransformerPreTrainedModel extends PreTrainedModel { } - -/** - * The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting. - * Refer to the paper for more details: https://huggingface.co/papers/2106.01345 - */ -class DecisionTransformerModel extends DecisionTransformerPreTrainedModel { } - -////////////////////////////////////////////////// - -class MultiModalityPreTrainedModel extends PreTrainedModel { } -class MultiModalityCausalLM extends MultiModalityPreTrainedModel { - forward_params = [ - // prepare_inputs_embeds - 'input_ids', - 'pixel_values', - 'images_seq_mask', - 'images_emb_mask', - - // language_model - 'attention_mask', - 'position_ids', - 'past_key_values', - ]; - - /** - * @param {ConstructorParameters} args - */ - constructor(...args) { - super(...args); - - // State-based approach to switch out which heads to use during generation - this._generation_mode = 'text'; + get texture() { + if (this.ensureValid(), !this.gpuTextureData) throw new Error("The data is not stored as a WebGL texture."); + return this.gpuTextureData; } - - async forward(model_inputs) { - const mode = this._generation_mode ?? 'text'; - - // TODO support re-using PKVs for input_ids.dims[1] !== 1 - // if (model_inputs.past_key_values) { - // // && model_inputs.input_ids.dims[1] === 1 - // } - - let output_1; - if (mode === 'text' || !model_inputs.past_key_values) { - const session = this.sessions['prepare_inputs_embeds']; - const prep_inputs = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(model_inputs, session.inputNames); - output_1 = await sessionRun(session, prep_inputs); - } else { - const session = this.sessions['gen_img_embeds']; - const prep_inputs = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)({ - image_ids: model_inputs.input_ids, - }, session.inputNames); - output_1 = await sessionRun(session, prep_inputs); - } - - const input_2 = { ...model_inputs, ...output_1 } - const output_2 = await decoderForward(this, input_2); - - const head = this.sessions[ - mode === 'text' - ? 'lm_head' - : 'gen_head' - ]; - if (!head) { - throw new Error(`Unable to find "${head}" generation head`); + 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 = true; + let s = await this.downloader(); + return this.downloader = void 0, this.dataLocation = "cpu", this.cpuData = s, r && this.disposer && (this.disposer(), this.disposer = void 0), s; + } finally { + this.isDownloading = false; + } } - - const output_3 = await sessionRun(head, (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.pick)(output_2, head.inputNames)) - - return { - ...output_1, - ...output_2, - ...output_3, - }; + default: + throw new Error(`cannot get data from location: ${this.dataLocation}`); + } } - - /** - * @param {import('./generation/parameters.js').GenerationFunctionParameters} options - */ - async generate(options) { - this._generation_mode = 'text'; - return super.generate(options); + 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"; } - - /** - * @param {import('./generation/parameters.js').GenerationFunctionParameters} options - */ - async generate_images(options) { - this._generation_mode = 'image'; - - const start_num_tokens = (options.inputs ?? options[this.main_input_name]).dims[1]; - const all_tokens = await super.generate(options); - - const generated_tokens = (/** @type {Tensor} */(all_tokens)).slice(null, [start_num_tokens, null]) - - const image_decode = this.sessions['image_decode']; - const { decoded_image } = await sessionRun(image_decode, { - generated_tokens, - }); - - // Equivalent to `np.clip((dec + 1) / 2 * 255, 0, 255)` - const clamped = decoded_image - .add_(1) - .mul_(255 / 2) - .clamp_(0, 255) - .to('uint8'); - - // Return as a list of images - const images = []; - for (const tensor of clamped) { - const img = _utils_image_js__WEBPACK_IMPORTED_MODULE_10__.RawImage.fromTensor(tensor); - images.push(img); - } - return images; + ensureValid() { + if (this.dataLocation === "none") throw new Error("The tensor is disposed."); } -} - -class MgpstrModelOutput extends ModelOutput { - constructor({ char_logits, bpe_logits, wp_logits }) { - super(); - this.char_logits = char_logits; - this.bpe_logits = bpe_logits; - this.wp_logits = wp_logits; + reshape(r) { + if (this.ensureValid(), this.downloader || this.disposer) throw new Error("Cannot reshape a tensor that owns GPU resource."); + return Za(this, r); } - - get logits() { - return [this.char_logits, this.bpe_logits, this.wp_logits]; + }; +}); +var Le; +var en = G(() => { + "use strict"; + Yt(); + Le = ce; +}); +var Qa; +var es; +var ot; +var at; +var $e; +var ze; +var tn = G(() => { + "use strict"; + Kr(); + Qa = (a, r) => { + (typeof ie.trace > "u" ? !ie.wasm.trace : !ie.trace) || console.timeStamp(`${a}::ORT::${r}`); + }, es = (a, r) => { + let s = new Error().stack?.split(/\r\n|\r|\n/g) || [], f = false; + for (let i = 0; i < s.length; i++) { + if (f && !s[i].includes("TRACE_FUNC")) { + let p = `FUNC_${a}::${s[i].trim().split(" ")[1]}`; + r && (p += `::${r}`), Qa("CPU", p); + return; + } + s[i].includes("TRACE_FUNC") && (f = true); + } + }, ot = (a) => { + (typeof ie.trace > "u" ? !ie.wasm.trace : !ie.trace) || es("BEGIN", a); + }, at = (a) => { + (typeof ie.trace > "u" ? !ie.wasm.trace : !ie.trace) || es("END", a); + }, $e = (a) => { + (typeof ie.trace > "u" ? !ie.wasm.trace : !ie.trace) || console.time(`ORT::${a}`); + }, ze = (a) => { + (typeof ie.trace > "u" ? !ie.wasm.trace : !ie.trace) || console.timeEnd(`ORT::${a}`); + }; +}); +var Jt; +var ts = G(() => { + "use strict"; + Zr(); + en(); + tn(); + Jt = class a { + constructor(r) { + this.handler = r; + } + async run(r, s, f) { + ot(), $e("InferenceSession.run"); + let i = {}, p = {}; + if (typeof r != "object" || r === null || r instanceof Le || Array.isArray(r)) throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values."); + let l = true; + if (typeof s == "object") { + if (s === null) throw new TypeError("Unexpected argument[1]: cannot be null."); + if (s instanceof Le) throw new TypeError("'fetches' cannot be a Tensor"); + if (Array.isArray(s)) { + if (s.length === 0) throw new TypeError("'fetches' cannot be an empty array."); + l = false; + for (let w of s) { + if (typeof w != "string") throw new TypeError("'fetches' must be a string array or an object."); + if (this.outputNames.indexOf(w) === -1) throw new RangeError(`'fetches' contains invalid output name: ${w}.`); + i[w] = null; + } + if (typeof f == "object" && f !== null) p = f; + else if (typeof f < "u") throw new TypeError("'options' must be an object."); + } else { + let w = false, S = Object.getOwnPropertyNames(s); + for (let v of this.outputNames) if (S.indexOf(v) !== -1) { + let T = s[v]; + (T === null || T instanceof Le) && (w = true, l = false, i[v] = T); + } + if (w) { + if (typeof f == "object" && f !== null) p = f; + else if (typeof f < "u") throw new TypeError("'options' must be an object."); + } else p = s; + } + } else if (typeof s < "u") throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'."); + for (let w of this.inputNames) if (typeof r[w] > "u") throw new Error(`input '${w}' is missing in 'feeds'.`); + if (l) for (let w of this.outputNames) i[w] = null; + let b = await this.handler.run(r, i, p), g = {}; + for (let w in b) if (Object.hasOwnProperty.call(b, w)) { + let S = b[w]; + S instanceof Le ? g[w] = S : g[w] = new Le(S.type, S.data, S.dims); + } + return ze("InferenceSession.run"), at(), g; } -} - -class MgpstrPreTrainedModel extends PreTrainedModel { } - -/** - * MGP-STR Model transformer with three classification heads on top - * (three A^3 modules and three linear layer on top of the transformer encoder output) for scene text recognition (STR). - */ -class MgpstrForSceneTextRecognition extends MgpstrPreTrainedModel { - /** - * @param {any} model_inputs - */ - async _call(model_inputs) { - return new MgpstrModelOutput(await super._call(model_inputs)); - } -} - -////////////////////////////////////////////////// -// PatchTST Transformer models -class PatchTSTPreTrainedModel extends PreTrainedModel { } - -/** - * The bare PatchTST Model outputting raw hidden-states without any specific head. - */ -class PatchTSTModel extends PatchTSTPreTrainedModel { } - -/** - * The PatchTST for prediction model. - */ -class PatchTSTForPrediction extends PatchTSTPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// PatchTSMixer Transformer models -class PatchTSMixerPreTrainedModel extends PreTrainedModel { } - -/** - * The bare PatchTSMixer Model outputting raw hidden-states without any specific head. - */ -class PatchTSMixerModel extends PatchTSMixerPreTrainedModel { } - -/** - * The PatchTSMixer for prediction model. - */ -class PatchTSMixerForPrediction extends PatchTSMixerPreTrainedModel { } -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class UltravoxPreTrainedModel extends PreTrainedModel { - forward_params = [ - 'input_ids', - 'attention_mask', - 'position_ids', - 'audio_values', - 'past_key_values', - ]; -} - -class UltravoxModel extends UltravoxPreTrainedModel { - - _merge_input_ids_with_audio_features(kwargs) { - const audio_hidden_size = kwargs.audio_features.dims.at(-1); - const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); - - return default_merge_input_ids_with_audio_features({ - // @ts-ignore - audio_token_id: this.config.ignore_index ?? this.config.audio_token_id, - ...kwargs, - audio_features: reshaped_audio_features, - }) + async release() { + return this.handler.dispose(); + } + static async create(r, s, f, i) { + ot(), $e("InferenceSession.create"); + let p, l = {}; + if (typeof r == "string") { + if (p = r, typeof s == "object" && s !== null) l = s; + else if (typeof s < "u") throw new TypeError("'options' must be an object."); + } else if (r instanceof Uint8Array) { + if (p = r, typeof s == "object" && s !== null) l = s; + else if (typeof s < "u") throw new TypeError("'options' must be an object."); + } else if (r instanceof ArrayBuffer || typeof SharedArrayBuffer < "u" && r instanceof SharedArrayBuffer) { + let S = r, v = 0, T = r.byteLength; + if (typeof s == "object" && s !== null) l = s; + else if (typeof s == "number") { + if (v = s, !Number.isSafeInteger(v)) throw new RangeError("'byteOffset' must be an integer."); + if (v < 0 || v >= S.byteLength) throw new RangeError(`'byteOffset' is out of range [0, ${S.byteLength}).`); + if (T = r.byteLength - v, typeof f == "number") { + if (T = f, !Number.isSafeInteger(T)) throw new RangeError("'byteLength' must be an integer."); + if (T <= 0 || v + T > S.byteLength) throw new RangeError(`'byteLength' is out of range (0, ${S.byteLength - v}].`); + if (typeof i == "object" && i !== null) l = i; + else if (typeof i < "u") throw new TypeError("'options' must be an object."); + } else if (typeof f < "u") throw new TypeError("'byteLength' must be a number."); + } else if (typeof s < "u") throw new TypeError("'options' must be an object."); + p = new Uint8Array(S, v, T); + } else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'."); + let [b, g] = await Da(l), w = await b.createInferenceSessionHandler(p, g); + return ze("InferenceSession.create"), at(), new a(w); } -} -////////////////////////////////////////////////// - -class VoxtralForConditionalGeneration extends UltravoxModel { } - -////////////////////////////////////////////////// -// Mimi models -class MimiPreTrainedModel extends PreTrainedModel { - main_input_name = 'input_values'; - forward_params = ['input_values']; -} - -class MimiEncoderOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.audio_codes Discrete code embeddings, of shape `(batch_size, num_quantizers, codes_length)`. - */ - constructor({ audio_codes }) { - super(); - this.audio_codes = audio_codes; + startProfiling() { + this.handler.startProfiling(); } -} - -class MimiDecoderOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.audio_values Decoded audio values, of shape `(batch_size, num_channels, sequence_length)`. - */ - constructor({ audio_values }) { - super(); - this.audio_values = audio_values; + endProfiling() { + this.handler.endProfiling(); } -} - -/** - * The Mimi neural audio codec model. - */ -class MimiModel extends MimiPreTrainedModel { - /** - * Encodes the input audio waveform into discrete codes. - * @param {Object} inputs Model inputs - * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). - * @returns {Promise} The output tensor of shape `(batch_size, num_codebooks, sequence_length)`. - */ - async encode(inputs) { - return new MimiEncoderOutput(await sessionRun(this.sessions['encoder_model'], inputs)); + get inputNames() { + return this.handler.inputNames; } - - /** - * Decodes the given frames into an output audio waveform. - * @param {MimiEncoderOutput} inputs The encoded audio codes. - * @returns {Promise} The output tensor of shape `(batch_size, num_channels, sequence_length)`. - */ - async decode(inputs) { - return new MimiDecoderOutput(await sessionRun(this.sessions['decoder_model'], inputs)); + get outputNames() { + return this.handler.outputNames; } -} - -class MimiEncoderModel extends MimiPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'encoder_model', - }); + get inputMetadata() { + return this.handler.inputMetadata; } -} -class MimiDecoderModel extends MimiPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'decoder_model', - }); + get outputMetadata() { + return this.handler.outputMetadata; + } + }; +}); +var bc; +var rs = G(() => { + "use strict"; + ts(); + bc = Jt; +}); +var ns = G(() => { + "use strict"; +}); +var os = G(() => { + "use strict"; +}); +var as = G(() => { + "use strict"; +}); +var ss = G(() => { + "use strict"; +}); +var rn = {}; +At(rn, { InferenceSession: () => bc, TRACE: () => Qa, TRACE_EVENT_BEGIN: () => $e, TRACE_EVENT_END: () => ze, TRACE_FUNC_BEGIN: () => ot, TRACE_FUNC_END: () => at, Tensor: () => Le, env: () => ee, registerBackend: () => rt }); +var Ve = G(() => { + "use strict"; + Pa(); + Na(); + rs(); + en(); + ns(); + os(); + tn(); + as(); + ss(); +}); +var Xt = G(() => { + "use strict"; +}); +var cs = {}; +At(cs, { default: () => gc }); +var us; +var fs; +var gc; +var ds = G(() => { + "use strict"; + nn(); + je(); + Zt(); + us = "ort-wasm-proxy-worker", fs = globalThis.self?.name === us; + fs && (self.onmessage = (a) => { + let { type: r, in: s } = a.data; + try { + switch (r) { + case "init-wasm": + Kt(s.wasm).then(() => { + Qt(s).then(() => { + postMessage({ type: r }); + }, (f) => { + postMessage({ type: r, err: f }); + }); + }, (f) => { + postMessage({ type: r, err: f }); + }); + break; + case "init-ep": { + let { epName: f, env: i } = s; + er(i, f).then(() => { + postMessage({ type: r }); + }, (p) => { + postMessage({ type: r, err: p }); + }); + break; + } + case "copy-from": { + let { buffer: f } = s, i = Lt(f); + postMessage({ type: r, out: i }); + break; + } + case "create": { + let { model: f, options: i } = s; + tr(f, i).then((p) => { + postMessage({ type: r, out: p }); + }, (p) => { + postMessage({ type: r, err: p }); + }); + break; + } + case "release": + rr(s), postMessage({ type: r }); + break; + case "run": { + let { sessionId: f, inputIndices: i, inputs: p, outputIndices: l, options: b } = s; + nr(f, i, p, l, new Array(l.length).fill(null), b).then((g) => { + g.some((w) => w[3] !== "cpu") ? postMessage({ type: r, err: "Proxy does not support non-cpu tensor location." }) : postMessage({ type: r, out: g }, ar([...p, ...g])); + }, (g) => { + postMessage({ type: r, err: g }); + }); + break; + } + case "end-profiling": + or(s), postMessage({ type: r }); + break; + default: + } + } catch (f) { + postMessage({ type: r, err: f }); + } + }); + gc = fs ? null : (a) => new Worker(a ?? ye, { type: "module", name: us }); +}); +var ps = {}; +At(ps, { default: () => yc }); +async function ls(a = {}) { + var r = a, s = !!globalThis.window, f = !!globalThis.WorkerGlobalScope, i = f && self.name?.startsWith("em-pthread"); + r.mountExternalData = (e, t) => { + e.startsWith("./") && (e = e.substring(2)), (r.ed || (r.ed = /* @__PURE__ */ new Map())).set(e, t); + }, r.unmountExternalData = () => { + delete r.ed, delete r.Te, delete r.Se, delete r.Ue; + }, globalThis.SharedArrayBuffer ?? new WebAssembly.Memory({ initial: 0, maximum: 0, shared: true }).buffer.constructor; + let p = () => { + let e = (t) => (...n) => { + let o = Me; + return n = t(...n), Me != o ? new Promise((u, c) => { + Cr = { resolve: u, reject: c }; + }) : n; + }; + (() => { + for (let t of ["_OrtAppendExecutionProvider", "_OrtCreateSession", "_OrtRun", "_OrtRunWithBinding", "_OrtBindInput"]) r[t] = e(r[t]); + })(), typeof jsepRunAsync < "u" && (r._OrtRun = jsepRunAsync(r._OrtRun), r._OrtRunWithBinding = jsepRunAsync(r._OrtRunWithBinding)), p = void 0; + }; + r.asyncInit = () => { + p?.(); + }; + var l, b, g = (e, t) => { + throw t; + }, w = import.meta.url, S = ""; + if (s || f) { + try { + S = new URL(".", w).href; + } catch { + } + f && (b = (e) => { + var t = new XMLHttpRequest(); + return t.open("GET", e, false), t.responseType = "arraybuffer", t.send(null), new Uint8Array(t.response); + }), l = async (e) => { + if (oe(e)) return new Promise((n, o) => { + var u = new XMLHttpRequest(); + u.open("GET", e, true), u.responseType = "arraybuffer", u.onload = () => { + u.status == 200 || u.status == 0 && u.response ? n(u.response) : o(u.status); + }, u.onerror = o, u.send(null); + }); + var t = await fetch(e, { credentials: "same-origin" }); + if (t.ok) return t.arrayBuffer(); + throw Error(t.status + " : " + t.url); + }; + } + var v, T, A, C, _, k, U = console.log.bind(console), M = console.error.bind(console), Y = U, O = M, $ = false, oe = (e) => e.startsWith("file://"); + function d() { + Fe.buffer != Z.buffer && se(); + } + if (i) { + let e = function(t) { + try { + var n = t.data, o = n.$c; + if (o === "load") { + let u = []; + self.onmessage = (c) => u.push(c), k = () => { + postMessage({ $c: "loaded" }); + for (let c of u) e(c); + self.onmessage = e; + }; + for (let c of n.ue) r[c] && !r[c].proxy || (r[c] = (...h) => { + postMessage({ $c: "callHandler", te: c, args: h }); + }, c == "print" && (Y = r[c]), c == "printErr" && (O = r[c])); + Fe = n.Me, se(), T = n.Ne, wt(), jt(); + } else if (o === "run") { + (function(u) { + var c = (d(), E)[u + 52 >>> 2 >>> 0]; + u = (d(), E)[u + 56 >>> 2 >>> 0], Fo(c, c - u), D(c); + })(n.Xc), zr(n.Xc, 0, 0, 1, 0, 0), wn(), Br(n.Xc), te || (vo(), te = true); + try { + ei(n.ze, n.kd); + } catch (u) { + if (u != "unwind") throw u; + } + } else n.target !== "setimmediate" && (o === "checkMailbox" ? te && _t() : o && (O(`worker: received unknown command ${o}`), O(n))); + } catch (u) { + throw _o(), u; + } + }; + var Vc = e, te = false; + self.onunhandledrejection = (t) => { + throw t.reason || t; + }, self.onmessage = e; + } + var Z, X, De, K, I, E, R, ae, pe, J, ge, ne = false; + function se() { + var e = Fe.buffer; + r.HEAP8 = Z = new Int8Array(e), De = new Int16Array(e), r.HEAPU8 = X = new Uint8Array(e), K = new Uint16Array(e), r.HEAP32 = I = new Int32Array(e), r.HEAPU32 = E = new Uint32Array(e), R = new Float32Array(e), ae = new Float64Array(e), pe = new BigInt64Array(e), J = new BigUint64Array(e); + } + function wr() { + ne = true, i ? k() : Ne.hc(); + } + function we(e) { + throw O(e = "Aborted(" + e + ")"), $ = true, e = new WebAssembly.RuntimeError(e + ". Build with -sASSERTIONS for more info."), _?.(e), e; + } + function qe() { + return { a: { qa: Af, f: ti, K: ri, k: ni, p: oi, l: ai, fa: si, b: ii, da: ui, gc: An, q: fi, ea: On, Ua: Mn, cc: Cn, ec: Dn, Va: Pn, Sa: Un, La: _n, Ra: Rn, oa: Nn, dc: Wn, ac: kn, Ta: Fn, bc: Gn, _a: ci, Ba: li, Xb: pi, Vb: hi, Aa: gi, O: yi, J: wi, Wb: Ti, ka: Li, Yb: Bi, Oa: Oi, _b: Ci, Ea: Di, Tb: Pi, Ca: Ui, Na: Br, Xa: _i, U: ki, n: Vi, c: Ir, qb: ji, w: Hi, N: qi, A: Yi, j: Ji, o: Jn, rb: Xi, H: Zi, T: Ki, g: Qi, u: eu, m: tu, i: ru, Ia: nu, Ja: ou, Ka: au, Ga: Qn, Ha: eo, Ub: to, ab: iu, Za: cu, Z: du, pb: lu, Da: pu, Ya: uu, X: mu, Wa: hu, $b: bu, G: su, db: gu, _: yu, pa: Ft, Zb: Tu, cb: wu, bb: vu, lb: Uu, z: _u, sa: Ru, ra: Nu, nb: Wu, Y: ku, v: Fu, kb: Gu, jb: $u, ib: zu, mb: Vu, gb: ju, fb: Hu, eb: qu, Pa: po, Qa: mo, fc: vr, W: ho, Fa: bo, ma: go, Ma: yo, la: wo, Fb: fc, va: nc, Gb: uc, wa: rc, E: zf, e: Of, r: Lf, x: If2, C: kf, Ib: Qf, ca: Kf, D: Df, xa: ec, aa: oc, ha: Zf, Jb: Xf, Kb: Jf, za: jf, Lb: qf, ya: Yf, Mb: Hf, ua: ic, ba: tc, d: Bf, B: Cf, s: Mf, Eb: cc, t: Uf, y: Gf, F: Pf, I: _f, L: $f, Nb: Vf, R: ac, ia: Wf, $: sc, Pb: Nf, Rb: Rf, Ob: Ff, h: Ju, a: Fe, $a: Ye, Hb: Xu, V: Zu, M: Ku, na: Qu, Db: ef, ja: tf, S: rf, Ab: nf, Bb: of, vb: af, wb: sf, P: uf, xb: ff, yb: cf, ta: df, Sb: lf, ob: pf, Q: mf, hb: hf, Cb: bf, sb: gf, tb: wf, ub: Tf, ga: vf, zb: Ef, Qb: Sf } }; + } + async function wt() { + function e(o, u) { + var c = Ne = o.exports; + o = {}; + for (let [h, m] of Object.entries(c)) typeof m == "function" ? (c = Ri(m), o[h] = c) : o[h] = m; + return Ne = o, Ne = (function() { + var h = Ne, m = (x) => (N) => x(N) >>> 0, y = (x) => () => x() >>> 0; + return (h = Object.assign({}, h)).ic = m(h.ic), h.Nc = y(h.Nc), h.Pc = m(h.Pc), h.Bd = /* @__PURE__ */ ((x) => (N, F) => x(N, F) >>> 0)(h.Bd), h.Gd = m(h.Gd), h.Hd = y(h.Hd), h.Ld = m(h.Ld), h; + })(), gn.push(Ne.sd), To = (o = Ne).ic, vo = o.jc, r._OrtInit = o.kc, r._OrtGetLastError = o.lc, r._OrtCreateSessionOptions = o.mc, r._OrtAppendExecutionProvider = o.nc, r._OrtAddFreeDimensionOverride = o.oc, r._OrtAddSessionConfigEntry = o.pc, r._OrtReleaseSessionOptions = o.qc, r._OrtCreateSession = o.rc, r._OrtReleaseSession = o.sc, r._OrtGetInputOutputCount = o.tc, r._OrtGetInputOutputMetadata = o.uc, r._OrtFree = o.vc, r._OrtCreateTensor = o.wc, r._OrtGetTensorData = o.xc, r._OrtReleaseTensor = o.yc, r._OrtCreateRunOptions = o.zc, r._OrtAddRunConfigEntry = o.Ac, r._OrtReleaseRunOptions = o.Bc, r._OrtCreateBinding = o.Cc, r._OrtBindInput = o.Dc, r._OrtBindOutput = o.Ec, r._OrtClearBoundOutputs = o.Fc, r._OrtReleaseBinding = o.Gc, r._OrtRunWithBinding = o.Hc, r._OrtRun = o.Ic, r._OrtEndProfiling = o.Jc, Eo = r._OrtCreateWebGpuInstance = o.Kc, r._wgpuCreateInstance = o.Lc, Nr = r._OrtGetWebGpuDevice = o.Mc, zt = o.Nc, ve = r._free = o.Oc, Ke = r._malloc = o.Pc, So = r._wgpuBufferRelease = o.Qc, xo = o.Rc, Ao = o.Sc, Io = o.Tc, Lo = o.Uc, Bo = o.Vc, Oo = o.Yc, Mo = o.Zc, Co = o.hd, Do = o.id, Po = o.jd, Wr = o.ld, kr = o.md, Fr = o.nd, Gr = o.od, St = o.pd, $r = o.qd, Uo = o.rd, zr = o.ud, _o = o.vd, Ro = o.wd, No = o.xd, Vr = o.yd, Wo = o.zd, ko = o.Ad, jr = o.Bd, W = o.Cd, xt = o.Dd, Fo = o.Ed, D = o.Fd, Vt = o.Gd, P = o.Hd, Go = o.Id, Hr = o.Jd, $o = o.Kd, zo = o.Ld, Vo = o.Md, qr = o.Nd, jo = o.Od, Ho = o.Pd, qo = o.Qd, Yo = o.Rd, Jo = o.Sd, Xo = o.Td, Zo = o.Ud, Ko = o.Vd, Qo = o.Wd, ea = o.Xd, ta = o.Yd, ra = o.Zd, na = o._d, oa = o.$d, aa = o.ae, sa = o.be, ia = o.ce, ua = o.de, fa = o.fe, ca = o.ge, da = o.he, la = o.ie, pa = o.je, ma = o.ke, ha = o.le, ba = o.me, ga = o.Ae, ya = o.Be, wa = o.Ce, Ta = o.De, va = o.Ee, Ea = o.Fe, Sa = o.Ge, xa = o.He, Aa = o.Ie, Ia = o.Je, La = o.Ke, Ba = o.nf, Oa = o.of, Ma = o.pf, Ca = o.qf, T = u, Ne; + } + var t, n = qe(); + return r.instantiateWasm ? new Promise((o) => { + r.instantiateWasm(n, (u, c) => { + o(e(u, c)); + }); + }) : i ? e(new WebAssembly.Instance(T, qe()), T) : (ge ??= r.locateFile ? r.locateFile ? r.locateFile("ort-wasm-simd-threaded.asyncify.wasm", S) : S + "ort-wasm-simd-threaded.asyncify.wasm" : new URL("ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href, t = await (async function(o) { + var u = ge; + if (!v && !oe(u)) try { + var c = fetch(u, { credentials: "same-origin" }); + return await WebAssembly.instantiateStreaming(c, o); + } catch (h) { + O(`wasm streaming compile failed: ${h}`), O("falling back to ArrayBuffer instantiation"); + } + return (async function(h, m) { + try { + var y = await (async function(x) { + if (!v) try { + var N = await l(x); + return new Uint8Array(N); + } catch { + } + if (x == ge && v) x = new Uint8Array(v); + else { + if (!b) throw "both async and sync fetching of the wasm failed"; + x = b(x); + } + return x; + })(h); + return await WebAssembly.instantiate(y, m); + } catch (x) { + O(`failed to asynchronously prepare wasm: ${x}`), we(x); + } + })(u, o); + })(n), e(t.instance, t.module)); + } + class Tt { + name = "ExitStatus"; + constructor(t) { + this.message = `Program terminated with exit(${t})`, this.status = t; + } + } + var Se = (e) => { + e.terminate(), e.onmessage = () => { + }; + }, xe = [], Be = 0, re = null, Q = (e) => { + ke.length == 0 && (vn(), Tn(ke[0])); + var t = ke.pop(); + if (!t) return 6; + vt.push(t), Je[e.Xc] = t, t.Xc = e.Xc; + var n = { $c: "run", ze: e.ye, kd: e.kd, Xc: e.Xc }; + return t.postMessage(n, e.oe), 0; + }, z = 0, H = (e, t, ...n) => { + var o, u = 16 * n.length, c = P(), h = Vt(u), m = h >>> 3; + for (o of n) typeof o == "bigint" ? ((d(), pe)[m++ >>> 0] = 1n, (d(), pe)[m++ >>> 0] = o) : ((d(), pe)[m++ >>> 0] = 0n, (d(), ae)[m++ >>> 0] = o); + return e = Ro(e, 0, u, h, t), D(c), e; + }; + function Ye(e) { + if (i) return H(0, 1, e); + if (A = e, !(0 < z)) { + for (var t of vt) Se(t); + for (t of ke) Se(t); + ke = [], vt = [], Je = {}, $ = true; + } + g(0, new Tt(e)); + } + function Tr(e) { + if (i) return H(1, 0, e); + vr(e); + } + var vr = (e) => { + if (A = e, i) throw Tr(e), "unwind"; + Ye(e); + }, ke = [], vt = [], gn = [], Je = {}, yn = (e) => { + var t = e.Xc; + delete Je[t], ke.push(e), vt.splice(vt.indexOf(e), 1), e.Xc = 0, No(t); + }; + function wn() { + gn.forEach((e) => e()); + } + var Tn = (e) => new Promise((t) => { + e.onmessage = (u) => { + var c = u.data; + if (u = c.$c, c.gd && c.gd != zt()) { + var h = Je[c.gd]; + h ? h.postMessage(c, c.oe) : O(`Internal error! Worker sent a message "${u}" to target pthread ${c.gd}, but that thread no longer exists!`); + } else u === "checkMailbox" ? _t() : u === "spawnThread" ? Q(c) : u === "cleanupThread" ? me(() => { + yn(Je[c.Le]); + }) : u === "loaded" ? (e.loaded = true, t(e)) : c.target === "setimmediate" ? e.postMessage(c) : u === "uncaughtException" ? e.onerror(c.error) : u === "callHandler" ? r[c.te](...c.args) : u && O(`worker sent an unknown command ${u}`); + }, e.onerror = (u) => { + throw O(`worker sent an error! ${u.filename}:${u.lineno}: ${u.message}`), u; + }; + var n, o = []; + for (n of []) r.propertyIsEnumerable(n) && o.push(n); + e.postMessage({ $c: "load", ue: o, Me: Fe, Ne: T }); + }); + function vn() { + var e = new Worker((() => { + let t = URL; + return import.meta.url > "file:" && import.meta.url < "file;" ? new t("ort.webgpu.bundle.min.mjs", import.meta.url) : new URL(import.meta.url); + })(), { type: "module", workerData: "em-pthread", name: "em-pthread" }); + ke.push(e); + } + var Fe, ei = (e, t) => { + z = 0, e = qr(e, t), 0 < z ? A = e : Vr(e); + }, Pt = [], Ut = 0, ue = (e) => -9007199254740992 > e || 9007199254740992 < e ? NaN : Number(e); + function ti(e) { + var t = new Er(e >>>= 0); + return (d(), Z)[t.ad + 12 >>> 0] == 0 && (En(t, true), Ut--), Sn(t, false), Pt.push(t), zo(e); + } + var dt = 0, ri = () => { + W(0, 0); + var e = Pt.pop(); + Go(e.td), dt = 0; + }; + function En(e, t) { + t = t ? 1 : 0, (d(), Z)[e.ad + 12 >>> 0] = t; + } + function Sn(e, t) { + t = t ? 1 : 0, (d(), Z)[e.ad + 13 >>> 0] = t; + } + class Er { + constructor(t) { + this.td = t, this.ad = t - 24; + } + } + var Sr = (e) => { + var t = dt; + if (!t) return xt(0), 0; + var n = new Er(t); + (d(), E)[n.ad + 16 >>> 2 >>> 0] = t; + var o = (d(), E)[n.ad + 4 >>> 2 >>> 0]; + if (!o) return xt(0), t; + for (var u of e) { + if (u === 0 || u === o) break; + if ($o(u, o, n.ad + 16)) return xt(u), t; + } + return xt(o), t; + }; + function ni() { + return Sr([]); + } + function oi(e) { + return Sr([e >>> 0]); + } + function ai(e, t, n, o) { + return Sr([e >>> 0, t >>> 0, n >>> 0, o >>> 0]); + } + var si = () => { + var e = Pt.pop(); + e || we("no exception to throw"); + var t = e.td; + throw (d(), Z)[e.ad + 13 >>> 0] == 0 && (Pt.push(e), Sn(e, true), En(e, false), Ut++), Hr(t), dt = t; + }; + function ii(e, t, n) { + var o = new Er(e >>>= 0); + throw t >>>= 0, n >>>= 0, (d(), E)[o.ad + 16 >>> 2 >>> 0] = 0, (d(), E)[o.ad + 4 >>> 2 >>> 0] = t, (d(), E)[o.ad + 8 >>> 2 >>> 0] = n, Hr(e), Ut++, dt = e; + } + var ui = () => Ut; + function xn(e, t, n, o) { + return i ? H(2, 1, e, t, n, o) : An(e, t, n, o); + } + function An(e, t, n, o) { + if (e >>>= 0, t >>>= 0, n >>>= 0, o >>>= 0, !globalThis.SharedArrayBuffer) return 6; + var u = []; + return i && u.length === 0 ? xn(e, t, n, o) : (e = { ye: n, Xc: e, kd: o, oe: u }, i ? (e.$c = "spawnThread", postMessage(e, u), 0) : Q(e)); + } + function fi(e) { + throw dt ||= e >>> 0, dt; + } + var In = globalThis.TextDecoder && new TextDecoder(), Ln = (e, t, n, o) => { + if (n = t + n, o) return n; + for (; e[t] && !(t >= n); ) ++t; + return t; + }, Bn = (e, t = 0, n, o) => { + if (16 < (n = Ln(e, t >>>= 0, n, o)) - t && e.buffer && In) return In.decode(e.buffer instanceof ArrayBuffer ? e.subarray(t, n) : e.slice(t, n)); + for (o = ""; t < n; ) { + var u = e[t++]; + if (128 & u) { + var c = 63 & e[t++]; + if ((224 & u) == 192) o += String.fromCharCode((31 & u) << 6 | c); + else { + var h = 63 & e[t++]; + 65536 > (u = (240 & u) == 224 ? (15 & u) << 12 | c << 6 | h : (7 & u) << 18 | c << 12 | h << 6 | 63 & e[t++]) ? o += String.fromCharCode(u) : (u -= 65536, o += String.fromCharCode(55296 | u >> 10, 56320 | 1023 & u)); + } + } else o += String.fromCharCode(u); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Dac models -class DacPreTrainedModel extends PreTrainedModel { - main_input_name = 'input_values'; - forward_params = ['input_values']; -} - -class DacEncoderOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.audio_codes Discrete code embeddings, of shape `(batch_size, num_quantizers, codes_length)`. - */ - constructor({ audio_codes }) { - super(); - this.audio_codes = audio_codes; + return o; + }, lt = (e, t, n) => (e >>>= 0) ? Bn((d(), X), e, t, n) : ""; + function On(e, t, n) { + return i ? H(3, 1, e, t, n) : 0; + } + function Mn(e, t) { + if (i) return H(4, 1, e, t); + } + function Cn(e, t) { + if (i) return H(5, 1, e, t); + } + function Dn(e, t, n) { + if (i) return H(6, 1, e, t, n); + } + function Pn(e, t, n) { + return i ? H(7, 1, e, t, n) : 0; + } + function Un(e, t) { + if (i) return H(8, 1, e, t); + } + function _n(e, t, n) { + if (i) return H(9, 1, e, t, n); + } + function Rn(e, t, n, o) { + if (i) return H(10, 1, e, t, n, o); + } + function Nn(e, t, n, o) { + if (i) return H(11, 1, e, t, n, o); + } + function Wn(e, t, n, o) { + if (i) return H(12, 1, e, t, n, o); + } + function kn(e) { + if (i) return H(13, 1, e); + } + function Fn(e, t) { + if (i) return H(14, 1, e, t); + } + function Gn(e, t, n) { + if (i) return H(15, 1, e, t, n); + } + var ci = () => we(""), Oe = (e) => { + e >>>= 0; + for (var t = ""; ; ) { + var n = (d(), X)[e++ >>> 0]; + if (!n) return t; + t += String.fromCharCode(n); } -} - -class DacDecoderOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.audio_values Decoded audio values, of shape `(batch_size, num_channels, sequence_length)`. - */ - constructor({ audio_values }) { - super(); - this.audio_values = audio_values; + }, xr = {}, Ar = {}, di = {}, pt = class extends Error { + constructor(e) { + super(e), this.name = "BindingError"; } -} - -/** - * The DAC (Descript Audio Codec) model. - */ -class DacModel extends DacPreTrainedModel { - /** - * Encodes the input audio waveform into discrete codes. - * @param {Object} inputs Model inputs - * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). - * @returns {Promise} The output tensor of shape `(batch_size, num_codebooks, sequence_length)`. - */ - async encode(inputs) { - return new DacEncoderOutput(await sessionRun(this.sessions['encoder_model'], inputs)); + }; + function Pe(e, t, n = {}) { + return (function(o, u, c = {}) { + var h = u.name; + if (!o) throw new pt(`type "${h}" must have a positive integer typeid pointer`); + if (Ar.hasOwnProperty(o)) { + if (c.ve) return; + throw new pt(`Cannot register type '${h}' twice`); + } + Ar[o] = u, delete di[o], xr.hasOwnProperty(o) && (u = xr[o], delete xr[o], u.forEach((m) => m())); + })(e, t, n); + } + var $n = (e, t, n) => { + switch (t) { + case 1: + return n ? (o) => (d(), Z)[o >>> 0] : (o) => (d(), X)[o >>> 0]; + case 2: + return n ? (o) => (d(), De)[o >>> 1 >>> 0] : (o) => (d(), K)[o >>> 1 >>> 0]; + case 4: + return n ? (o) => (d(), I)[o >>> 2 >>> 0] : (o) => (d(), E)[o >>> 2 >>> 0]; + case 8: + return n ? (o) => (d(), pe)[o >>> 3 >>> 0] : (o) => (d(), J)[o >>> 3 >>> 0]; + default: + throw new TypeError(`invalid integer width (${t}): ${e}`); } - - /** - * Decodes the given frames into an output audio waveform. - * @param {DacEncoderOutput} inputs The encoded audio codes. - * @returns {Promise} The output tensor of shape `(batch_size, num_channels, sequence_length)`. - */ - async decode(inputs) { - return new DacDecoderOutput(await sessionRun(this.sessions['decoder_model'], inputs)); + }; + function li(e, t, n, o, u) { + e >>>= 0, n >>>= 0, t = Oe(t >>> 0); + let c = (h) => h; + if (o = o === 0n) { + let h = 8 * n; + c = (m) => BigInt.asUintN(h, m), u = c(u); + } + Pe(e, { name: t, Wc: c, cd: (h, m) => (typeof m == "number" && (m = BigInt(m)), m), bd: $n(t, n, !o), dd: null }); + } + function pi(e, t, n, o) { + Pe(e >>>= 0, { name: t = Oe(t >>> 0), Wc: function(u) { + return !!u; + }, cd: function(u, c) { + return c ? n : o; + }, bd: function(u) { + return this.Wc((d(), X)[u >>> 0]); + }, dd: null }); + } + var zn = [], Xe = [0, 1, , 1, null, 1, true, 1, false, 1]; + function Ir(e) { + 9 < (e >>>= 0) && --Xe[e + 1] === 0 && (Xe[e] = void 0, zn.push(e)); + } + var Te = (e) => { + if (!e) throw new pt(`Cannot use deleted val. handle = ${e}`); + return Xe[e]; + }, Ae = (e) => { + switch (e) { + case void 0: + return 2; + case null: + return 4; + case true: + return 6; + case false: + return 8; + default: + let t = zn.pop() || Xe.length; + return Xe[t] = e, Xe[t + 1] = 1, t; } -} - -class DacEncoderModel extends DacPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'encoder_model', - }); + }; + function Lr(e) { + return this.Wc((d(), E)[e >>> 2 >>> 0]); + } + var mi = { name: "emscripten::val", Wc: (e) => { + var t = Te(e); + return Ir(e), t; + }, cd: (e, t) => Ae(t), bd: Lr, dd: null }; + function hi(e) { + return Pe(e >>> 0, mi); + } + var bi = (e, t) => { + switch (t) { + case 4: + return function(n) { + return this.Wc((d(), R)[n >>> 2 >>> 0]); + }; + case 8: + return function(n) { + return this.Wc((d(), ae)[n >>> 3 >>> 0]); + }; + default: + throw new TypeError(`invalid float width (${t}): ${e}`); } -} -class DacDecoderModel extends DacPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'decoder_model', - }); + }; + function gi(e, t, n) { + n >>>= 0, Pe(e >>>= 0, { name: t = Oe(t >>> 0), Wc: (o) => o, cd: (o, u) => u, bd: bi(t, n), dd: null }); + } + function yi(e, t, n, o, u) { + e >>>= 0, n >>>= 0, t = Oe(t >>> 0); + let c = (m) => m; + if (o === 0) { + var h = 32 - 8 * n; + c = (m) => m << h >>> h, u = c(u); + } + Pe(e, { name: t, Wc: c, cd: (m, y) => y, bd: $n(t, n, o !== 0), dd: null }); + } + function wi(e, t, n) { + function o(c) { + var h = (d(), E)[c >>> 2 >>> 0]; + return c = (d(), E)[c + 4 >>> 2 >>> 0], new u((d(), Z).buffer, c, h); } -} -////////////////////////////////////////////////// - - -////////////////////////////////////////////////// -// Snac models -class SnacPreTrainedModel extends PreTrainedModel { - main_input_name = 'input_values'; - forward_params = ['input_values']; -} - -/** - * The SNAC (Multi-Scale Neural Audio Codec) model. - */ -class SnacModel extends SnacPreTrainedModel { - /** - * Encodes the input audio waveform into discrete codes. - * @param {Object} inputs Model inputs - * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). - * @returns {Promise>} The output tensors of shape `(batch_size, num_codebooks, sequence_length)`. - */ - async encode(inputs) { - return await sessionRun(this.sessions['encoder_model'], inputs); + var u = [Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, BigInt64Array, BigUint64Array][t]; + Pe(e >>>= 0, { name: n = Oe(n >>> 0), Wc: o, bd: o }, { ve: true }); + } + var Ue = (e, t, n) => { + var o = (d(), X); + if (t >>>= 0, 0 < n) { + var u = t; + n = t + n - 1; + for (var c = 0; c < e.length; ++c) { + var h = e.codePointAt(c); + if (127 >= h) { + if (t >= n) break; + o[t++ >>> 0] = h; + } else if (2047 >= h) { + if (t + 1 >= n) break; + o[t++ >>> 0] = 192 | h >> 6, o[t++ >>> 0] = 128 | 63 & h; + } else if (65535 >= h) { + if (t + 2 >= n) break; + o[t++ >>> 0] = 224 | h >> 12, o[t++ >>> 0] = 128 | h >> 6 & 63, o[t++ >>> 0] = 128 | 63 & h; + } else { + if (t + 3 >= n) break; + o[t++ >>> 0] = 240 | h >> 18, o[t++ >>> 0] = 128 | h >> 12 & 63, o[t++ >>> 0] = 128 | h >> 6 & 63, o[t++ >>> 0] = 128 | 63 & h, c++; + } + } + o[t >>> 0] = 0, e = t - u; + } else e = 0; + return e; + }, _e = (e) => { + for (var t = 0, n = 0; n < e.length; ++n) { + var o = e.charCodeAt(n); + 127 >= o ? t++ : 2047 >= o ? t += 2 : 55296 <= o && 57343 >= o ? (t += 4, ++n) : t += 3; + } + return t; + }; + function Ti(e, t) { + Pe(e >>>= 0, { name: t = Oe(t >>> 0), Wc(n) { + var o = (d(), E)[n >>> 2 >>> 0]; + return o = lt(n + 4, o, true), ve(n), o; + }, cd(n, o) { + o instanceof ArrayBuffer && (o = new Uint8Array(o)); + var u = typeof o == "string"; + if (!(u || ArrayBuffer.isView(o) && o.BYTES_PER_ELEMENT == 1)) throw new pt("Cannot pass non-string to std::string"); + var c = u ? _e(o) : o.length, h = Ke(4 + c + 1), m = h + 4; + return (d(), E)[h >>> 2 >>> 0] = c, u ? Ue(o, m, c + 1) : (d(), X).set(o, m >>> 0), n !== null && n.push(ve, h), h; + }, bd: Lr, dd(n) { + ve(n); + } }); + } + var Vn = globalThis.TextDecoder ? new TextDecoder("utf-16le") : void 0, vi = (e, t, n) => { + if (e >>>= 1, 16 < (t = Ln((d(), K), e, t / 2, n)) - e && Vn) return Vn.decode((d(), K).slice(e, t)); + for (n = ""; e < t; ++e) { + var o = (d(), K)[e >>> 0]; + n += String.fromCharCode(o); + } + return n; + }, Ei = (e, t, n) => { + if (n ??= 2147483647, 2 > n) return 0; + var o = t; + n = (n -= 2) < 2 * e.length ? n / 2 : e.length; + for (var u = 0; u < n; ++u) { + var c = e.charCodeAt(u); + (d(), De)[t >>> 1 >>> 0] = c, t += 2; + } + return (d(), De)[t >>> 1 >>> 0] = 0, t - o; + }, Si = (e) => 2 * e.length, xi = (e, t, n) => { + var o = ""; + e >>>= 2; + for (var u = 0; !(u >= t / 4); u++) { + var c = (d(), E)[e + u >>> 0]; + if (!c && !n) break; + o += String.fromCodePoint(c); + } + return o; + }, Ai = (e, t, n) => { + if (t >>>= 0, n ??= 2147483647, 4 > n) return 0; + var o = t; + n = o + n - 4; + for (var u = 0; u < e.length; ++u) { + var c = e.codePointAt(u); + if (65535 < c && u++, (d(), I)[t >>> 2 >>> 0] = c, (t += 4) + 4 > n) break; + } + return (d(), I)[t >>> 2 >>> 0] = 0, t - o; + }, Ii = (e) => { + for (var t = 0, n = 0; n < e.length; ++n) 65535 < e.codePointAt(n) && n++, t += 4; + return t; + }; + function Li(e, t, n) { + if (e >>>= 0, t >>>= 0, n = Oe(n >>>= 0), t === 2) var o = vi, u = Ei, c = Si; + else o = xi, u = Ai, c = Ii; + Pe(e, { name: n, Wc: (h) => { + var m = (d(), E)[h >>> 2 >>> 0]; + return m = o(h + 4, m * t, true), ve(h), m; + }, cd: (h, m) => { + if (typeof m != "string") throw new pt(`Cannot pass non-string to C++ string type ${n}`); + var y = c(m), x = Ke(4 + y + t); + return (d(), E)[x >>> 2 >>> 0] = y / t, u(m, x + 4, y + t), h !== null && h.push(ve, x), x; + }, bd: Lr, dd(h) { + ve(h); + } }); + } + function Bi(e, t) { + Pe(e >>>= 0, { we: true, name: t = Oe(t >>> 0), Wc: () => { + }, cd: () => { + } }); + } + function Oi(e) { + zr(e >>> 0, !f, 1, !s, 131072, false), wn(); + } + var me = (e) => { + if (!$) try { + if (e(), !(0 < z)) try { + i ? zt() && Vr(A) : vr(A); + } catch (t) { + t instanceof Tt || t == "unwind" || g(0, t); + } + } catch (t) { + t instanceof Tt || t == "unwind" || g(0, t); } - - /** - * Decodes the given frames into an output audio waveform. - * @param {Record} inputs The encoded audio codes. - * @returns {Promise<{audio_values: Tensor}>} The output tensor of shape `(batch_size, num_channels, sequence_length)`. - */ - async decode(inputs) { - return await sessionRun(this.sessions['decoder_model'], inputs); + }, Mi = !Atomics.waitAsync || globalThis.navigator?.userAgent && 91 > Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) || [])[2]); + function Br(e) { + e >>>= 0, Mi || (Atomics.waitAsync((d(), I), e >>> 2, e).value.then(_t), e += 128, Atomics.store((d(), I), e >>> 2, 1)); + } + var _t = () => me(() => { + var e = zt(); + e && (Br(e), ko()); + }); + function Ci(e, t) { + (e >>>= 0) == t >>> 0 ? setTimeout(_t) : i ? postMessage({ gd: e, $c: "checkMailbox" }) : (e = Je[e]) && e.postMessage({ $c: "checkMailbox" }); + } + var Or = []; + function Di(e, t, n, o, u) { + for (t >>>= 0, u >>>= 0, Or.length = 0, n = u >>> 3, o = u + o >>> 3; n < o; ) { + var c; + c = (d(), pe)[n++ >>> 0] ? (d(), pe)[n++ >>> 0] : (d(), ae)[n++ >>> 0], Or.push(c); } -} - -class SnacEncoderModel extends SnacPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'encoder_model', - }); + return (t ? Yr[t] : xf[e])(...Or); + } + var Pi = () => { + z = 0; + }; + function Ui(e) { + e >>>= 0, i ? postMessage({ $c: "cleanupThread", Le: e }) : yn(Je[e]); + } + function _i(e) { + } + var Rt = (e) => { + try { + e(); + } catch (t) { + we(t); } -} -class SnacDecoderModel extends SnacPreTrainedModel { - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options = {}) { - return super.from_pretrained(pretrained_model_name_or_path, { - ...options, - // Update default model file name if not provided - model_file_name: options.model_file_name ?? 'decoder_model', - }); + }; + function Ri(e) { + var t = (...n) => { + Nt.push(e); + try { + return e(...n); + } finally { + $ || (Nt.pop(), Me && Ge === 1 && Nt.length === 0 && (Ge = 0, z += 1, Rt(Oa), typeof Fibers < "u" && Fibers.We())); + } + }; + return qn.set(e, t), t; + } + var Ge = 0, Me = null, jn = 0, Nt = [], Mr = /* @__PURE__ */ new Map(), Hn = /* @__PURE__ */ new Map(), qn = /* @__PURE__ */ new Map(), Ni = 0, Cr = null, Wi = [], Yn = (e) => (function(t) { + if (!$) { + if (Ge === 0) { + var n = false, o = false; + t((u = 0) => { + if (!$ && (jn = u, n = true, o)) { + Ge = 2, Rt(() => Ma(Me)), typeof MainLoop < "u" && MainLoop.se && MainLoop.resume(), u = false; + try { + var c = (function() { + var y = (d(), I)[Me + 8 >>> 2 >>> 0]; + return y = Hn.get(y), y = qn.get(y), --z, y(); + })(); + } catch (y) { + c = y, u = true; + } + var h = false; + if (!Me) { + var m = Cr; + m && (Cr = null, (u ? m.reject : m.resolve)(c), h = true); + } + if (u && !h) throw c; + } + }), o = true, n || (Ge = 1, Me = (function() { + var u = Ke(65548), c = u + 12; + if ((d(), E)[u >>> 2 >>> 0] = c, (d(), E)[u + 4 >>> 2 >>> 0] = c + 65536, c = Nt[0], !Mr.has(c)) { + var h = Ni++; + Mr.set(c, h), Hn.set(h, c); + } + return c = Mr.get(c), (d(), I)[u + 8 >>> 2 >>> 0] = c, u; + })(), typeof MainLoop < "u" && MainLoop.se && MainLoop.pause(), Rt(() => Ba(Me))); + } else Ge === 2 ? (Ge = 0, Rt(Ca), ve(Me), Me = null, Wi.forEach(me)) : we(`invalid state: ${Ge}`); + return jn; } -} -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -// AutoModels, used to simplify construction of PreTrainedModels -// (uses config to instantiate correct class) - -/** - * Base class of all AutoModels. Contains the `from_pretrained` function - * which is used to instantiate pretrained models. - */ -class PretrainedMixin { - /** - * Mapping from model type to model class. - * @type {Map[]} - */ - static MODEL_CLASS_MAPPINGS = null; - - /** - * Whether to attempt to instantiate the base class (`PretrainedModel`) if - * the model type is not found in the mapping. - */ - static BASE_IF_FAIL = false; - - - /** @type {typeof PreTrainedModel.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = 'main', - model_file_name = null, - subfolder = 'onnx', - device = null, - dtype = null, - use_external_data_format = null, - session_options = {}, - } = {}) { - - const options = { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - model_file_name, - subfolder, - device, - dtype, - use_external_data_format, - session_options, - } - options.config = await _configs_js__WEBPACK_IMPORTED_MODULE_0__.AutoConfig.from_pretrained(pretrained_model_name_or_path, options); - - if (!this.MODEL_CLASS_MAPPINGS) { - throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); - } - const model_type = options.config.model_type; - for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) { - let modelInfo = MODEL_CLASS_MAPPING.get(model_type); - if (!modelInfo) { - // As a fallback, we check if model_type is specified as the exact class - for (const cls of MODEL_CLASS_MAPPING.values()) { - if (cls[0] === model_type) { - modelInfo = cls; - break; - } - } - if (!modelInfo) continue; // Item not found in this mapping - } - return await modelInfo[1].from_pretrained(pretrained_model_name_or_path, options); - } - - if (this.BASE_IF_FAIL) { - if (!(CUSTOM_ARCHITECTURES.has(model_type))) { - console.warn(`Unknown model class "${model_type}", attempting to construct from base class.`); - } - return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options); - } else { - throw Error(`Unsupported model type: ${model_type}`) - } - } -} - -const MODEL_MAPPING_NAMES_ENCODER_ONLY = new Map([ - ['bert', ['BertModel', BertModel]], - ['neobert', ['NeoBertModel', NeoBertModel]], - ['modernbert', ['ModernBertModel', ModernBertModel]], - ['nomic_bert', ['NomicBertModel', NomicBertModel]], - ['roformer', ['RoFormerModel', RoFormerModel]], - ['electra', ['ElectraModel', ElectraModel]], - ['esm', ['EsmModel', EsmModel]], - ['convbert', ['ConvBertModel', ConvBertModel]], - ['camembert', ['CamembertModel', CamembertModel]], - ['deberta', ['DebertaModel', DebertaModel]], - ['deberta-v2', ['DebertaV2Model', DebertaV2Model]], - ['mpnet', ['MPNetModel', MPNetModel]], - ['albert', ['AlbertModel', AlbertModel]], - ['distilbert', ['DistilBertModel', DistilBertModel]], - ['roberta', ['RobertaModel', RobertaModel]], - ['xlm', ['XLMModel', XLMModel]], - ['xlm-roberta', ['XLMRobertaModel', XLMRobertaModel]], - ['clap', ['ClapModel', ClapModel]], - ['clip', ['CLIPModel', CLIPModel]], - ['clipseg', ['CLIPSegModel', CLIPSegModel]], - ['chinese_clip', ['ChineseCLIPModel', ChineseCLIPModel]], - ['siglip', ['SiglipModel', SiglipModel]], - ['jina_clip', ['JinaCLIPModel', JinaCLIPModel]], - ['mobilebert', ['MobileBertModel', MobileBertModel]], - ['squeezebert', ['SqueezeBertModel', SqueezeBertModel]], - ['wav2vec2', ['Wav2Vec2Model', Wav2Vec2Model]], - ['wav2vec2-bert', ['Wav2Vec2BertModel', Wav2Vec2BertModel]], - ['unispeech', ['UniSpeechModel', UniSpeechModel]], - ['unispeech-sat', ['UniSpeechSatModel', UniSpeechSatModel]], - ['hubert', ['HubertModel', HubertModel]], - ['wavlm', ['WavLMModel', WavLMModel]], - ['audio-spectrogram-transformer', ['ASTModel', ASTModel]], - ['vits', ['VitsModel', VitsModel]], - ['pyannote', ['PyAnnoteModel', PyAnnoteModel]], - ['wespeaker-resnet', ['WeSpeakerResNetModel', WeSpeakerResNetModel]], - - ['detr', ['DetrModel', DetrModel]], - ['rt_detr', ['RTDetrModel', RTDetrModel]], - ['rt_detr_v2', ['RTDetrV2Model', RTDetrV2Model]], - ['rf_detr', ['RFDetrModel', RFDetrModel]], - ['d_fine', ['DFineModel', DFineModel]], - ['table-transformer', ['TableTransformerModel', TableTransformerModel]], - ['vit', ['ViTModel', ViTModel]], - ['ijepa', ['IJepaModel', IJepaModel]], - ['pvt', ['PvtModel', PvtModel]], - ['vit_msn', ['ViTMSNModel', ViTMSNModel]], - ['vit_mae', ['ViTMAEModel', ViTMAEModel]], - ['groupvit', ['GroupViTModel', GroupViTModel]], - ['fastvit', ['FastViTModel', FastViTModel]], - ['mobilevit', ['MobileViTModel', MobileViTModel]], - ['mobilevitv2', ['MobileViTV2Model', MobileViTV2Model]], - ['owlvit', ['OwlViTModel', OwlViTModel]], - ['owlv2', ['Owlv2Model', Owlv2Model]], - ['beit', ['BeitModel', BeitModel]], - ['deit', ['DeiTModel', DeiTModel]], - ['hiera', ['HieraModel', HieraModel]], - ['convnext', ['ConvNextModel', ConvNextModel]], - ['convnextv2', ['ConvNextV2Model', ConvNextV2Model]], - ['dinov2', ['Dinov2Model', Dinov2Model]], - ['dinov2_with_registers', ['Dinov2WithRegistersModel', Dinov2WithRegistersModel]], - ['dinov3_vit', ['DINOv3ViTModel', DINOv3ViTModel]], - ['dinov3_convnext', ['DINOv3ConvNextModel', DINOv3ConvNextModel]], - ['resnet', ['ResNetModel', ResNetModel]], - ['swin', ['SwinModel', SwinModel]], - ['swin2sr', ['Swin2SRModel', Swin2SRModel]], - ['donut-swin', ['DonutSwinModel', DonutSwinModel]], - ['yolos', ['YolosModel', YolosModel]], - ['dpt', ['DPTModel', DPTModel]], - ['glpn', ['GLPNModel', GLPNModel]], - - ['hifigan', ['SpeechT5HifiGan', SpeechT5HifiGan]], - ['efficientnet', ['EfficientNetModel', EfficientNetModel]], - - ['decision_transformer', ['DecisionTransformerModel', DecisionTransformerModel]], - ['patchtst', ['PatchTSTForPrediction', PatchTSTModel]], - ['patchtsmixer', ['PatchTSMixerForPrediction', PatchTSMixerModel]], - - ['mobilenet_v1', ['MobileNetV1Model', MobileNetV1Model]], - ['mobilenet_v2', ['MobileNetV2Model', MobileNetV2Model]], - ['mobilenet_v3', ['MobileNetV3Model', MobileNetV3Model]], - ['mobilenet_v4', ['MobileNetV4Model', MobileNetV4Model]], - - ['maskformer', ['MaskFormerModel', MaskFormerModel]], - ['mgp-str', ['MgpstrForSceneTextRecognition', MgpstrForSceneTextRecognition]], - - ['style_text_to_speech_2', ['StyleTextToSpeech2Model', StyleTextToSpeech2Model]], -]); - -const MODEL_MAPPING_NAMES_ENCODER_DECODER = new Map([ - ['t5', ['T5Model', T5Model]], - ['longt5', ['LongT5Model', LongT5Model]], - ['mt5', ['MT5Model', MT5Model]], - ['bart', ['BartModel', BartModel]], - ['mbart', ['MBartModel', MBartModel]], - ['marian', ['MarianModel', MarianModel]], - ['whisper', ['WhisperModel', WhisperModel]], - ['m2m_100', ['M2M100Model', M2M100Model]], - ['blenderbot', ['BlenderbotModel', BlenderbotModel]], - ['blenderbot-small', ['BlenderbotSmallModel', BlenderbotSmallModel]], -]); - -const MODEL_MAPPING_NAMES_AUTO_ENCODER = new Map([ - ['mimi', ['MimiModel', MimiModel]], - ['dac', ['DacModel', DacModel]], - ['snac', ['SnacModel', SnacModel]], -]); - -const MODEL_MAPPING_NAMES_DECODER_ONLY = new Map([ - ['bloom', ['BloomModel', BloomModel]], - ['jais', ['JAISModel', JAISModel]], - ['gpt2', ['GPT2Model', GPT2Model]], - ['gptj', ['GPTJModel', GPTJModel]], - ['gpt_bigcode', ['GPTBigCodeModel', GPTBigCodeModel]], - ['gpt_neo', ['GPTNeoModel', GPTNeoModel]], - ['gpt_neox', ['GPTNeoXModel', GPTNeoXModel]], - ['codegen', ['CodeGenModel', CodeGenModel]], - ['llama', ['LlamaModel', LlamaModel]], - ['arcee', ['ArceeModel', ArceeModel]], - ['lfm2', ['Lfm2Model', Lfm2Model]], - ['smollm3', ['SmolLM3Model', SmolLM3Model]], - ['exaone', ['ExaoneModel', ExaoneModel]], - ['olmo', ['OlmoModel', OlmoModel]], - ['olmo2', ['Olmo2Model', Olmo2Model]], - ['mobilellm', ['MobileLLMModel', MobileLLMModel]], - ['granite', ['GraniteModel', GraniteModel]], - ['cohere', ['CohereModel', CohereModel]], - ['gemma', ['GemmaModel', GemmaModel]], - ['gemma2', ['Gemma2Model', Gemma2Model]], - ['gemma3_text', ['Gemma3Model', Gemma3Model]], - ['helium', ['HeliumModel', HeliumModel]], - ['glm', ['GlmModel', GlmModel]], - ['openelm', ['OpenELMModel', OpenELMModel]], - ['qwen2', ['Qwen2Model', Qwen2Model]], - ['qwen3', ['Qwen3Model', Qwen3Model]], - ['phi', ['PhiModel', PhiModel]], - ['phi3', ['Phi3Model', Phi3Model]], - ['mpt', ['MptModel', MptModel]], - ['opt', ['OPTModel', OPTModel]], - ['mistral', ['MistralModel', MistralModel]], - ['ernie4_5', ['Ernie4_5_Model', Ernie4_5_Model]], - ['starcoder2', ['Starcoder2Model', Starcoder2Model]], - ['falcon', ['FalconModel', FalconModel]], - ['stablelm', ['StableLmModel', StableLmModel]], - ['modernbert-decoder', ['ModernBertDecoderModel', ModernBertDecoderModel]], -]); - -const MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = new Map([ - ['speecht5', ['SpeechT5ForSpeechToText', SpeechT5ForSpeechToText]], - ['whisper', ['WhisperForConditionalGeneration', WhisperForConditionalGeneration]], - ['lite-whisper', ['LiteWhisperForConditionalGeneration', LiteWhisperForConditionalGeneration]], - ['moonshine', ['MoonshineForConditionalGeneration', MoonshineForConditionalGeneration]], -]); - -const MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = new Map([ - ['speecht5', ['SpeechT5ForTextToSpeech', SpeechT5ForTextToSpeech]], -]); - -const MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = new Map([ - ['vits', ['VitsModel', VitsModel]], - ['musicgen', ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration]], -]); - -const MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['bert', ['BertForSequenceClassification', BertForSequenceClassification]], - ['neobert', ['NeoBertForSequenceClassification', NeoBertForSequenceClassification]], - ['modernbert', ['ModernBertForSequenceClassification', ModernBertForSequenceClassification]], - ['roformer', ['RoFormerForSequenceClassification', RoFormerForSequenceClassification]], - ['electra', ['ElectraForSequenceClassification', ElectraForSequenceClassification]], - ['esm', ['EsmForSequenceClassification', EsmForSequenceClassification]], - ['convbert', ['ConvBertForSequenceClassification', ConvBertForSequenceClassification]], - ['camembert', ['CamembertForSequenceClassification', CamembertForSequenceClassification]], - ['deberta', ['DebertaForSequenceClassification', DebertaForSequenceClassification]], - ['deberta-v2', ['DebertaV2ForSequenceClassification', DebertaV2ForSequenceClassification]], - ['mpnet', ['MPNetForSequenceClassification', MPNetForSequenceClassification]], - ['albert', ['AlbertForSequenceClassification', AlbertForSequenceClassification]], - ['distilbert', ['DistilBertForSequenceClassification', DistilBertForSequenceClassification]], - ['roberta', ['RobertaForSequenceClassification', RobertaForSequenceClassification]], - ['xlm', ['XLMForSequenceClassification', XLMForSequenceClassification]], - ['xlm-roberta', ['XLMRobertaForSequenceClassification', XLMRobertaForSequenceClassification]], - ['bart', ['BartForSequenceClassification', BartForSequenceClassification]], - ['mbart', ['MBartForSequenceClassification', MBartForSequenceClassification]], - ['mobilebert', ['MobileBertForSequenceClassification', MobileBertForSequenceClassification]], - ['squeezebert', ['SqueezeBertForSequenceClassification', SqueezeBertForSequenceClassification]], -]); - -const MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['bert', ['BertForTokenClassification', BertForTokenClassification]], - ['neobert', ['NeoBertForTokenClassification', NeoBertForTokenClassification]], - ['modernbert', ['ModernBertForTokenClassification', ModernBertForTokenClassification]], - ['roformer', ['RoFormerForTokenClassification', RoFormerForTokenClassification]], - ['electra', ['ElectraForTokenClassification', ElectraForTokenClassification]], - ['esm', ['EsmForTokenClassification', EsmForTokenClassification]], - ['convbert', ['ConvBertForTokenClassification', ConvBertForTokenClassification]], - ['camembert', ['CamembertForTokenClassification', CamembertForTokenClassification]], - ['deberta', ['DebertaForTokenClassification', DebertaForTokenClassification]], - ['deberta-v2', ['DebertaV2ForTokenClassification', DebertaV2ForTokenClassification]], - ['mpnet', ['MPNetForTokenClassification', MPNetForTokenClassification]], - ['distilbert', ['DistilBertForTokenClassification', DistilBertForTokenClassification]], - ['roberta', ['RobertaForTokenClassification', RobertaForTokenClassification]], - ['xlm', ['XLMForTokenClassification', XLMForTokenClassification]], - ['xlm-roberta', ['XLMRobertaForTokenClassification', XLMRobertaForTokenClassification]], -]); - -const MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = new Map([ - ['t5', ['T5ForConditionalGeneration', T5ForConditionalGeneration]], - ['longt5', ['LongT5ForConditionalGeneration', LongT5ForConditionalGeneration]], - ['mt5', ['MT5ForConditionalGeneration', MT5ForConditionalGeneration]], - ['bart', ['BartForConditionalGeneration', BartForConditionalGeneration]], - ['mbart', ['MBartForConditionalGeneration', MBartForConditionalGeneration]], - ['marian', ['MarianMTModel', MarianMTModel]], - ['m2m_100', ['M2M100ForConditionalGeneration', M2M100ForConditionalGeneration]], - ['blenderbot', ['BlenderbotForConditionalGeneration', BlenderbotForConditionalGeneration]], - ['blenderbot-small', ['BlenderbotSmallForConditionalGeneration', BlenderbotSmallForConditionalGeneration]], -]); - -const MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = new Map([ - ['bloom', ['BloomForCausalLM', BloomForCausalLM]], - ['gpt2', ['GPT2LMHeadModel', GPT2LMHeadModel]], - ['jais', ['JAISLMHeadModel', JAISLMHeadModel]], - ['gptj', ['GPTJForCausalLM', GPTJForCausalLM]], - ['gpt_bigcode', ['GPTBigCodeForCausalLM', GPTBigCodeForCausalLM]], - ['gpt_neo', ['GPTNeoForCausalLM', GPTNeoForCausalLM]], - ['gpt_neox', ['GPTNeoXForCausalLM', GPTNeoXForCausalLM]], - ['codegen', ['CodeGenForCausalLM', CodeGenForCausalLM]], - ['llama', ['LlamaForCausalLM', LlamaForCausalLM]], - ['arcee', ['ArceeForCausalLM', ArceeForCausalLM]], - ['lfm2', ['Lfm2ForCausalLM', Lfm2ForCausalLM]], - ['smollm3', ['SmolLM3ForCausalLM', SmolLM3ForCausalLM]], - ['exaone', ['ExaoneForCausalLM', ExaoneForCausalLM]], - ['olmo', ['OlmoForCausalLM', OlmoForCausalLM]], - ['olmo2', ['Olmo2ForCausalLM', Olmo2ForCausalLM]], - ['mobilellm', ['MobileLLMForCausalLM', MobileLLMForCausalLM]], - ['granite', ['GraniteForCausalLM', GraniteForCausalLM]], - ['cohere', ['CohereForCausalLM', CohereForCausalLM]], - ['gemma', ['GemmaForCausalLM', GemmaForCausalLM]], - ['gemma2', ['Gemma2ForCausalLM', Gemma2ForCausalLM]], - ['gemma3_text', ['Gemma3ForCausalLM', Gemma3ForCausalLM]], - ['helium', ['HeliumForCausalLM', HeliumForCausalLM]], - ['glm', ['GlmForCausalLM', GlmForCausalLM]], - ['openelm', ['OpenELMForCausalLM', OpenELMForCausalLM]], - ['qwen2', ['Qwen2ForCausalLM', Qwen2ForCausalLM]], - ['qwen3', ['Qwen3ForCausalLM', Qwen3ForCausalLM]], - ['phi', ['PhiForCausalLM', PhiForCausalLM]], - ['phi3', ['Phi3ForCausalLM', Phi3ForCausalLM]], - ['mpt', ['MptForCausalLM', MptForCausalLM]], - ['opt', ['OPTForCausalLM', OPTForCausalLM]], - ['mbart', ['MBartForCausalLM', MBartForCausalLM]], - ['mistral', ['MistralForCausalLM', MistralForCausalLM]], - ['ernie4_5', ['Ernie4_5_ForCausalLM', Ernie4_5_ForCausalLM]], - ['starcoder2', ['Starcoder2ForCausalLM', Starcoder2ForCausalLM]], - ['falcon', ['FalconForCausalLM', FalconForCausalLM]], - ['trocr', ['TrOCRForCausalLM', TrOCRForCausalLM]], - ['stablelm', ['StableLmForCausalLM', StableLmForCausalLM]], - ['modernbert-decoder', ['ModernBertDecoderForCausalLM', ModernBertDecoderForCausalLM]], - - // Also image-text-to-text - ['phi3_v', ['Phi3VForCausalLM', Phi3VForCausalLM]], -]); - -const MODEL_FOR_MULTIMODALITY_MAPPING_NAMES = new Map([ - ['multi_modality', ['MultiModalityCausalLM', MultiModalityCausalLM]], -]); - - -const MODEL_FOR_MASKED_LM_MAPPING_NAMES = new Map([ - ['bert', ['BertForMaskedLM', BertForMaskedLM]], - ['neobert', ['NeoBertForMaskedLM', NeoBertForMaskedLM]], - ['modernbert', ['ModernBertForMaskedLM', ModernBertForMaskedLM]], - ['roformer', ['RoFormerForMaskedLM', RoFormerForMaskedLM]], - ['electra', ['ElectraForMaskedLM', ElectraForMaskedLM]], - ['esm', ['EsmForMaskedLM', EsmForMaskedLM]], - ['convbert', ['ConvBertForMaskedLM', ConvBertForMaskedLM]], - ['camembert', ['CamembertForMaskedLM', CamembertForMaskedLM]], - ['deberta', ['DebertaForMaskedLM', DebertaForMaskedLM]], - ['deberta-v2', ['DebertaV2ForMaskedLM', DebertaV2ForMaskedLM]], - ['mpnet', ['MPNetForMaskedLM', MPNetForMaskedLM]], - ['albert', ['AlbertForMaskedLM', AlbertForMaskedLM]], - ['distilbert', ['DistilBertForMaskedLM', DistilBertForMaskedLM]], - ['roberta', ['RobertaForMaskedLM', RobertaForMaskedLM]], - ['xlm', ['XLMWithLMHeadModel', XLMWithLMHeadModel]], - ['xlm-roberta', ['XLMRobertaForMaskedLM', XLMRobertaForMaskedLM]], - ['mobilebert', ['MobileBertForMaskedLM', MobileBertForMaskedLM]], - ['squeezebert', ['SqueezeBertForMaskedLM', SqueezeBertForMaskedLM]], -]); - -const MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = new Map([ - ['bert', ['BertForQuestionAnswering', BertForQuestionAnswering]], - ['neobert', ['NeoBertForQuestionAnswering', NeoBertForQuestionAnswering]], - ['roformer', ['RoFormerForQuestionAnswering', RoFormerForQuestionAnswering]], - ['electra', ['ElectraForQuestionAnswering', ElectraForQuestionAnswering]], - ['convbert', ['ConvBertForQuestionAnswering', ConvBertForQuestionAnswering]], - ['camembert', ['CamembertForQuestionAnswering', CamembertForQuestionAnswering]], - ['deberta', ['DebertaForQuestionAnswering', DebertaForQuestionAnswering]], - ['deberta-v2', ['DebertaV2ForQuestionAnswering', DebertaV2ForQuestionAnswering]], - ['mpnet', ['MPNetForQuestionAnswering', MPNetForQuestionAnswering]], - ['albert', ['AlbertForQuestionAnswering', AlbertForQuestionAnswering]], - ['distilbert', ['DistilBertForQuestionAnswering', DistilBertForQuestionAnswering]], - ['roberta', ['RobertaForQuestionAnswering', RobertaForQuestionAnswering]], - ['xlm', ['XLMForQuestionAnswering', XLMForQuestionAnswering]], - ['xlm-roberta', ['XLMRobertaForQuestionAnswering', XLMRobertaForQuestionAnswering]], - ['mobilebert', ['MobileBertForQuestionAnswering', MobileBertForQuestionAnswering]], - ['squeezebert', ['SqueezeBertForQuestionAnswering', SqueezeBertForQuestionAnswering]], -]); - -const MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = new Map([ - ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]], - ['idefics3', ['Idefics3ForConditionalGeneration', Idefics3ForConditionalGeneration]], - ['smolvlm', ['SmolVLMForConditionalGeneration', SmolVLMForConditionalGeneration]], -]); - -const MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = new Map([ - ['llava', ['LlavaForConditionalGeneration', LlavaForConditionalGeneration]], - ['llava_onevision', ['LlavaOnevisionForConditionalGeneration', LlavaOnevisionForConditionalGeneration]], - ['moondream1', ['Moondream1ForConditionalGeneration', Moondream1ForConditionalGeneration]], - ['florence2', ['Florence2ForConditionalGeneration', Florence2ForConditionalGeneration]], - ['qwen2-vl', ['Qwen2VLForConditionalGeneration', Qwen2VLForConditionalGeneration]], - ['idefics3', ['Idefics3ForConditionalGeneration', Idefics3ForConditionalGeneration]], - ['smolvlm', ['SmolVLMForConditionalGeneration', SmolVLMForConditionalGeneration]], - ['paligemma', ['PaliGemmaForConditionalGeneration', PaliGemmaForConditionalGeneration]], - ['llava_qwen2', ['LlavaQwen2ForCausalLM', LlavaQwen2ForCausalLM]], - ['gemma3n', ['Gemma3nForConditionalGeneration', Gemma3nForConditionalGeneration]], -]); - -const MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES = new Map([ - ['ultravox', ['UltravoxModel', UltravoxModel]], - ['voxtral', ['VoxtralForConditionalGeneration', VoxtralForConditionalGeneration]], -]); - - -const MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = new Map([ - ['vision-encoder-decoder', ['VisionEncoderDecoderModel', VisionEncoderDecoderModel]], -]); - -const MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['vit', ['ViTForImageClassification', ViTForImageClassification]], - ['ijepa', ['IJepaForImageClassification', IJepaForImageClassification]], - ['pvt', ['PvtForImageClassification', PvtForImageClassification]], - ['vit_msn', ['ViTMSNForImageClassification', ViTMSNForImageClassification]], - ['fastvit', ['FastViTForImageClassification', FastViTForImageClassification]], - ['mobilevit', ['MobileViTForImageClassification', MobileViTForImageClassification]], - ['mobilevitv2', ['MobileViTV2ForImageClassification', MobileViTV2ForImageClassification]], - ['beit', ['BeitForImageClassification', BeitForImageClassification]], - ['deit', ['DeiTForImageClassification', DeiTForImageClassification]], - ['hiera', ['HieraForImageClassification', HieraForImageClassification]], - ['convnext', ['ConvNextForImageClassification', ConvNextForImageClassification]], - ['convnextv2', ['ConvNextV2ForImageClassification', ConvNextV2ForImageClassification]], - ['dinov2', ['Dinov2ForImageClassification', Dinov2ForImageClassification]], - ['dinov2_with_registers', ['Dinov2WithRegistersForImageClassification', Dinov2WithRegistersForImageClassification]], - ['resnet', ['ResNetForImageClassification', ResNetForImageClassification]], - ['swin', ['SwinForImageClassification', SwinForImageClassification]], - ['segformer', ['SegformerForImageClassification', SegformerForImageClassification]], - ['efficientnet', ['EfficientNetForImageClassification', EfficientNetForImageClassification]], - ['mobilenet_v1', ['MobileNetV1ForImageClassification', MobileNetV1ForImageClassification]], - ['mobilenet_v2', ['MobileNetV2ForImageClassification', MobileNetV2ForImageClassification]], - ['mobilenet_v3', ['MobileNetV3ForImageClassification', MobileNetV3ForImageClassification]], - ['mobilenet_v4', ['MobileNetV4ForImageClassification', MobileNetV4ForImageClassification]], -]); - -const MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = new Map([ - ['detr', ['DetrForObjectDetection', DetrForObjectDetection]], - ['rt_detr', ['RTDetrForObjectDetection', RTDetrForObjectDetection]], - ['rt_detr_v2', ['RTDetrV2ForObjectDetection', RTDetrV2ForObjectDetection]], - ['rf_detr', ['RFDetrForObjectDetection', RFDetrForObjectDetection]], - ['d_fine', ['DFineForObjectDetection', DFineForObjectDetection]], - ['table-transformer', ['TableTransformerForObjectDetection', TableTransformerForObjectDetection]], - ['yolos', ['YolosForObjectDetection', YolosForObjectDetection]], -]); - -const MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = new Map([ - ['owlvit', ['OwlViTForObjectDetection', OwlViTForObjectDetection]], - ['owlv2', ['Owlv2ForObjectDetection', Owlv2ForObjectDetection]], - ['grounding-dino', ['GroundingDinoForObjectDetection', GroundingDinoForObjectDetection]], -]); - -const MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = new Map([ - // TODO: Do not add new models here - ['detr', ['DetrForSegmentation', DetrForSegmentation]], - ['clipseg', ['CLIPSegForImageSegmentation', CLIPSegForImageSegmentation]], -]); - -const MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = new Map([ - ['segformer', ['SegformerForSemanticSegmentation', SegformerForSemanticSegmentation]], - ['sapiens', ['SapiensForSemanticSegmentation', SapiensForSemanticSegmentation]], - - ['swin', ['SwinForSemanticSegmentation', SwinForSemanticSegmentation]], - ['mobilenet_v1', ['MobileNetV1ForSemanticSegmentation', MobileNetV1ForSemanticSegmentation]], - ['mobilenet_v2', ['MobileNetV2ForSemanticSegmentation', MobileNetV2ForSemanticSegmentation]], - ['mobilenet_v3', ['MobileNetV3ForSemanticSegmentation', MobileNetV3ForSemanticSegmentation]], - ['mobilenet_v4', ['MobileNetV4ForSemanticSegmentation', MobileNetV4ForSemanticSegmentation]], -]); - -const MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = new Map([ - ['detr', ['DetrForSegmentation', DetrForSegmentation]], - ['maskformer', ['MaskFormerForInstanceSegmentation', MaskFormerForInstanceSegmentation]], -]); - -const MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = new Map([ - ['sam', ['SamModel', SamModel]], -]); - -const MODEL_FOR_CTC_MAPPING_NAMES = new Map([ - ['wav2vec2', ['Wav2Vec2ForCTC', Wav2Vec2ForCTC]], - ['wav2vec2-bert', ['Wav2Vec2BertForCTC', Wav2Vec2BertForCTC]], - ['unispeech', ['UniSpeechForCTC', UniSpeechForCTC]], - ['unispeech-sat', ['UniSpeechSatForCTC', UniSpeechSatForCTC]], - ['wavlm', ['WavLMForCTC', WavLMForCTC]], - ['hubert', ['HubertForCTC', HubertForCTC]], -]); - -const MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['wav2vec2', ['Wav2Vec2ForSequenceClassification', Wav2Vec2ForSequenceClassification]], - ['wav2vec2-bert', ['Wav2Vec2BertForSequenceClassification', Wav2Vec2BertForSequenceClassification]], - ['unispeech', ['UniSpeechForSequenceClassification', UniSpeechForSequenceClassification]], - ['unispeech-sat', ['UniSpeechSatForSequenceClassification', UniSpeechSatForSequenceClassification]], - ['wavlm', ['WavLMForSequenceClassification', WavLMForSequenceClassification]], - ['hubert', ['HubertForSequenceClassification', HubertForSequenceClassification]], - ['audio-spectrogram-transformer', ['ASTForAudioClassification', ASTForAudioClassification]], -]); - -const MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = new Map([ - ['wavlm', ['WavLMForXVector', WavLMForXVector]], -]); - -const MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = new Map([ - ['unispeech-sat', ['UniSpeechSatForAudioFrameClassification', UniSpeechSatForAudioFrameClassification]], - ['wavlm', ['WavLMForAudioFrameClassification', WavLMForAudioFrameClassification]], - ['wav2vec2', ['Wav2Vec2ForAudioFrameClassification', Wav2Vec2ForAudioFrameClassification]], - ['pyannote', ['PyAnnoteForAudioFrameClassification', PyAnnoteForAudioFrameClassification]], -]); - -const MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = new Map([ - ['vitmatte', ['VitMatteForImageMatting', VitMatteForImageMatting]], -]); - -const MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING_NAMES = new Map([ - ['patchtst', ['PatchTSTForPrediction', PatchTSTForPrediction]], - ['patchtsmixer', ['PatchTSMixerForPrediction', PatchTSMixerForPrediction]], -]) - -const MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = new Map([ - ['swin2sr', ['Swin2SRForImageSuperResolution', Swin2SRForImageSuperResolution]], -]) - -const MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = new Map([ - ['dpt', ['DPTForDepthEstimation', DPTForDepthEstimation]], - ['depth_anything', ['DepthAnythingForDepthEstimation', DepthAnythingForDepthEstimation]], - ['glpn', ['GLPNForDepthEstimation', GLPNForDepthEstimation]], - ['sapiens', ['SapiensForDepthEstimation', SapiensForDepthEstimation]], - ['depth_pro', ['DepthProForDepthEstimation', DepthProForDepthEstimation]], - ['metric3d', ['Metric3DForDepthEstimation', Metric3DForDepthEstimation]], - ['metric3dv2', ['Metric3Dv2ForDepthEstimation', Metric3Dv2ForDepthEstimation]], -]) - -const MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = new Map([ - ['sapiens', ['SapiensForNormalEstimation', SapiensForNormalEstimation]], -]) - -const MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES = new Map([ - ['vitpose', ['VitPoseForPoseEstimation', VitPoseForPoseEstimation]], -]) - -// NOTE: This is custom to Transformers.js, and is necessary because certain models -// (e.g., CLIP) are split into vision and text components -const MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = new Map([ - ['clip', ['CLIPVisionModelWithProjection', CLIPVisionModelWithProjection]], - ['siglip', ['SiglipVisionModel', SiglipVisionModel]], - ['jina_clip', ['JinaCLIPVisionModel', JinaCLIPVisionModel]], -]) - -const MODEL_CLASS_TYPE_MAPPING = [ - // MODEL_MAPPING_NAMES: - [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly], - [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder], - [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly], - [MODEL_MAPPING_NAMES_AUTO_ENCODER, MODEL_TYPES.AutoEncoder], - - [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], - [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], - [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly], - [MODEL_FOR_MULTIMODALITY_MAPPING_NAMES, MODEL_TYPES.MultiModality], - [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq], - [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText], - [MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.AudioTextToText], - [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration], - [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], - [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], - - // Custom: - [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], -]; - -for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) { - // @ts-ignore - for (const [name, model] of mappings.values()) { - MODEL_TYPE_MAPPING.set(name, type); - MODEL_CLASS_TO_NAME_MAPPING.set(model, name); - MODEL_NAME_TO_CLASS_MAPPING.set(name, model); - } -} - -const CUSTOM_MAPPING = [ - // OVERRIDE: - // TODO: Refactor to allow class to specify model - ['MusicgenForConditionalGeneration', MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen], - ['Phi3VForCausalLM', Phi3VForCausalLM, MODEL_TYPES.Phi3V], - - ['CLIPTextModelWithProjection', CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], - ['SiglipTextModel', SiglipTextModel, MODEL_TYPES.EncoderOnly], - ['JinaCLIPTextModel', JinaCLIPTextModel, MODEL_TYPES.EncoderOnly], - ['ClapTextModelWithProjection', ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], - ['ClapAudioModelWithProjection', ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly], - - ['DacEncoderModel', DacEncoderModel, MODEL_TYPES.EncoderOnly], - ['DacDecoderModel', DacDecoderModel, MODEL_TYPES.EncoderOnly], - ['MimiEncoderModel', MimiEncoderModel, MODEL_TYPES.EncoderOnly], - ['MimiDecoderModel', MimiDecoderModel, MODEL_TYPES.EncoderOnly], - ['SnacEncoderModel', SnacEncoderModel, MODEL_TYPES.EncoderOnly], - ['SnacDecoderModel', SnacDecoderModel, MODEL_TYPES.EncoderOnly], - - ['Gemma3nForConditionalGeneration', Gemma3nForConditionalGeneration, MODEL_TYPES.ImageAudioTextToText], -] -for (const [name, model, type] of CUSTOM_MAPPING) { - MODEL_TYPE_MAPPING.set(name, type); - MODEL_CLASS_TO_NAME_MAPPING.set(model, name); - MODEL_NAME_TO_CLASS_MAPPING.set(name, model); -} - -const CUSTOM_ARCHITECTURES = new Map([ - ['modnet', MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], - ['birefnet', MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], - ['isnet', MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], - ['ben', MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], -]); -for (const [name, mapping] of CUSTOM_ARCHITECTURES.entries()) { - mapping.set(name, ['PreTrainedModel', PreTrainedModel]) - MODEL_TYPE_MAPPING.set(name, MODEL_TYPES.EncoderOnly); - MODEL_CLASS_TO_NAME_MAPPING.set(PreTrainedModel, name); - MODEL_NAME_TO_CLASS_MAPPING.set(name, PreTrainedModel); -} - - -/** - * Helper class which is used to instantiate pretrained models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModel.from_pretrained('Xenova/bert-base-uncased'); - */ -class AutoModel extends PretrainedMixin { - /** @type {Map[]} */ - // @ts-ignore - static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map(x => x[0]); - static BASE_IF_FAIL = true; -} - -/** - * Helper class which is used to instantiate pretrained sequence classification models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForSequenceClassification.from_pretrained('Xenova/distilbert-base-uncased-finetuned-sst-2-english'); - */ -class AutoModelForSequenceClassification extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained token classification models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForTokenClassification.from_pretrained('Xenova/distilbert-base-multilingual-cased-ner-hrl'); - */ -class AutoModelForTokenClassification extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained sequence-to-sequence models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForSeq2SeqLM.from_pretrained('Xenova/t5-small'); - */ -class AutoModelForSeq2SeqLM extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained sequence-to-sequence speech-to-text models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForSpeechSeq2Seq.from_pretrained('openai/whisper-tiny.en'); - */ -class AutoModelForSpeechSeq2Seq extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained sequence-to-sequence text-to-spectrogram models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForTextToSpectrogram.from_pretrained('microsoft/speecht5_tts'); - */ -class AutoModelForTextToSpectrogram extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained text-to-waveform models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForTextToSpectrogram.from_pretrained('facebook/mms-tts-eng'); - */ -class AutoModelForTextToWaveform extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained causal language models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForCausalLM.from_pretrained('Xenova/gpt2'); - */ -class AutoModelForCausalLM extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained masked language models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForMaskedLM.from_pretrained('Xenova/bert-base-uncased'); - */ -class AutoModelForMaskedLM extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASKED_LM_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained question answering models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForQuestionAnswering.from_pretrained('Xenova/distilbert-base-cased-distilled-squad'); - */ -class AutoModelForQuestionAnswering extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained vision-to-sequence models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForVision2Seq.from_pretrained('Xenova/vit-gpt2-image-captioning'); - */ -class AutoModelForVision2Seq extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained image classification models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForImageClassification.from_pretrained('Xenova/vit-base-patch16-224'); - */ -class AutoModelForImageClassification extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForImageSegmentation.from_pretrained('Xenova/detr-resnet-50-panoptic'); - */ -class AutoModelForImageSegmentation extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained image segmentation models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForSemanticSegmentation.from_pretrained('nvidia/segformer-b3-finetuned-cityscapes-1024-1024'); - */ -class AutoModelForSemanticSegmentation extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained universal image segmentation models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForUniversalSegmentation.from_pretrained('hf-internal-testing/tiny-random-MaskFormerForInstanceSegmentation'); - */ -class AutoModelForUniversalSegmentation extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]; -} - -/** - * Helper class which is used to instantiate pretrained object detection models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForObjectDetection.from_pretrained('Xenova/detr-resnet-50'); - */ -class AutoModelForObjectDetection extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]; -} - -class AutoModelForZeroShotObjectDetection extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]; -} - - -/** - * Helper class which is used to instantiate pretrained mask generation models with the `from_pretrained` function. - * The chosen model class is determined by the type specified in the model config. - * - * @example - * let model = await AutoModelForMaskGeneration.from_pretrained('Xenova/sam-vit-base'); - */ -class AutoModelForMaskGeneration extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]; -} - -class AutoModelForCTC extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_CTC_MAPPING_NAMES]; -} - -class AutoModelForAudioClassification extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]; -} - -class AutoModelForXVector extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]; -} - -class AutoModelForAudioFrameClassification extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]; -} - -class AutoModelForDocumentQuestionAnswering extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]; -} - -class AutoModelForImageMatting extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]; -} - -class AutoModelForImageToImage extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]; -} - -class AutoModelForDepthEstimation extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]; -} - -class AutoModelForNormalEstimation extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]; -} - -class AutoModelForPoseEstimation extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]; -} - -class AutoModelForImageFeatureExtraction extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]; -} - -class AutoModelForImageTextToText extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]; -} - -class AutoModelForAudioTextToText extends PretrainedMixin { - static MODEL_CLASS_MAPPINGS = [MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]; -} - -////////////////////////////////////////////////// - -////////////////////////////////////////////////// -class Seq2SeqLMOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits The output logits of the model. - * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. - * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. - * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. - * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. - */ - constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) { - super(); - this.logits = logits; - this.past_key_values = past_key_values; - this.encoder_outputs = encoder_outputs; - this.decoder_attentions = decoder_attentions; - this.cross_attentions = cross_attentions; + })((t) => { + e().then(t); + }); + function ki(e) { + return e >>>= 0, Yn(async () => { + var t = await Te(e); + return Ae(t); + }); + } + var Dr = [], Fi = (e) => { + var t = Dr.length; + return Dr.push(e), t; + }, Gi = (e, t) => { + for (var n = Array(e), o = 0; o < e; ++o) { + var u = o, c = (d(), E)[t + 4 * o >>> 2 >>> 0], h = Ar[c]; + if (h === void 0) throw e = `parameter ${o}`, c = To(c), t = Oe(c), ve(c), new pt(`${e} has unknown type ${t}`); + n[u] = h; + } + return n; + }, $i = (e, t, n) => { + var o = []; + return e = e(o, n), o.length && ((d(), E)[t >>> 2 >>> 0] = Ae(o)), e; + }, zi = {}, Wt = (e) => { + var t = zi[e]; + return t === void 0 ? Oe(e) : t; + }; + function Vi(e, t, n) { + var [o, ...u] = Gi(e, t >>> 0); + t = o.cd.bind(o); + var c = u.map((y) => y.bd.bind(y)); + e--; + var h = { toValue: Te }; + switch (e = c.map((y, x) => { + var N = `argFromPtr${x}`; + return h[N] = y, `${N}(args${x ? "+" + 8 * x : ""})`; + }), n) { + case 0: + var m = "toValue(handle)"; + break; + case 2: + m = "new (toValue(handle))"; + break; + case 3: + m = ""; + break; + case 1: + h.getStringOrSymbol = Wt, m = "toValue(handle)[getStringOrSymbol(methodName)]"; } -} - -/** - * Base class for outputs of sentence classification models. - */ -class SequenceClassifierOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). - * @param {Record} [output.attentions] Object of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. - * Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. - */ - constructor({ logits, ...attentions }) { - super(); - this.logits = logits; - const attentions_list = Object.values(attentions); - if (attentions_list.length > 0) { - // Only set attentions if they are not empty - this.attentions = attentions_list; - } + return m += `(${e})`, o.we || (h.toReturnWire = t, h.emval_returnValue = $i, m = `return emval_returnValue(toReturnWire, destructorsRef, ${m})`), m = `return function (handle, methodName, destructorsRef, args) { + ${m} + }`, n = new Function(Object.keys(h), m)(...Object.values(h)), m = `methodCaller<(${u.map((y) => y.name)}) => ${o.name}>`, Fi(Object.defineProperty(n, "name", { value: m })); + } + function ji(e, t) { + return t >>>= 0, (e = Te(e >>> 0)) == Te(t); + } + function Hi(e) { + return (e >>>= 0) ? (e = Wt(e), Ae(globalThis[e])) : Ae(globalThis); + } + function qi(e) { + return e = Wt(e >>> 0), Ae(r[e]); + } + function Yi(e, t) { + return t >>>= 0, e = Te(e >>> 0), t = Te(t), Ae(e[t]); + } + function Ji(e) { + 9 < (e >>>= 0) && (Xe[e + 1] += 1); + } + function Jn(e, t, n, o, u) { + return Dr[e >>> 0](t >>> 0, n >>> 0, o >>> 0, u >>> 0); + } + function Xi(e, t, n, o, u) { + return Jn(e >>> 0, t >>> 0, n >>> 0, o >>> 0, u >>> 0); + } + function Zi() { + return Ae([]); + } + function Ki(e) { + e = Te(e >>> 0); + for (var t = Array(e.length), n = 0; n < e.length; n++) t[n] = e[n]; + return Ae(t); + } + function Qi(e) { + return Ae(Wt(e >>> 0)); + } + function eu() { + return Ae({}); + } + function tu(e) { + for (var t = Te(e >>>= 0); t.length; ) { + var n = t.pop(); + t.pop()(n); } -} - -/** - * Base class for outputs of XVector models. - */ -class XVectorOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`. - * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`. - */ - constructor({ logits, embeddings }) { - super(); - this.logits = logits; - this.embeddings = embeddings; + Ir(e); + } + function ru(e, t, n) { + t >>>= 0, n >>>= 0, e = Te(e >>> 0), t = Te(t), n = Te(n), e[t] = n; + } + function nu(e, t) { + e = ue(e), t >>>= 0, e = new Date(1e3 * e), (d(), I)[t >>> 2 >>> 0] = e.getUTCSeconds(), (d(), I)[t + 4 >>> 2 >>> 0] = e.getUTCMinutes(), (d(), I)[t + 8 >>> 2 >>> 0] = e.getUTCHours(), (d(), I)[t + 12 >>> 2 >>> 0] = e.getUTCDate(), (d(), I)[t + 16 >>> 2 >>> 0] = e.getUTCMonth(), (d(), I)[t + 20 >>> 2 >>> 0] = e.getUTCFullYear() - 1900, (d(), I)[t + 24 >>> 2 >>> 0] = e.getUTCDay(), e = (e.getTime() - Date.UTC(e.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, (d(), I)[t + 28 >>> 2 >>> 0] = e; + } + var Xn = (e) => e % 4 == 0 && (e % 100 != 0 || e % 400 == 0), Zn = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335], Kn = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + function ou(e, t) { + e = ue(e), t >>>= 0, e = new Date(1e3 * e), (d(), I)[t >>> 2 >>> 0] = e.getSeconds(), (d(), I)[t + 4 >>> 2 >>> 0] = e.getMinutes(), (d(), I)[t + 8 >>> 2 >>> 0] = e.getHours(), (d(), I)[t + 12 >>> 2 >>> 0] = e.getDate(), (d(), I)[t + 16 >>> 2 >>> 0] = e.getMonth(), (d(), I)[t + 20 >>> 2 >>> 0] = e.getFullYear() - 1900, (d(), I)[t + 24 >>> 2 >>> 0] = e.getDay(); + var n = (Xn(e.getFullYear()) ? Zn : Kn)[e.getMonth()] + e.getDate() - 1 | 0; + (d(), I)[t + 28 >>> 2 >>> 0] = n, (d(), I)[t + 36 >>> 2 >>> 0] = -60 * e.getTimezoneOffset(), n = new Date(e.getFullYear(), 6, 1).getTimezoneOffset(); + var o = new Date(e.getFullYear(), 0, 1).getTimezoneOffset(); + e = 0 | (n != o && e.getTimezoneOffset() == Math.min(o, n)), (d(), I)[t + 32 >>> 2 >>> 0] = e; + } + function au(e) { + e >>>= 0; + var t = new Date((d(), I)[e + 20 >>> 2 >>> 0] + 1900, (d(), I)[e + 16 >>> 2 >>> 0], (d(), I)[e + 12 >>> 2 >>> 0], (d(), I)[e + 8 >>> 2 >>> 0], (d(), I)[e + 4 >>> 2 >>> 0], (d(), I)[e >>> 2 >>> 0], 0), n = (d(), I)[e + 32 >>> 2 >>> 0], o = t.getTimezoneOffset(), u = new Date(t.getFullYear(), 6, 1).getTimezoneOffset(), c = new Date(t.getFullYear(), 0, 1).getTimezoneOffset(), h = Math.min(c, u); + return 0 > n ? (d(), I)[e + 32 >>> 2 >>> 0] = +(u != c && h == o) : 0 < n != (h == o) && (u = Math.max(c, u), t.setTime(t.getTime() + 6e4 * ((0 < n ? h : u) - o))), (d(), I)[e + 24 >>> 2 >>> 0] = t.getDay(), n = (Xn(t.getFullYear()) ? Zn : Kn)[t.getMonth()] + t.getDate() - 1 | 0, (d(), I)[e + 28 >>> 2 >>> 0] = n, (d(), I)[e >>> 2 >>> 0] = t.getSeconds(), (d(), I)[e + 4 >>> 2 >>> 0] = t.getMinutes(), (d(), I)[e + 8 >>> 2 >>> 0] = t.getHours(), (d(), I)[e + 12 >>> 2 >>> 0] = t.getDate(), (d(), I)[e + 16 >>> 2 >>> 0] = t.getMonth(), (d(), I)[e + 20 >>> 2 >>> 0] = t.getYear(), e = t.getTime(), BigInt(isNaN(e) ? -1 : e / 1e3); + } + function Qn(e, t, n, o, u, c, h) { + return i ? H(16, 1, e, t, n, o, u, c, h) : -52; + } + function eo(e, t, n, o, u, c) { + if (i) return H(17, 1, e, t, n, o, u, c); + } + var Et = {}, su = () => performance.timeOrigin + performance.now(); + function to(e, t) { + if (i) return H(18, 1, e, t); + if (Et[e] && (clearTimeout(Et[e].id), delete Et[e]), !t) return 0; + var n = setTimeout(() => { + delete Et[e], me(() => Wo(e, performance.timeOrigin + performance.now())); + }, t); + return Et[e] = { id: n, Ve: t }, 0; + } + function iu(e, t, n, o) { + e >>>= 0, t >>>= 0, n >>>= 0, o >>>= 0; + var u = (/* @__PURE__ */ new Date()).getFullYear(), c = new Date(u, 0, 1).getTimezoneOffset(); + u = new Date(u, 6, 1).getTimezoneOffset(); + var h = Math.max(c, u); + (d(), E)[e >>> 2 >>> 0] = 60 * h, (d(), I)[t >>> 2 >>> 0] = +(c != u), e = (t = (m) => { + var y = Math.abs(m); + return `UTC${0 <= m ? "-" : "+"}${String(Math.floor(y / 60)).padStart(2, "0")}${String(y % 60).padStart(2, "0")}`; + })(c), t = t(u), u < c ? (Ue(e, n, 17), Ue(t, o, 17)) : (Ue(e, o, 17), Ue(t, n, 17)); + } + var uu = () => Date.now(), fu = 1; + function cu(e, t, n) { + if (n >>>= 0, !(0 <= e && 3 >= e)) return 28; + if (e === 0) e = Date.now(); + else { + if (!fu) return 52; + e = performance.timeOrigin + performance.now(); } -} - -/** - * Base class for outputs of token classification models. - */ -class TokenClassifierOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Classification scores (before SoftMax). - */ - constructor({ logits }) { - super(); - this.logits = logits; + return e = Math.round(1e6 * e), (d(), pe)[n >>> 3 >>> 0] = BigInt(e), 0; + } + var Pr = [], ro = (e, t) => { + Pr.length = 0; + for (var n; n = (d(), X)[e++ >>> 0]; ) { + var o = n != 105; + t += (o &= n != 112) && t % 8 ? 4 : 0, Pr.push(n == 112 ? (d(), E)[t >>> 2 >>> 0] : n == 106 ? (d(), pe)[t >>> 3 >>> 0] : n == 105 ? (d(), I)[t >>> 2 >>> 0] : (d(), ae)[t >>> 3 >>> 0]), t += o ? 8 : 4; } -} - -/** - * Base class for masked language models outputs. - */ -class MaskedLMOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). - */ - constructor({ logits }) { - super(); - this.logits = logits; + return Pr; + }; + function du(e, t, n) { + return e >>>= 0, t = ro(t >>> 0, n >>> 0), Yr[e](...t); + } + function lu(e, t, n) { + return e >>>= 0, t = ro(t >>> 0, n >>> 0), Yr[e](...t); + } + var pu = () => { + }; + function mu(e, t) { + return O(lt(e >>> 0, t >>> 0)); + } + var hu = () => { + throw z += 1, "unwind"; + }; + function bu() { + return 4294901760; + } + var gu = () => 1, yu = () => navigator.hardwareConcurrency, Ze = {}, no = (e) => { + var t = _e(e) + 1, n = Ke(t); + return n && Ue(e, n, t), n; + }, kt = (e) => { + var t; + return (t = /\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(e)) ? +t[1] : (t = /:(\d+):\d+(?:\)|$)/.exec(e)) ? 2147483648 | +t[1] : 0; + }, oo = (e) => { + for (var t of e) (e = kt(t)) && (Ze[e] = t); + }; + function wu() { + var e = Error().stack.toString().split(` +`); + return e[0] == "Error" && e.shift(), oo(e), Ze.ee = kt(e[3]), Ze.xe = e, Ze.ee; + } + function Ft(e) { + if (!(e = Ze[e >>> 0])) return 0; + var t; + if (t = /^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(e)) e = t[1]; + else if (t = /^\s+at (.*) \(.*\)$/.exec(e)) e = t[1]; + else { + if (!(t = /^(.+?)@/.exec(e))) return 0; + e = t[1]; } -} - -/** - * Base class for outputs of question answering models. - */ -class QuestionAnsweringModelOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.start_logits Span-start scores (before SoftMax). - * @param {Tensor} output.end_logits Span-end scores (before SoftMax). - */ - constructor({ start_logits, end_logits }) { - super(); - this.start_logits = start_logits; - this.end_logits = end_logits; + return ve(Ft.ne ?? 0), Ft.ne = no(e), Ft.ne; + } + function Tu(e) { + e >>>= 0; + var t = (d(), X).length; + if (e <= t || 4294901760 < e) return false; + for (var n = 1; 4 >= n; n *= 2) { + var o = t * (1 + 0.2 / n); + o = Math.min(o, e + 100663296); + e: { + o = (Math.min(4294901760, 65536 * Math.ceil(Math.max(e, o) / 65536)) - Fe.buffer.byteLength + 65535) / 65536 | 0; + try { + Fe.grow(o), se(); + var u = 1; + break e; + } catch { + } + u = void 0; + } + if (u) return true; } -} - - -/** - * Base class for causal language model (or autoregressive) outputs. - */ -class CausalLMOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). - */ - constructor({ logits }) { - super(); - this.logits = logits; + return false; + } + function vu(e, t, n) { + if (e >>>= 0, t >>>= 0, Ze.ee == e) var o = Ze.xe; + else (o = Error().stack.toString().split(` +`))[0] == "Error" && o.shift(), oo(o); + for (var u = 3; o[u] && kt(o[u]) != e; ) ++u; + for (e = 0; e < n && o[e + u]; ++e) (d(), I)[t + 4 * e >>> 2 >>> 0] = kt(o[e + u]); + return e; + } + var Ce = (e) => { + var t = _e(e) + 1, n = Vt(t); + return Ue(e, n, t), n; + }, mt = (e) => (d(), E)[e >>> 2 >>> 0] + 4294967296 * (d(), I)[e + 4 >>> 2 >>> 0], fe = [], ao = (e, t) => { + fe[e >>> 0] = t; + }, Re = [], Gt = [], ht = (e, t) => { + Gt[e] = new Promise((n) => t.finally(() => n(e))); + }, B = (e) => { + if (e) return fe[e >>> 0]; + }, Ur = (e, t) => { + for (e = (d(), E)[e >>> 2 >>> 0]; e; e = (d(), E)[e >>> 2 >>> 0]) t[(d(), I)[e + 4 >>> 2 >>> 0]](e); + }, $t = (e, t, n) => { + (d(), E)[e >>> 2 >>> 0] = t, (d(), E)[e + 4 >>> 2 >>> 0] = n; + }, so = (e) => { + var t = (d(), E)[e >>> 2 >>> 0]; + return e = (d(), E)[e + 4 >>> 2 >>> 0], lt(t, e); + }, Ie = (e) => { + var t = (d(), E)[e >>> 2 >>> 0]; + return e = (d(), E)[e + 4 >>> 2 >>> 0], t ? lt(t, e) : e === 0 ? "" : void 0; + }, Eu = (e) => { + var t = Ie(e + 4), n = (n = (d(), E)[e + 12 >>> 2 >>> 0]) ? B(n) : "auto"; + if (e += 16) { + var o = B((d(), E)[e + 4 >>> 2 >>> 0]), u = (d(), E)[e + 16 >>> 2 >>> 0], c = (d(), E)[e + 20 >>> 2 >>> 0]; + if (u) { + for (var h = {}, m = 0; m < u; ++m) { + var y = c + 24 * m; + h[so(y + 4)] = (d(), ae)[y + 16 >>> 3 >>> 0]; + } + u = h; + } else u = void 0; + e = { module: o, constants: u, entryPoint: Ie(e + 8) }; + } else e = void 0; + return { label: t, layout: n, compute: e }; + }, io = (e, t) => { + function n(c, h, m, y = 0) { + c = e[c] ?? y, (d(), E)[h + m >>> 2 >>> 0] = c; + } + function o(c, h, m, y = 0) { + h += m, c = e[c] ?? y, (d(), E)[h >>> 2 >>> 0] = c, y = (d(), E)[h >>> 2 >>> 0], (d(), E)[h + 4 >>> 2 >>> 0] = (c - y) / 4294967296; + } + var u = (d(), E)[t >>> 2 >>> 0]; + n("maxTextureDimension1D", t, 4), n("maxTextureDimension2D", t, 8), n("maxTextureDimension3D", t, 12), n("maxTextureArrayLayers", t, 16), n("maxBindGroups", t, 20), n("maxBindGroupsPlusVertexBuffers", t, 24), n("maxBindingsPerBindGroup", t, 28), n("maxDynamicUniformBuffersPerPipelineLayout", t, 32), n("maxDynamicStorageBuffersPerPipelineLayout", t, 36), n("maxSampledTexturesPerShaderStage", t, 40), n("maxSamplersPerShaderStage", t, 44), n("maxStorageBuffersPerShaderStage", t, 48), n("maxStorageTexturesPerShaderStage", t, 52), n("maxUniformBuffersPerShaderStage", t, 56), n("minUniformBufferOffsetAlignment", t, 80), n("minStorageBufferOffsetAlignment", t, 84), o("maxUniformBufferBindingSize", t, 64), o("maxStorageBufferBindingSize", t, 72), n("maxVertexBuffers", t, 88), o("maxBufferSize", t, 96), n("maxVertexAttributes", t, 104), n("maxVertexBufferArrayStride", t, 108), n("maxInterStageShaderVariables", t, 112), n("maxColorAttachments", t, 116), n("maxColorAttachmentBytesPerSample", t, 120), n("maxComputeWorkgroupStorageSize", t, 124), n("maxComputeInvocationsPerWorkgroup", t, 128), n("maxComputeWorkgroupSizeX", t, 132), n("maxComputeWorkgroupSizeY", t, 136), n("maxComputeWorkgroupSizeZ", t, 140), n("maxComputeWorkgroupsPerDimension", t, 144), n("maxImmediateSize", t, 148), u !== 0 && (d(), n("maxStorageBuffersInVertexStage", u, 8, e.maxStorageBuffersPerShaderStage), n("maxStorageBuffersInFragmentStage", u, 16, e.maxStorageBuffersPerShaderStage), n("maxStorageTexturesInVertexStage", u, 12, e.maxStorageTexturesPerShaderStage), n("maxStorageTexturesInFragmentStage", u, 20, e.maxStorageTexturesPerShaderStage)); + }, Su = (e, t) => { + (d(), E)[t + 52 >>> 2 >>> 0] = e.subgroupMinSize, (d(), E)[t + 56 >>> 2 >>> 0] = e.subgroupMaxSize; + var n = no(e.vendor + e.architecture + e.device + e.description), o = _e(e.vendor); + $t(t + 4, n, o), n += o, o = _e(e.architecture), $t(t + 12, n, o), n += o, o = _e(e.device), $t(t + 20, n, o), n += o, o = _e(e.description), $t(t + 28, n, o), n += o, (d(), I)[t + 36 >>> 2 >>> 0] = 2, n = e.isFallbackAdapter ? 3 : 4, (d(), I)[t + 40 >>> 2 >>> 0] = n, (d(), E)[t + 44 >>> 2 >>> 0] = 0, (d(), E)[t + 48 >>> 2 >>> 0] = 0, Ur(t, { 327739: (u) => { + let c = 0, h = 0; + if (e.subgroupMatrixConfigs) { + c = e.subgroupMatrixConfigs.length, h = Ke(20 * c); + for (let [m, y] of e.subgroupMatrixConfigs.entries()) { + let x = h + 20 * m, N = fo.indexOf(y.componentType), F = fo.indexOf(y.resultComponentType); + (d(), I)[x >>> 2 >>> 0] = N, (d(), I)[x + 4 >>> 2 >>> 0] = F, (d(), E)[x + 8 >>> 2 >>> 0] = y.M, (d(), E)[x + 12 >>> 2 >>> 0] = y.N, (d(), E)[x + 16 >>> 2 >>> 0] = y.K; + } + } + (d(), E)[u + 12 >>> 2 >>> 0] = h, (d(), E)[u + 8 >>> 2 >>> 0] = c; + } }); + }, xu = [, , "uniform", "storage", "read-only-storage"], Au = [, "validation", "out-of-memory", "internal"], Iu = [, "compatibility", "core"], uo = { 1: "core-features-and-limits", 2: "depth-clip-control", 3: "depth32float-stencil8", 4: "texture-compression-bc", 5: "texture-compression-bc-sliced-3d", 6: "texture-compression-etc2", 7: "texture-compression-astc", 8: "texture-compression-astc-sliced-3d", 9: "timestamp-query", 10: "indirect-first-instance", 11: "shader-f16", 12: "rg11b10ufloat-renderable", 13: "bgra8unorm-storage", 14: "float32-filterable", 15: "float32-blendable", 16: "clip-distances", 17: "dual-source-blending", 18: "subgroups", 19: "texture-formats-tier1", 20: "texture-formats-tier2", 21: "primitive-index", 22: "texture-component-swizzle", 23: "subgroup-size-control", 327692: "chromium-experimental-unorm16-texture-formats", 327729: "chromium-experimental-multi-draw-indirect", 327732: "chromium-experimental-subgroup-matrix" }, Lu = [, "low-power", "high-performance"], Bu = [, "occlusion", "timestamp"], Ou = [, , "filtering", "non-filtering", "comparison"], Mu = [, , "write-only", "read-only", "read-write"], fo = [, "f32", "f16", "u32", "i32", "u8", "i8"], Cu = [, "r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32float", "r32uint", "r32sint", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rgb9e5ufloat", "rg32float", "rg32uint", "rg32sint", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32float", "rgba32uint", "rgba32sint", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb"], Du = [, , "float", "unfilterable-float", "depth", "sint", "uint"], co = [, "1d", "2d", "2d-array", "cube", "cube-array", "3d"], Pu = { undefined: 1, unknown: 1, destroyed: 2 }; + function Uu(e, t, n, o, u, c) { + t = ue(t), n = ue(n), o >>>= 0, u >>>= 0, c >>>= 0; + var h = B(e >>> 0); + if (e = {}, c) { + var m = (d(), E)[c + 12 >>> 2 >>> 0]; + if (m) { + var y = (d(), E)[c + 16 >>> 2 >>> 0]; + e.requiredFeatures = Array.from((d(), E).subarray(y >>> 2 >>> 0, y + 4 * m >>> 2 >>> 0), (L) => uo[L]); + } + if (m = (d(), E)[c + 20 >>> 2 >>> 0]) { + let L = function(he, de, Qe, et = false) { + de += Qe, (de = (d(), E)[de >>> 2 >>> 0]) == 4294967295 || et && de == 0 || (x[he] = de); + }, q = function(he, de, Qe) { + de += Qe, Qe = (d(), E)[de >>> 2 >>> 0]; + var et = (d(), E)[de + 4 >>> 2 >>> 0]; + Qe == 4294967295 && et == 4294967295 || (x[he] = mt(de)); + }; + var N = L, F = q; + y = (d(), E)[m >>> 2 >>> 0]; + var x = {}; + L("maxTextureDimension1D", m, 4), L("maxTextureDimension2D", m, 8), L("maxTextureDimension3D", m, 12), L("maxTextureArrayLayers", m, 16), L("maxBindGroups", m, 20), L("maxBindGroupsPlusVertexBuffers", m, 24), L("maxBindingsPerBindGroup", m, 28), L("maxDynamicUniformBuffersPerPipelineLayout", m, 32), L("maxDynamicStorageBuffersPerPipelineLayout", m, 36), L("maxSampledTexturesPerShaderStage", m, 40), L("maxSamplersPerShaderStage", m, 44), L("maxStorageBuffersPerShaderStage", m, 48), L("maxStorageTexturesPerShaderStage", m, 52), L("maxUniformBuffersPerShaderStage", m, 56), L("minUniformBufferOffsetAlignment", m, 80), L("minStorageBufferOffsetAlignment", m, 84), q("maxUniformBufferBindingSize", m, 64), q("maxStorageBufferBindingSize", m, 72), L("maxVertexBuffers", m, 88), q("maxBufferSize", m, 96), L("maxVertexAttributes", m, 104), L("maxVertexBufferArrayStride", m, 108), L("maxInterStageShaderVariables", m, 112), L("maxColorAttachments", m, 116), L("maxColorAttachmentBytesPerSample", m, 120), L("maxComputeWorkgroupStorageSize", m, 124), L("maxComputeInvocationsPerWorkgroup", m, 128), L("maxComputeWorkgroupSizeX", m, 132), L("maxComputeWorkgroupSizeY", m, 136), L("maxComputeWorkgroupSizeZ", m, 140), L("maxComputeWorkgroupsPerDimension", m, 144), L("maxImmediateSize", m, 148, true), y !== 0 && (d(), "maxStorageBuffersInVertexStage" in GPUSupportedLimits.prototype && (L("maxStorageBuffersInVertexStage", y, 8), L("maxStorageTexturesInVertexStage", y, 12), L("maxStorageBuffersInFragmentStage", y, 16), L("maxStorageTexturesInFragmentStage", y, 20))), e.requiredLimits = x; + } + (m = (d(), E)[c + 24 >>> 2 >>> 0]) && (m = { label: Ie(m + 4) }, e.defaultQueue = m), e.label = Ie(c + 4); } -} - -/** - * Base class for causal language model (or autoregressive) outputs. - */ -class CausalLMOutputWithPast extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). - * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks) - * that can be used (see `past_key_values` input) to speed up sequential decoding. - */ - constructor({ logits, past_key_values }) { - super(); - this.logits = logits; - this.past_key_values = past_key_values; + z += 1, ht(t, h.requestDevice(e).then((L) => { + --z, me(() => { + fe[u >>> 0] = L.queue, fe[o >>> 0] = L, z += 1, ht(n, L.lost.then((q) => { + me(() => { + L.onuncapturederror = () => { + }; + var he = P(), de = Ce(q.message); + kr(n, Pu[q.reason], de), D(he); + }), --z; + })), L.onuncapturederror = (q) => { + var he = 5; + q.error instanceof GPUValidationError ? he = 2 : q.error instanceof GPUOutOfMemoryError ? he = 3 : q.error instanceof GPUInternalError && (he = 4); + var de = P(); + q = Ce(q.error.message), Uo(o, he, q), D(de); + }, "adapterInfo" in L || (L.adapterInfo = h.info), $r(t, 1, o, 0); + }); + }, (L) => { + --z, me(() => { + var q = P(), he = Ce(L.message); + $r(t, 3, o, he), n && kr(n, 4, he), D(q); + }); + })); + } + function _u(e) { + var t = B(e >>>= 0), n = Re[e]; + if (n) { + for (var o = 0; o < n.length; ++o) n[o](); + delete Re[e]; } -} - -class ImageMattingOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. - */ - constructor({ alphas }) { - super(); - this.alphas = alphas; + t.destroy(); + } + function Ru(e, t, n) { + n >>>= 0; + var o = B(e >>>= 0); + n == 4294967295 && (n = void 0); + try { + var u = o.getMappedRange(t >>> 0, n); + } catch { + return 0; } -} - -/** - * Describes the outputs for the VITS model. - */ -class VitsModelOutput extends ModelOutput { - /** - * @param {Object} output The output of the model. - * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. - * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. - * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. - */ - constructor({ waveform, spectrogram }) { - super(); - this.waveform = waveform; - this.spectrogram = spectrogram; + var c = jr(16, u.byteLength); + return (d(), X).set(new Uint8Array(u), c >>> 0), Re[e].push(() => ve(c)), c; + } + function Nu(e, t, n) { + n >>>= 0; + var o = B(e >>>= 0); + n == 4294967295 && (n = void 0); + try { + var u = o.getMappedRange(t >>> 0, n); + } catch { + return 0; } -} - - -/***/ }), - -/***/ "./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js": -/*!******************************************************************************************************!*\ - !*** ./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js ***! - \******************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ASTFeatureExtractor: () => (/* binding */ ASTFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); - - - - - -class ASTFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - - constructor(config) { - super(config); - - const sampling_rate = this.config.sampling_rate; - const mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - 257, // num_frequency_bins - this.config.num_mel_bins, // num_mel_filters - 20, // min_frequency - Math.floor(sampling_rate / 2), // max_frequency - sampling_rate, // sampling_rate - null, // norm - "kaldi", // mel_scale - true, // triangularize_in_mel_space - ); - this.mel_filters = mel_filters; - - this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(400, 'hann', { - periodic: false, - }) - - this.mean = this.config.mean; - this.std = this.config.std; + var c = jr(16, u.byteLength); + return (d(), X).fill(0, c, u.byteLength), Re[e].push(() => { + new Uint8Array(u).set((d(), X).subarray(c >>> 0, c + u.byteLength >>> 0)), ve(c); + }), c; + } + function Wu(e, t, n, o, u) { + e >>>= 0, t = ue(t), n = ue(n), u >>>= 0; + var c = B(e); + Re[e] = [], u == 4294967295 && (u = void 0), z += 1, ht(t, c.mapAsync(n, o >>> 0, u).then(() => { + --z, me(() => { + Fr(t, 1, 0); + }); + }, (h) => { + --z, me(() => { + P(); + var m = Ce(h.message); + Fr(t, h.name === "AbortError" ? 4 : h.name === "OperationError" ? 3 : 0, m), delete Re[e]; + }); + })); + } + function ku(e) { + var t = B(e >>>= 0), n = Re[e]; + if (n) { + for (var o = 0; o < n.length; ++o) n[o](); + delete Re[e], t.unmap(); } - - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @param {number} max_length The maximum number of frames to return. - * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - async _extract_fbank_features(waveform, max_length) { - // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` - return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( - waveform, - this.window, // window - 400, // frame_length - 160, // hop_length - { - fft_length: 512, - power: 2.0, - center: false, - preemphasis: 0.97, - mel_filters: this.mel_filters, - log_mel: 'log', - mel_floor: 1.192092955078125e-07, - remove_dc_offset: true, - - // Custom - max_num_frames: max_length, - transpose: true, - } - ) + } + function Fu(e) { + delete fe[e >>> 0]; + } + function Gu(e, t, n) { + e >>>= 0, t >>>= 0, n >>>= 0; + var o = !!(d(), E)[t + 32 >>> 2 >>> 0]; + t = { label: Ie(t + 4), usage: (d(), E)[t + 16 >>> 2 >>> 0], size: mt(t + 24), mappedAtCreation: o }, e = B(e); + try { + var u = e.createBuffer(t); + } catch { + return false; } - - - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'ASTFeatureExtractor'); - - const features = await this._extract_fbank_features(audio, this.config.max_length); - if (this.config.do_normalize) { - // Normalize the input audio spectrogram to have mean=0, std=0.5 - const denom = this.std * 2; - const features_data = features.data; - for (let i = 0; i < features_data.length; ++i) { - features_data[i] = (features_data[i] - this.mean) / denom; - } + return fe[n >>> 0] = u, o && (Re[n] = []), true; + } + function $u(e, t, n, o) { + e >>>= 0, t = ue(t), o >>>= 0, n = Eu(n >>> 0), e = B(e), z += 1, ht(t, e.createComputePipelineAsync(n).then((u) => { + --z, me(() => { + fe[o >>> 0] = u, Wr(t, 1, o, 0); + }); + }, (u) => { + --z, me(() => { + var c = P(), h = Ce(u.message); + Wr(t, u.reason === "validation" ? 3 : u.reason === "internal" ? 4 : 0, o, h), D(c); + }); + })); + } + function zu(e, t, n) { + e >>>= 0, t >>>= 0, n >>>= 0; + var o = (d(), E)[t >>> 2 >>> 0], u = (d(), I)[o + 4 >>> 2 >>> 0]; + t = { label: Ie(t + 4), code: "" }, u === 2 && (t.code = so(o + 8)), e = B(e).createShaderModule(t), fe[n >>> 0] = e; + } + var Vu = (e) => { + (e = B(e)).onuncapturederror = null, e.destroy(); + }; + function ju(e, t) { + t = ue(t), e = B(e >>> 0), z += 1, ht(t, e.popErrorScope().then((n) => { + --z, me(() => { + var o = 5; + n ? n instanceof GPUValidationError ? o = 2 : n instanceof GPUOutOfMemoryError ? o = 3 : n instanceof GPUInternalError && (o = 4) : o = 1; + var u = P(), c = n ? Ce(n.message) : 0; + Gr(t, 1, o, c), D(u); + }); + }, (n) => { + --z, me(() => { + var o = P(), u = Ce(n.message); + Gr(t, 1, 5, u), D(o); + }); + })); + } + function Hu(e, t, n, o) { + if (t = ue(t), o >>>= 0, n >>>= 0) { + var u = { featureLevel: Iu[(d(), I)[n + 4 >>> 2 >>> 0]], powerPreference: Lu[(d(), I)[n + 8 >>> 2 >>> 0]], forceFallbackAdapter: !!(d(), E)[n + 12 >>> 2 >>> 0] }; + (e = (d(), E)[n >>> 2 >>> 0]) !== 0 && (d(), u.Ye = !!(d(), E)[e + 8 >>> 2 >>> 0]); + } + "gpu" in navigator ? (z += 1, ht(t, navigator.gpu.requestAdapter(u).then((c) => { + --z, me(() => { + if (c) fe[o >>> 0] = c, St(t, 1, o, 0); + else { + var h = P(), m = Ce("WebGPU not available on this browser (requestAdapter returned null)"); + St(t, 3, o, m), D(h); } - - return { - input_values: features.unsqueeze_(0) - }; + }); + }, (c) => { + --z, me(() => { + var h = P(), m = Ce(c.message); + St(t, 4, o, m), D(h); + }); + }))) : (u = P(), e = Ce("WebGPU not available on this browser (navigator.gpu is not available)"), St(t, 3, o, e), D(u)); + } + function qu(e, t, n) { + return e >>>= 0, t >>>= 0, n >>>= 0, Yn(async () => { + var o = []; + if (n) { + var u = (d(), I)[n >>> 2 >>> 0]; + o.length = t + 1, o[t] = new Promise((m) => setTimeout(m, u, 0)); + } else o.length = t; + for (var c = 0; c < t; ++c) { + var h = mt(e + 8 * c); + if (!(h in Gt)) return h; + o[c] = Gt[h]; + } + return o = await Promise.race(o), delete Gt[o], o; + }); + } + var _r, Rr = {}, lo = () => { + if (!_r) { + var e, t = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: (globalThis.navigator?.language ?? "C").replace("-", "_") + ".UTF-8", _: "./this.program" }; + for (e in Rr) Rr[e] === void 0 ? delete t[e] : t[e] = Rr[e]; + var n = []; + for (e in t) n.push(`${e}=${t[e]}`); + _r = n; + } + return _r; + }; + function po(e, t) { + if (i) return H(19, 1, e, t); + e >>>= 0, t >>>= 0; + var n, o = 0, u = 0; + for (n of lo()) { + var c = t + o; + (d(), E)[e + u >>> 2 >>> 0] = c, o += Ue(n, c, 1 / 0) + 1, u += 4; + } + return 0; + } + function mo(e, t) { + if (i) return H(20, 1, e, t); + e >>>= 0, t >>>= 0; + var n = lo(); + for (var o of ((d(), E)[e >>> 2 >>> 0] = n.length, e = 0, n)) e += _e(o) + 1; + return (d(), E)[t >>> 2 >>> 0] = e, 0; + } + function ho(e) { + return i ? H(21, 1, e) : 52; + } + function bo(e, t, n, o, u) { + return i ? H(22, 1, e, t, n, o, u) : 52; + } + function go(e, t, n, o) { + return i ? H(23, 1, e, t, n, o) : 52; + } + function yo(e, t, n, o) { + return i ? H(24, 1, e, t, n, o) : 70; + } + var Yu = [null, [], []]; + function wo(e, t, n, o) { + if (i) return H(25, 1, e, t, n, o); + t >>>= 0, n >>>= 0, o >>>= 0; + for (var u = 0, c = 0; c < n; c++) { + var h = (d(), E)[t >>> 2 >>> 0], m = (d(), E)[t + 4 >>> 2 >>> 0]; + t += 8; + for (var y = 0; y < m; y++) { + var x = e, N = (d(), X)[h + y >>> 0], F = Yu[x]; + N === 0 || N === 10 ? ((x === 1 ? Y : O)(Bn(F)), F.length = 0) : F.push(N); + } + u += m; } -} - - -/***/ }), - -/***/ "./src/models/auto/feature_extraction_auto.js": -/*!****************************************************!*\ - !*** ./src/models/auto/feature_extraction_auto.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AutoFeatureExtractor: () => (/* binding */ AutoFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/constants.js */ "./src/utils/constants.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _feature_extractors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../feature_extractors.js */ "./src/models/feature_extractors.js"); - - - - - - -class AutoFeatureExtractor { - - /** @type {typeof FeatureExtractor.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options={}) { - - const preprocessorConfig = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.FEATURE_EXTRACTOR_NAME, true, options); - - // Determine feature extractor class - const key = preprocessorConfig.feature_extractor_type; - const feature_extractor_class = _feature_extractors_js__WEBPACK_IMPORTED_MODULE_3__[key]; - - if (!feature_extractor_class) { - throw new Error(`Unknown feature_extractor_type: '${key}'. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.GITHUB_ISSUE_URL}.`); - } - - // Instantiate feature extractor - return new feature_extractor_class(preprocessorConfig); + return (d(), E)[o >>> 2 >>> 0] = u, 0; + } + function Ju(e) { + return e >>> 0; + } + function Xu(e, t) { + return io(B(e >>> 0).limits, t >>> 0), 1; + } + function Zu(e, t) { + return B(e >>> 0).features.has(uo[t]); + } + function Ku(e) { + return BigInt(B(e >>> 0).size); + } + function Qu(e) { + return BigInt(B(e >>> 0).usage); + } + function ef(e, t) { + if (e >>>= 0, t >>>= 0) { + var n = Ie(t + 4); + n = { label: n, timestampWrites: t = (t = (d(), E)[t + 12 >>> 2 >>> 0]) !== 0 ? { querySet: B((d(), E)[t + 4 >>> 2 >>> 0]), beginningOfPassWriteIndex: (d(), E)[t + 8 >>> 2 >>> 0], endOfPassWriteIndex: (d(), E)[t + 12 >>> 2 >>> 0] } : void 0 }; } -} - - -/***/ }), - -/***/ "./src/models/auto/image_processing_auto.js": -/*!**************************************************!*\ - !*** ./src/models/auto/image_processing_auto.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AutoImageProcessor: () => (/* binding */ AutoImageProcessor) -/* harmony export */ }); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/constants.js */ "./src/utils/constants.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _image_processors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../image_processors.js */ "./src/models/image_processors.js"); - - - - - - -class AutoImageProcessor { - - /** @type {typeof ImageProcessor.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options={}) { - - const preprocessorConfig = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.IMAGE_PROCESSOR_NAME, true, options); - - // Determine image processor class - const key = preprocessorConfig.image_processor_type ?? preprocessorConfig.feature_extractor_type; - let image_processor_class = _image_processors_js__WEBPACK_IMPORTED_MODULE_3__[key?.replace(/Fast$/, '')]; - - if (!image_processor_class) { - if (key !== undefined) { - // Only log a warning if the class is not found and the key is set. - console.warn(`Image processor type '${key}' not found, assuming base ImageProcessor. Please report this at ${_utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.GITHUB_ISSUE_URL}.`) - } - image_processor_class = _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_2__.ImageProcessor; - } - - // Instantiate image processor - return new image_processor_class(preprocessorConfig); + return t = B(e), e = Bo(0), n = t.beginComputePass(n), fe[e >>> 0] = n, e; + } + function tf(e, t, n, o) { + n = ue(n), (o = ue(o)) == -1 && (o = void 0), (e = B(e >>> 0)).clearBuffer(B(t >>> 0), n, o); + } + function rf(e, t, n, o, u, c) { + n = ue(n), u = ue(u), c = ue(c), B(e >>> 0).copyBufferToBuffer(B(t >>> 0), n, B(o >>> 0), u, c); + } + function nf(e) { + var t = B(e >>> 0); + return e = Io(0), t = t.finish(), fe[e >>> 0] = t, e; + } + function of(e, t, n, o, u, c) { + c = ue(c), B(e >>> 0).resolveQuerySet(B(t >>> 0), n, o, B(u >>> 0), c); + } + function af(e, t, n, o) { + B(e >>> 0).dispatchWorkgroups(t, n, o); + } + function sf(e, t, n) { + n = ue(n), B(e >>> 0).dispatchWorkgroupsIndirect(B(t >>> 0), n); + } + function uf(e) { + B(e >>> 0).end(); + } + function ff(e, t, n, o, u) { + o >>>= 0, u >>>= 0, e = B(e >>> 0), n = B(n >>> 0), o == 0 ? e.setBindGroup(t, n) : e.setBindGroup(t, n, (d(), E), u >>> 2, o); + } + function cf(e, t) { + B(e >>> 0).setPipeline(B(t >>> 0)); + } + function df(e, t, n) { + B(e >>> 0).Xe(B(t >>> 0), n); + } + function lf(e, t) { + function n(u) { + var c = (d(), E)[u + 8 >>> 2 >>> 0], h = (d(), E)[u + 32 >>> 2 >>> 0], m = (d(), E)[u + 36 >>> 2 >>> 0], y = 0; + return Ur(u, { 14: (x) => { + y = (d(), E)[x + 8 >>> 2 >>> 0]; + } }), c ? ((h = mt(u + 24)) == -1 && (h = void 0), c = { buffer: B(c), offset: mt(u + 16), size: h }) : c = B(h || m || y), { binding: (d(), E)[u + 4 >>> 2 >>> 0], resource: c }; + } + e >>>= 0, t = { label: Ie((t >>>= 0) + 4), layout: B((d(), E)[t + 12 >>> 2 >>> 0]), entries: (function(u, c) { + for (var h = [], m = 0; m < u; ++m) h.push(n(c + 40 * m)); + return h; + })((d(), E)[t + 16 >>> 2 >>> 0], (d(), E)[t + 20 >>> 2 >>> 0]) }, e = B(e); + var o = xo(0); + return ao(o, e.createBindGroup(t)), o; + } + function pf(e, t) { + function n(y) { + var x = (d(), E)[y + 4 >>> 2 >>> 0]; + if (x) return { type: xu[x], hasDynamicOffset: !!(d(), E)[y + 8 >>> 2 >>> 0], minBindingSize: mt(y + 16) }; + } + function o(y) { + if (y = (d(), E)[y + 4 >>> 2 >>> 0]) return { type: Ou[y] }; + } + function u(y) { + var x = (d(), E)[y + 4 >>> 2 >>> 0]; + if (x) return { sampleType: Du[x], viewDimension: co[(d(), I)[y + 8 >>> 2 >>> 0]], multisampled: !!(d(), E)[y + 12 >>> 2 >>> 0] }; + } + function c(y) { + var x = (d(), E)[y + 4 >>> 2 >>> 0]; + if (x) return { access: Mu[x], format: Cu[(d(), I)[y + 8 >>> 2 >>> 0]], viewDimension: co[(d(), I)[y + 12 >>> 2 >>> 0]] }; + } + function h(y) { + var x = { binding: (d(), E)[y + 4 >>> 2 >>> 0], visibility: (d(), E)[y + 8 >>> 2 >>> 0], buffer: n(y + 24), sampler: o(y + 48), texture: u(y + 56), storageTexture: c(y + 72) }; + return Ur(y, { 13: () => { + x.externalTexture = {}; + } }), x; + } + e >>>= 0, t = { label: Ie((t >>>= 0) + 4), entries: (function(y, x) { + for (var N = [], F = 0; F < y; ++F) N.push(h(x + 88 * F)); + return N; + })((d(), E)[t + 12 >>> 2 >>> 0], (d(), E)[t + 16 >>> 2 >>> 0]) }, e = B(e); + var m = Ao(0); + return ao(m, e.createBindGroupLayout(t)), m; + } + function mf(e, t) { + var n; + return e >>>= 0, (t >>>= 0) && (n = { label: Ie(t + 4) }), t = B(e), e = Lo(0), n = t.createCommandEncoder(n), fe[e >>> 0] = n, e; + } + function hf(e, t) { + e >>>= 0, t >>>= 0; + for (var n = (d(), E)[t + 12 >>> 2 >>> 0], o = (d(), E)[t + 16 >>> 2 >>> 0], u = [], c = 0; c < n; ++c) u.push(B((d(), E)[o + 4 * c >>> 2 >>> 0])); + return t = { label: Ie(t + 4), bindGroupLayouts: u, immediateSize: (d(), E)[t + 20 >>> 2 >>> 0] }, n = B(e), e = Oo(0), t = n.createPipelineLayout(t), fe[e >>> 0] = t, e; + } + function bf(e, t) { + e >>>= 0, t >>>= 0, t = { type: Bu[(d(), I)[t + 12 >>> 2 >>> 0]], count: (d(), E)[t + 16 >>> 2 >>> 0] }; + var n = B(e); + return e = Mo(0), t = n.createQuerySet(t), fe[e >>> 0] = t, e; + } + function gf(e, t) { + return Su(B(e >>> 0).adapterInfo, t >>> 0), 1; + } + var yf = { "core-features-and-limits": 1, "depth-clip-control": 2, "depth32float-stencil8": 3, "texture-compression-bc": 4, "texture-compression-bc-sliced-3d": 5, "texture-compression-etc2": 6, "texture-compression-astc": 7, "texture-compression-astc-sliced-3d": 8, "timestamp-query": 9, "indirect-first-instance": 10, "shader-f16": 11, "rg11b10ufloat-renderable": 12, "bgra8unorm-storage": 13, "float32-filterable": 14, "float32-blendable": 15, "clip-distances": 16, "dual-source-blending": 17, subgroups: 18, "texture-formats-tier1": 19, "texture-formats-tier2": 20, "primitive-index": 21, "texture-component-swizzle": 22, "subgroup-size-control": 23, "chromium-experimental-unorm16-texture-formats": 327692, "chromium-experimental-multi-draw-indirect": 327729, "chromium-experimental-subgroup-matrix": 327732 }; + function wf(e, t) { + t >>>= 0; + var n = B(e >>> 0); + e = Ke(4 * n.features.size); + var o = 0, u = 0; + for (let c of n.features) 0 <= (n = yf[c]) && ((d(), I)[e + o >>> 2 >>> 0] = n, o += 4, u++); + (d(), E)[t + 4 >>> 2 >>> 0] = e, (d(), E)[t >>> 2 >>> 0] = u; + } + function Tf(e, t) { + return io(B(e >>> 0).limits, t >>> 0), 1; + } + function vf(e, t) { + B(e >>> 0).pushErrorScope(Au[t]); + } + function Ef(e, t, n) { + t >>>= 0, n >>>= 0, e = B(e >>> 0), t = Array.from((d(), I).subarray(n >>> 2 >>> 0, n + 4 * t >>> 2 >>> 0), (o) => B(o)), e.submit(t); + } + function Sf(e, t, n, o, u) { + n = ue(n), o >>>= 0, u >>>= 0, e = B(e >>> 0), t = B(t >>> 0), o = (d(), X).subarray(o >>> 0, o + u >>> 0), e.writeBuffer(t, n, o, 0, u); + } + i || (function() { + for (var e = r.numThreads - 1; e--; ) vn(); + xe.push(async () => { + var t = (async function() { + if (!i) return Promise.all(ke.map(Tn)); + })(); + Be++, await t, --Be == 0 && re && (t = re, re = null, t()); + }); + })(), i || (Fe = new WebAssembly.Memory({ initial: 256, maximum: 65536, shared: true }), se()), r.wasmBinary && (v = r.wasmBinary), r.stackSave = () => P(), r.stackRestore = (e) => D(e), r.stackAlloc = (e) => Vt(e), r.setValue = function(e, t, n = "i8") { + switch (n.endsWith("*") && (n = "*"), n) { + case "i1": + case "i8": + (d(), Z)[e >>> 0] = t; + break; + case "i16": + (d(), De)[e >>> 1 >>> 0] = t; + break; + case "i32": + (d(), I)[e >>> 2 >>> 0] = t; + break; + case "i64": + (d(), pe)[e >>> 3 >>> 0] = BigInt(t); + break; + case "float": + (d(), R)[e >>> 2 >>> 0] = t; + break; + case "double": + (d(), ae)[e >>> 3 >>> 0] = t; + break; + case "*": + (d(), E)[e >>> 2 >>> 0] = t; + break; + default: + we(`invalid type for setValue: ${n}`); + } + }, r.getValue = function(e, t = "i8") { + switch (t.endsWith("*") && (t = "*"), t) { + case "i1": + case "i8": + return (d(), Z)[e >>> 0]; + case "i16": + return (d(), De)[e >>> 1 >>> 0]; + case "i32": + return (d(), I)[e >>> 2 >>> 0]; + case "i64": + return (d(), pe)[e >>> 3 >>> 0]; + case "float": + return (d(), R)[e >>> 2 >>> 0]; + case "double": + return (d(), ae)[e >>> 3 >>> 0]; + case "*": + return (d(), E)[e >>> 2 >>> 0]; + default: + we(`invalid type for getValue: ${t}`); } -} - - -/***/ }), - -/***/ "./src/models/auto/processing_auto.js": -/*!********************************************!*\ - !*** ./src/models/auto/processing_auto.js ***! - \********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AutoProcessor: () => (/* binding */ AutoProcessor) -/* harmony export */ }); -/* harmony import */ var _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../utils/constants.js */ "./src/utils/constants.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _processors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../processors.js */ "./src/models/processors.js"); -/* harmony import */ var _image_processors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../image_processors.js */ "./src/models/image_processors.js"); -/* harmony import */ var _feature_extractors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../feature_extractors.js */ "./src/models/feature_extractors.js"); - - - - - - - - - - -/** - * Helper class which is used to instantiate pretrained processors with the `from_pretrained` function. - * The chosen processor class is determined by the type specified in the processor config. - * - * **Example:** Load a processor using `from_pretrained`. - * ```javascript - * let processor = await AutoProcessor.from_pretrained('openai/whisper-tiny.en'); - * ``` - * - * **Example:** Run an image through a processor. - * ```javascript - * let processor = await AutoProcessor.from_pretrained('Xenova/clip-vit-base-patch16'); - * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); - * let image_inputs = await processor(image); - * // { - * // "pixel_values": { - * // "dims": [ 1, 3, 224, 224 ], - * // "type": "float32", - * // "data": Float32Array [ -1.558687686920166, -1.558687686920166, -1.5440893173217773, ... ], - * // "size": 150528 - * // }, - * // "original_sizes": [ - * // [ 533, 800 ] - * // ], - * // "reshaped_input_sizes": [ - * // [ 224, 224 ] - * // ] - * // } - * ``` - */ -class AutoProcessor { - - /** @type {typeof Processor.from_pretrained} */ - static async from_pretrained(pretrained_model_name_or_path, options={}) { - - // TODO: first check for processor.json - const preprocessorConfig = await (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_1__.getModelJSON)(pretrained_model_name_or_path, _utils_constants_js__WEBPACK_IMPORTED_MODULE_0__.IMAGE_PROCESSOR_NAME, true, options); - - const { image_processor_type, feature_extractor_type, processor_class } = preprocessorConfig; - if (processor_class && _processors_js__WEBPACK_IMPORTED_MODULE_3__[processor_class]) { - return _processors_js__WEBPACK_IMPORTED_MODULE_3__[processor_class].from_pretrained(pretrained_model_name_or_path, options); - } - - if (!image_processor_type && !feature_extractor_type) { - throw new Error('No `image_processor_type` or `feature_extractor_type` found in the config.'); - } - - const components = {}; - if (image_processor_type) { - // Some image processors are saved with the "Fast" suffix, so we remove that if present. - const image_processor_class = _image_processors_js__WEBPACK_IMPORTED_MODULE_4__[image_processor_type.replace(/Fast$/, '')]; - if (!image_processor_class) { - throw new Error(`Unknown image_processor_type: '${image_processor_type}'.`); - } - components.image_processor = new image_processor_class(preprocessorConfig); - } - - if (feature_extractor_type) { - const image_processor_class = _image_processors_js__WEBPACK_IMPORTED_MODULE_4__[feature_extractor_type]; - if (image_processor_class) { - // Handle legacy case where image processors were specified as feature extractors - components.image_processor = new image_processor_class(preprocessorConfig); - } else { - const feature_extractor_class = _feature_extractors_js__WEBPACK_IMPORTED_MODULE_5__[feature_extractor_type]; - if (!feature_extractor_class) { - throw new Error(`Unknown feature_extractor_type: '${feature_extractor_type}'.`); - } - components.feature_extractor = new feature_extractor_class(preprocessorConfig); - } - } - - const config = {}; - return new _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor(config, components, null); + }, r.UTF8ToString = lt, r.stringToUTF8 = Ue, r.lengthBytesUTF8 = _e; + var To, vo, Eo, Nr, zt, ve, Ke, So, xo, Ao, Io, Lo, Bo, Oo, Mo, Co, Do, Po, Wr, kr, Fr, Gr, St, $r, Uo, zr, _o, Ro, No, Vr, Wo, ko, jr, W, xt, Fo, D, Vt, P, Go, Hr, $o, zo, Vo, qr, jo, Ho, qo, Yo, Jo, Xo, Zo, Ko, Qo, ea, ta, ra, na, oa, aa, sa, ia, ua, fa, ca, da, la, pa, ma, ha, ba, ga, ya, wa, Ta, va, Ea, Sa, xa, Aa, Ia, La, Ba, Oa, Ma, Ca, Ne, xf = [Ye, Tr, xn, On, Mn, Cn, Dn, Pn, Un, _n, Rn, Nn, Wn, kn, Fn, Gn, Qn, eo, to, po, mo, ho, bo, go, yo, wo], Yr = { 1280444: (e, t, n, o, u) => { + if (r === void 0 || !r.ed) return 1; + if ((e = lt(Number(e >>> 0))).startsWith("./") && (e = e.substring(2)), !(e = r.ed.get(e))) return 2; + if (t = Number(t >>> 0), n = Number(n >>> 0), o = Number(o >>> 0), t + n > e.byteLength) return 3; + try { + let c = e.subarray(t, t + n); + switch (u) { + case 0: + (d(), X).set(c, o >>> 0); + break; + case 1: + r.pe ? r.pe(o, c) : r.Re(o, c); + break; + default: + return 4; + } + return 0; + } catch { + return 4; } -} - - -/***/ }), - -/***/ "./src/models/beit/image_processing_beit.js": -/*!**************************************************!*\ - !*** ./src/models/beit/image_processing_beit.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ BeitFeatureExtractor: () => (/* binding */ BeitFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class BeitFeatureExtractor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/bit/image_processing_bit.js": -/*!************************************************!*\ - !*** ./src/models/bit/image_processing_bit.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ BitImageProcessor: () => (/* binding */ BitImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class BitImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/chinese_clip/image_processing_chinese_clip.js": -/*!******************************************************************!*\ - !*** ./src/models/chinese_clip/image_processing_chinese_clip.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ChineseCLIPFeatureExtractor: () => (/* binding */ ChineseCLIPFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class ChineseCLIPFeatureExtractor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/clap/feature_extraction_clap.js": -/*!****************************************************!*\ - !*** ./src/models/clap/feature_extraction_clap.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ClapFeatureExtractor: () => (/* binding */ ClapFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); - - - - - -class ClapFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - - constructor(config) { - super(config); - - this.mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - this.config.nb_frequency_bins, // num_frequency_bins - this.config.feature_size, // num_mel_filters - this.config.frequency_min, // min_frequency - this.config.frequency_max, // max_frequency - this.config.sampling_rate, // sampling_rate - null, // norm - "htk", // mel_scale - ); - - this.mel_filters_slaney = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - this.config.nb_frequency_bins, // num_frequency_bins - this.config.feature_size, // num_mel_filters - this.config.frequency_min, // min_frequency - this.config.frequency_max, // max_frequency - this.config.sampling_rate, // sampling_rate - "slaney", // norm - "slaney", // mel_scale - ); - - this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(this.config.fft_window_size, 'hann') - + }, 1281268: (e, t, n) => { + r.re(e, (d(), X).subarray(t >>> 0, t + n >>> 0)); + }, 1281332: () => r.Pe(), 1281374: (e) => { + r.qe(e); + }, 1281411: () => typeof wasmOffsetConverter < "u" }; + function Af() { + return typeof wasmOffsetConverter < "u"; + } + function If2(e, t, n, o) { + var u = P(); + try { + return Ko(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); } - - - /** - * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. - * - * Four different path are possible: - * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram - * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram - * are then stacked together. They will later be used for `feature_fusion`. - * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is - * padded based on `padding`. - * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded - * based on `padding`, and is repeated `4` times. - * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel - * spectrogram will be computed on a random crop of the waveform. - * - * @param {Float32Array|Float64Array} waveform The input waveform. - * @param {number} max_length The maximum length of the waveform. - * @param {string} truncation The truncation strategy to use. - * @param {string} padding The padding strategy to use. - * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. - * @private - */ - async _get_input_mel(waveform, max_length, truncation, padding) { - - /** @type {Tensor} */ - let input_mel; - let longer = false; - const diff = waveform.length - max_length; - if (diff > 0) { - if (truncation === 'rand_trunc') { - longer = true; - const idx = Math.floor(Math.random() * (diff + 1)); - waveform = waveform.subarray(idx, idx + max_length); - - input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); - } else { - // TODO implement fusion strategy - throw new Error(`Truncation strategy "${truncation}" not implemented`) - } - } else { - if (diff < 0) { - let padded = new Float64Array(max_length); // already padded with zeros - padded.set(waveform); - - if (padding === 'repeat') { - for (let i = waveform.length; i < max_length; i += waveform.length) { - padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i); - } - } else if (padding === 'repeatpad') { - for (let i = waveform.length; i < -diff; i += waveform.length) { - padded.set(waveform, i); - } - } - waveform = padded; - } - - if (truncation === 'fusion') { - throw new Error(`Truncation strategy "${truncation}" not implemented`) - } - - input_mel = await this._extract_fbank_features(waveform, this.mel_filters_slaney, this.config.nb_max_samples); - } - - return input_mel.unsqueeze_(0); + } + function Lf(e, t, n) { + var o = P(); + try { + return Jo(e, t, n); + } catch (u) { + if (D(o), u !== u + 0) throw u; + W(1, 0); } - - /** - * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. - * In CLAP, two different filter banks are used depending on the truncation pattern: - * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from - * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` - * is set to `"fusion"`. - * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used - * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original - * implementation when the truncation mode is not `"fusion"`. - * - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @param {number[][]} mel_filters The mel filters to use. - * @param {number} [max_length=null] The maximum number of frames to return. - * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - async _extract_fbank_features(waveform, mel_filters, max_length = null) { - // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` - return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( - waveform, - this.window, // window - this.config.fft_window_size, // frame_length - this.config.hop_length, // hop_length - { - power: 2.0, - mel_filters, - log_mel: 'dB', - - // Custom - max_num_frames: max_length, - do_pad: false, - transpose: true, - } - ) + } + function Bf(e) { + var t = P(); + try { + jo(e); + } catch (n) { + if (D(t), n !== n + 0) throw n; + W(1, 0); } - - - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio, { - max_length = null, - } = {}) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'ClapFeatureExtractor'); - - // convert to mel spectrogram, truncate and pad if needed. - const padded_inputs = await this._get_input_mel( - audio, - max_length ?? this.config.nb_max_samples, - this.config.truncation, - this.config.padding, - ); - - return { - input_features: padded_inputs.unsqueeze_(0), - } + } + function Of(e, t) { + var n = P(); + try { + return qr(e, t); + } catch (o) { + if (D(n), o !== o + 0) throw o; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/clip/image_processing_clip.js": -/*!**************************************************!*\ - !*** ./src/models/clip/image_processing_clip.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ CLIPFeatureExtractor: () => (/* binding */ CLIPFeatureExtractor), -/* harmony export */ CLIPImageProcessor: () => (/* binding */ CLIPImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class CLIPImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class CLIPFeatureExtractor extends CLIPImageProcessor { } - - -/***/ }), - -/***/ "./src/models/convnext/image_processing_convnext.js": -/*!**********************************************************!*\ - !*** ./src/models/convnext/image_processing_convnext.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ConvNextFeatureExtractor: () => (/* binding */ ConvNextFeatureExtractor), -/* harmony export */ ConvNextImageProcessor: () => (/* binding */ ConvNextImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class ConvNextImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - constructor(config) { - super(config); - - /** - * Percentage of the image to crop. Only has an effect if this.size < 384. - */ - // @ts-expect-error TS2339 - this.crop_pct = this.config.crop_pct ?? (224 / 256); + } + function Mf(e, t, n) { + var o = P(); + try { + Vo(e, t, n); + } catch (u) { + if (D(o), u !== u + 0) throw u; + W(1, 0); } - - async resize(image) { - const shortest_edge = this.size?.shortest_edge; - if (shortest_edge === undefined) { - throw new Error(`Size dictionary must contain 'shortest_edge' key.`); - } - - if (shortest_edge < 384) { - // maintain same ratio, resizing shortest edge to shortest_edge/crop_pct - const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct); - - const [newWidth, newHeight] = this.get_resize_output_image_size(image, { - shortest_edge: resize_shortest_edge, - }); - - image = await image.resize(newWidth, newHeight, { - resample: this.resample, - }); - - // then crop to (shortest_edge, shortest_edge) - image = await image.center_crop(shortest_edge, shortest_edge); - } else { - // warping (no cropping) when evaluated at 384 or larger - image = await image.resize(shortest_edge, shortest_edge, { - resample: this.resample, - }); - } - - return image; + } + function Cf(e, t) { + var n = P(); + try { + Qo(e, t); + } catch (o) { + if (D(n), o !== o + 0) throw o; + W(1, 0); } -} -class ConvNextFeatureExtractor extends ConvNextImageProcessor { } - - -/***/ }), - -/***/ "./src/models/dac/feature_extraction_dac.js": -/*!**************************************************!*\ - !*** ./src/models/dac/feature_extraction_dac.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DacFeatureExtractor: () => (/* binding */ DacFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../encodec/feature_extraction_encodec.js */ "./src/models/encodec/feature_extraction_encodec.js"); - - -class DacFeatureExtractor extends _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_0__.EncodecFeatureExtractor { } - - -/***/ }), - -/***/ "./src/models/deit/image_processing_deit.js": -/*!**************************************************!*\ - !*** ./src/models/deit/image_processing_deit.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DeiTFeatureExtractor: () => (/* binding */ DeiTFeatureExtractor), -/* harmony export */ DeiTImageProcessor: () => (/* binding */ DeiTImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class DeiTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class DeiTFeatureExtractor extends DeiTImageProcessor { } - -/***/ }), - -/***/ "./src/models/detr/image_processing_detr.js": -/*!**************************************************!*\ - !*** ./src/models/detr/image_processing_detr.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DetrFeatureExtractor: () => (/* binding */ DetrFeatureExtractor), -/* harmony export */ DetrImageProcessor: () => (/* binding */ DetrImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - - -/** - * @typedef {object} DetrFeatureExtractorResultProps - * @property {import('../../utils/tensor.js').Tensor} pixel_mask - * @typedef {import('../../base/image_processors_utils.js').ImageProcessorResult & DetrFeatureExtractorResultProps} DetrFeatureExtractorResult - */ - -class DetrImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** - * Calls the feature extraction process on an array of images, preprocesses - * each image, and concatenates the resulting features into a single Tensor. - * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. - * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. - */ - async _call(images) { - const result = await super._call(images); - - // TODO support differently-sized images, for now assume all images are the same size. - // TODO support different mask sizes (not just 64x64) - // Currently, just fill pixel mask with 1s - const maskSize = [result.pixel_values.dims[0], 64, 64]; - const pixel_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)(maskSize, 1n); - - return { ...result, pixel_mask }; + } + function Df(e, t, n, o, u, c, h) { + var m = P(); + try { + return Yo(e, t, n, o, u, c, h); + } catch (y) { + if (D(m), y !== y + 0) throw y; + W(1, 0); } - - /** @type {typeof post_process_object_detection} */ - post_process_object_detection(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + } + function Pf(e, t, n, o, u, c) { + var h = P(); + try { + Ho(e, t, n, o, u, c); + } catch (m) { + if (D(h), m !== m + 0) throw m; + W(1, 0); } - - /** @type {typeof post_process_panoptic_segmentation} */ - post_process_panoptic_segmentation(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_panoptic_segmentation)(...args); + } + function Uf(e, t, n, o) { + var u = P(); + try { + Zo(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); } - - /** @type {typeof post_process_instance_segmentation} */ - post_process_instance_segmentation(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_instance_segmentation)(...args); + } + function _f(e, t, n, o, u, c, h) { + var m = P(); + try { + ta(e, t, n, o, u, c, h); + } catch (y) { + if (D(m), y !== y + 0) throw y; + W(1, 0); } -} - -class DetrFeatureExtractor extends DetrImageProcessor { } // NOTE: extends DetrImageProcessor - - -/***/ }), - -/***/ "./src/models/dinov3_vit/image_processing_dinov3_vit.js": -/*!**************************************************************!*\ - !*** ./src/models/dinov3_vit/image_processing_dinov3_vit.js ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DINOv3ViTImageProcessor: () => (/* binding */ DINOv3ViTImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class DINOv3ViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/donut/image_processing_donut.js": -/*!****************************************************!*\ - !*** ./src/models/donut/image_processing_donut.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DonutFeatureExtractor: () => (/* binding */ DonutFeatureExtractor), -/* harmony export */ DonutImageProcessor: () => (/* binding */ DonutImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class DonutImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - pad_image(pixelData, imgDims, padSize, options = {}) { - const [imageHeight, imageWidth, imageChannels] = imgDims; - - let image_mean = this.image_mean; - if (!Array.isArray(this.image_mean)) { - image_mean = new Array(imageChannels).fill(image_mean); - } - - let image_std = this.image_std; - if (!Array.isArray(image_std)) { - image_std = new Array(imageChannels).fill(image_mean); - } - - const constant_values = image_mean.map((x, i) => - x / image_std[i]); - - return super.pad_image(pixelData, imgDims, padSize, { - center: true, - - // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed. - // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451 - constant_values, - ...options, - }); + } + function Rf(e, t, n, o, u, c, h) { + var m = P(); + try { + ra(e, t, n, o, u, c, h); + } catch (y) { + if (D(m), y !== y + 0) throw y; + W(1, 0); } -} -class DonutFeatureExtractor extends DonutImageProcessor { } - - -/***/ }), - -/***/ "./src/models/dpt/image_processing_dpt.js": -/*!************************************************!*\ - !*** ./src/models/dpt/image_processing_dpt.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DPTFeatureExtractor: () => (/* binding */ DPTFeatureExtractor), -/* harmony export */ DPTImageProcessor: () => (/* binding */ DPTImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class DPTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class DPTFeatureExtractor extends DPTImageProcessor { } // NOTE: extends DPTImageProcessor - - -/***/ }), - -/***/ "./src/models/efficientnet/image_processing_efficientnet.js": -/*!******************************************************************!*\ - !*** ./src/models/efficientnet/image_processing_efficientnet.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EfficientNetImageProcessor: () => (/* binding */ EfficientNetImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class EfficientNetImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - constructor(config) { - super(config); - // @ts-expect-error TS2339 - this.include_top = this.config.include_top ?? true; - if (this.include_top) { - this.image_std = this.image_std.map(x => x * x); - } + } + function Nf(e, t, n, o, u, c, h, m) { + var y = P(); + try { + la(e, t, n, o, u, c, h, m); + } catch (x) { + if (D(y), x !== x + 0) throw x; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/encodec/feature_extraction_encodec.js": -/*!**********************************************************!*\ - !*** ./src/models/encodec/feature_extraction_encodec.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ EncodecFeatureExtractor: () => (/* binding */ EncodecFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - -class EncodecFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - /** - * Asynchronously extracts input values from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. - */ - async _call(audio) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'EncodecFeatureExtractor'); - - if (audio instanceof Float64Array) { - audio = new Float32Array(audio); - } - - const num_channels = this.config.feature_size; - if (audio.length % num_channels !== 0) { - throw new Error(`The length of the audio data must be a multiple of the number of channels (${num_channels}).`); - } - - const shape = [ - 1, /* batch_size */ - num_channels, /* num_channels */ - audio.length / num_channels, /* num_samples */ - ]; - return { - input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('float32', audio, shape), - }; + } + function Wf(e, t, n, o, u, c, h, m, y, x, N, F) { + var L = P(); + try { + na(e, t, n, o, u, c, h, m, y, x, N, F); + } catch (q) { + if (D(L), q !== q + 0) throw q; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/feature_extractors.js": -/*!******************************************!*\ - !*** ./src/models/feature_extractors.js ***! - \******************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ASTFeatureExtractor: () => (/* reexport safe */ _audio_spectrogram_transformer_feature_extraction_audio_spectrogram_transformer_js__WEBPACK_IMPORTED_MODULE_0__.ASTFeatureExtractor), -/* harmony export */ ClapFeatureExtractor: () => (/* reexport safe */ _clap_feature_extraction_clap_js__WEBPACK_IMPORTED_MODULE_2__.ClapFeatureExtractor), -/* harmony export */ DacFeatureExtractor: () => (/* reexport safe */ _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_3__.DacFeatureExtractor), -/* harmony export */ EncodecFeatureExtractor: () => (/* reexport safe */ _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_1__.EncodecFeatureExtractor), -/* harmony export */ Gemma3nAudioFeatureExtractor: () => (/* reexport safe */ _gemma3n_feature_extraction_gemma3n_js__WEBPACK_IMPORTED_MODULE_4__.Gemma3nAudioFeatureExtractor), -/* harmony export */ ImageFeatureExtractor: () => (/* reexport safe */ _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_13__.ImageProcessor), -/* harmony export */ MoonshineFeatureExtractor: () => (/* reexport safe */ _moonshine_feature_extraction_moonshine_js__WEBPACK_IMPORTED_MODULE_5__.MoonshineFeatureExtractor), -/* harmony export */ PyAnnoteFeatureExtractor: () => (/* reexport safe */ _pyannote_feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_6__.PyAnnoteFeatureExtractor), -/* harmony export */ SeamlessM4TFeatureExtractor: () => (/* reexport safe */ _seamless_m4t_feature_extraction_seamless_m4t_js__WEBPACK_IMPORTED_MODULE_7__.SeamlessM4TFeatureExtractor), -/* harmony export */ SnacFeatureExtractor: () => (/* reexport safe */ _snac_feature_extraction_snac_js__WEBPACK_IMPORTED_MODULE_8__.SnacFeatureExtractor), -/* harmony export */ SpeechT5FeatureExtractor: () => (/* reexport safe */ _speecht5_feature_extraction_speecht5_js__WEBPACK_IMPORTED_MODULE_9__.SpeechT5FeatureExtractor), -/* harmony export */ Wav2Vec2FeatureExtractor: () => (/* reexport safe */ _wav2vec2_feature_extraction_wav2vec2_js__WEBPACK_IMPORTED_MODULE_10__.Wav2Vec2FeatureExtractor), -/* harmony export */ WeSpeakerFeatureExtractor: () => (/* reexport safe */ _wespeaker_feature_extraction_wespeaker_js__WEBPACK_IMPORTED_MODULE_11__.WeSpeakerFeatureExtractor), -/* harmony export */ WhisperFeatureExtractor: () => (/* reexport safe */ _whisper_feature_extraction_whisper_js__WEBPACK_IMPORTED_MODULE_12__.WhisperFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _audio_spectrogram_transformer_feature_extraction_audio_spectrogram_transformer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js */ "./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"); -/* harmony import */ var _encodec_feature_extraction_encodec_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./encodec/feature_extraction_encodec.js */ "./src/models/encodec/feature_extraction_encodec.js"); -/* harmony import */ var _clap_feature_extraction_clap_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./clap/feature_extraction_clap.js */ "./src/models/clap/feature_extraction_clap.js"); -/* harmony import */ var _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dac/feature_extraction_dac.js */ "./src/models/dac/feature_extraction_dac.js"); -/* harmony import */ var _gemma3n_feature_extraction_gemma3n_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gemma3n/feature_extraction_gemma3n.js */ "./src/models/gemma3n/feature_extraction_gemma3n.js"); -/* harmony import */ var _moonshine_feature_extraction_moonshine_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./moonshine/feature_extraction_moonshine.js */ "./src/models/moonshine/feature_extraction_moonshine.js"); -/* harmony import */ var _pyannote_feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./pyannote/feature_extraction_pyannote.js */ "./src/models/pyannote/feature_extraction_pyannote.js"); -/* harmony import */ var _seamless_m4t_feature_extraction_seamless_m4t_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./seamless_m4t/feature_extraction_seamless_m4t.js */ "./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"); -/* harmony import */ var _snac_feature_extraction_snac_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./snac/feature_extraction_snac.js */ "./src/models/snac/feature_extraction_snac.js"); -/* harmony import */ var _speecht5_feature_extraction_speecht5_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./speecht5/feature_extraction_speecht5.js */ "./src/models/speecht5/feature_extraction_speecht5.js"); -/* harmony import */ var _wav2vec2_feature_extraction_wav2vec2_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./wav2vec2/feature_extraction_wav2vec2.js */ "./src/models/wav2vec2/feature_extraction_wav2vec2.js"); -/* harmony import */ var _wespeaker_feature_extraction_wespeaker_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./wespeaker/feature_extraction_wespeaker.js */ "./src/models/wespeaker/feature_extraction_wespeaker.js"); -/* harmony import */ var _whisper_feature_extraction_whisper_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./whisper/feature_extraction_whisper.js */ "./src/models/whisper/feature_extraction_whisper.js"); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - - - - - - - - - - - - - -// For legacy support, ImageFeatureExtractor is an alias for ImageProcessor - - - -/***/ }), - -/***/ "./src/models/florence2/processing_florence2.js": -/*!******************************************************!*\ - !*** ./src/models/florence2/processing_florence2.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Florence2Processor: () => (/* binding */ Florence2Processor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); - - - - -class Florence2Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - - constructor(config, components, chat_template) { - super(config, components, chat_template); - - const { - // @ts-expect-error TS2339 - tasks_answer_post_processing_type, - // @ts-expect-error TS2339 - task_prompts_without_inputs, - // @ts-expect-error TS2339 - task_prompts_with_input, - } = this.image_processor.config; - - /** @type {Map} */ - this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {})); - - /** @type {Map} */ - this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {})); - - /** @type {Map} */ - this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {})); - - this.regexes = { - quad_boxes: /(.+?)/gm, - bboxes: /([^<]+)?/gm, - } - this.size_per_bin = 1000; + } + function kf(e, t, n, o, u) { + var c = P(); + try { + return ea(e, t, n, o, u); + } catch (h) { + if (D(c), h !== h + 0) throw h; + W(1, 0); + } + } + function Ff(e, t, n, o, u, c) { + var h = P(); + try { + pa(e, t, n, o, u, c); + } catch (m) { + if (D(h), m !== m + 0) throw m; + W(1, 0); + } + } + function Gf(e, t, n, o, u) { + var c = P(); + try { + qo(e, t, n, o, u); + } catch (h) { + if (D(c), h !== h + 0) throw h; + W(1, 0); } - - /** - * Helper function to construct prompts from input texts - * @param {string|string[]} text - * @returns {string[]} - */ - construct_prompts(text) { - if (typeof text === 'string') { - text = [text]; - } - - const prompts = []; - for (const t of text) { - // 1. fixed task prompts without additional inputs - if (this.task_prompts_without_inputs.has(t)) { - prompts.push(this.task_prompts_without_inputs.get(t)); - } - // 2. task prompts with additional inputs - else { - for (const [task, prompt] of this.task_prompts_with_input) { - if (t.includes(task)) { - prompts.push(prompt.replaceAll('{input}', t).replaceAll(task, '')); - break; - } - } - - // 3. default prompt - if (prompts.length !== text.length) { - prompts.push(t); - } - } - } - return prompts; + } + function $f(e, t, n, o, u, c, h, m) { + var y = P(); + try { + Xo(e, t, n, o, u, c, h, m); + } catch (x) { + if (D(y), x !== x + 0) throw x; + W(1, 0); } - - /** - * Post-process the output of the model to each of the task outputs. - * @param {string} text The text to post-process. - * @param {string} task The task to post-process the text for. - * @param {[number, number]} image_size The size of the image. height x width. - */ - post_process_generation(text, task, image_size) { - const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? 'pure_text'; - - // remove the special tokens - text = text.replaceAll('', '').replaceAll('', ''); - - let final_answer; - switch (task_answer_post_processing_type) { - case 'pure_text': - final_answer = text; - break; - - case 'description_with_bboxes': - case 'bboxes': - case 'phrase_grounding': - case 'ocr': - const key = task_answer_post_processing_type === 'ocr' ? 'quad_boxes' : 'bboxes'; - const matches = text.matchAll(this.regexes[key]); - const labels = []; - const items = []; - for (const [_, label, ...locations] of matches) { - // Push new label, or duplicate the last label - labels.push(label ? label.trim() : labels.at(-1) ?? ''); - items.push(locations.map((x, i) => - // NOTE: Add 0.5 to use the center position of the bin as the coordinate. - (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2]) - ); - } - final_answer = { labels, [key]: items }; - break; - - default: - throw new Error(`Task "${task}" (of type "${task_answer_post_processing_type}") not yet implemented.`); - } - - return { [task]: final_answer } + } + function zf(e) { + var t = P(); + try { + return ma(e); + } catch (n) { + if (D(t), n !== n + 0) throw n; + W(1, 0); } - - // NOTE: images and text are switched from the python version - // `images` is required, `text` is optional - async _call(images, text=null, kwargs = {}) { - - if (!images && !text){ - throw new Error('Either text or images must be provided'); - } - - const image_inputs = await this.image_processor(images, kwargs); - const text_inputs = text ? this.tokenizer(this.construct_prompts(text), kwargs) : {}; - - return { - ...image_inputs, - ...text_inputs, - } + } + function Vf(e, t, n, o, u, c, h, m, y) { + var x = P(); + try { + aa(e, t, n, o, u, c, h, m, y); + } catch (N) { + if (D(x), N !== N + 0) throw N; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/gemma3n/feature_extraction_gemma3n.js": -/*!**********************************************************!*\ - !*** ./src/models/gemma3n/feature_extraction_gemma3n.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Gemma3nAudioFeatureExtractor: () => (/* binding */ Gemma3nAudioFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); - - - - -class Gemma3nAudioFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - - constructor(config) { - super(config); - - const { - fft_length, feature_size, min_frequency, max_frequency, sampling_rate, frame_length - } = this.config; - - const mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - Math.floor(1 + fft_length / 2), // num_frequency_bins - feature_size, // num_mel_filters - min_frequency, // min_frequency - max_frequency, // max_frequency - sampling_rate, // sampling_rate - null, // norm - "htk", // mel_scale - false, // triangularize_in_mel_space - ); - this.mel_filters = mel_filters; - - this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(frame_length, 'hann') + } + function jf(e, t, n) { + var o = P(); + try { + return ha(e, t, n); + } catch (u) { + if (D(o), u !== u + 0) throw u; + W(1, 0); } - - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @param {number} max_length The maximum number of frames to return. - * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - async _extract_fbank_features(waveform, max_length) { - // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` - return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( - waveform, - this.window, // window - this.config.frame_length, // frame_length - this.config.hop_length, // hop_length - { - fft_length: this.config.fft_length, - center: false, - onesided: true, - preemphasis: this.config.preemphasis, - preemphasis_htk_flavor: this.config.preemphasis_htk_flavor, - mel_filters: this.mel_filters, - log_mel: 'log', - mel_floor: this.config.mel_floor, - remove_dc_offset: false, - - // Custom - transpose: true, - } - ) + } + function Hf(e, t) { + var n = P(); + try { + return La(e, t); + } catch (o) { + if (D(n), o !== o + 0) throw o; + return W(1, 0), 0n; } - - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @param {Object} options Optional parameters for feature extraction. - * @param {number} [options.max_length=480_000] If provided, defines the maximum length of the audio to allow. - * Audio longer than this will be truncated if `truncation=True`. - * @param {boolean} [options.truncation=true] Whether or not to truncate audio above `max_length`. - * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. - * @param {number} [options.pad_to_multiple_of=128] The number to pad the sequence to a multiple of. - * @returns {Promise<{ input_features: Tensor, input_features_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. - */ - async _call(audio, { - max_length = 480_000, - truncation=true, - padding = true, - pad_to_multiple_of = 128, - } = {}) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'Gemma3nAudioFeatureExtractor'); - if (truncation && audio.length > max_length) { - audio = audio.slice(0, max_length); - } - if (padding && audio.length % pad_to_multiple_of !== 0) { - const padding_length = pad_to_multiple_of - (audio.length % pad_to_multiple_of); - const padded_audio = new Float64Array(audio.length + padding_length); - padded_audio.set(audio); - if (this.config.padding_value !== 0) { - padded_audio.fill(this.config.padding_value, audio.length); - } - audio = padded_audio; - } - - const features = await this._extract_fbank_features(audio, this.config.max_length); - const padded_attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([1, features.dims[0]], true); - return { - input_features: features.unsqueeze_(0), - input_features_mask: padded_attention_mask, - } + } + function qf(e, t, n, o) { + var u = P(); + try { + return ba(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/gemma3n/processing_gemma3n.js": -/*!**************************************************!*\ - !*** ./src/models/gemma3n/processing_gemma3n.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Gemma3nProcessor: () => (/* binding */ Gemma3nProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils/image.js */ "./src/utils/image.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); - - - - - - - - -class Gemma3nProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor; - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoFeatureExtractor; - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AutoTokenizer; - static uses_processor_config = true; - static uses_chat_template_file = true; - - constructor(config, components, chat_template) { - super(config, components, chat_template); - this.audio_seq_length = this.config.audio_seq_length; - this.image_seq_length = this.config.image_seq_length; - - const { - // Audio tokens - audio_token_id, boa_token, audio_token, eoa_token, - - // Image tokens - image_token_id, boi_token, image_token, eoi_token - } = this.tokenizer.config; - - this.audio_token_id = audio_token_id - this.boa_token = boa_token - this.audio_token = audio_token - const audio_tokens_expanded = audio_token.repeat(this.audio_seq_length); - this.full_audio_sequence = `\n\n${boa_token}${audio_tokens_expanded}${eoa_token}\n\n` - - this.image_token_id = image_token_id - this.boi_token = boi_token - this.image_token = image_token - const image_tokens_expanded = image_token.repeat(this.image_seq_length); - this.full_image_sequence = `\n\n${boi_token}${image_tokens_expanded}${eoi_token}\n\n` + } + function Yf(e) { + var t = P(); + try { + return oa(e); + } catch (n) { + if (D(t), n !== n + 0) throw n; + return W(1, 0), 0n; } - - /** - * - * @param {string|string[]} text - * @param {RawImage|RawImage[]|RawImage[][]} images - * @param {RawAudio|RawAudio[]|RawAudio[][]} audio - * @returns {Promise} - */ - async _call(text, images = null, audio = null, options = {}) { - - if (typeof text === 'string') { - text = [text]; - } - - let audio_inputs; - if (audio) { - audio_inputs = await this.feature_extractor(audio, options); - - text = text.map(prompt => prompt.replaceAll(this.audio_token, this.full_audio_sequence)); - } - let image_inputs; - if (images) { - image_inputs = await this.image_processor(images, options); - text = text.map(prompt => prompt.replaceAll(this.image_token, this.full_image_sequence)); - } - - let text_inputs = this.tokenizer(text, options); - return { - ...text_inputs, - ...image_inputs, - ...audio_inputs, - } + } + function Jf(e, t, n, o) { + var u = P(); + try { + return ga(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/glpn/image_processing_glpn.js": -/*!**************************************************!*\ - !*** ./src/models/glpn/image_processing_glpn.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ GLPNFeatureExtractor: () => (/* binding */ GLPNFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class GLPNFeatureExtractor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/grounding_dino/image_processing_grounding_dino.js": -/*!**********************************************************************!*\ - !*** ./src/models/grounding_dino/image_processing_grounding_dino.js ***! - \**********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ GroundingDinoImageProcessor: () => (/* binding */ GroundingDinoImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - - -/** - * @typedef {object} GroundingDinoFeatureExtractorResultProps - * @property {import('../../utils/tensor.js').Tensor} pixel_mask - * @typedef {import('../../base/image_processors_utils.js').ImageProcessorResult & GroundingDinoFeatureExtractorResultProps} GroundingDinoFeatureExtractorResult - */ - -class GroundingDinoImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** - * Calls the feature extraction process on an array of images, preprocesses - * each image, and concatenates the resulting features into a single Tensor. - * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. - * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. - */ - async _call(images) { - const result = await super._call(images); - - const dims = result.pixel_values.dims; - const pixel_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.ones)([dims[0], dims[2], dims[3]]); - - return { ...result, pixel_mask }; + } + function Xf(e, t, n, o, u) { + var c = P(); + try { + return ya(e, t, n, o, u); + } catch (h) { + if (D(c), h !== h + 0) throw h; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/grounding_dino/processing_grounding_dino.js": -/*!****************************************************************!*\ - !*** ./src/models/grounding_dino/processing_grounding_dino.js ***! - \****************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ GroundingDinoProcessor: () => (/* binding */ GroundingDinoProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - - - -/** - * Get token ids of phrases from posmaps and input_ids. - * @param {import('../../utils/tensor.js').Tensor} posmaps A boolean tensor of unbatched text-thresholded logits related to the detected bounding boxes of shape `(hidden_size, )`. - * @param {import('../../utils/tensor.js').Tensor} input_ids A tensor of token ids of shape `(sequence_length, )`. - */ -function get_phrases_from_posmap(posmaps, input_ids) { - - const left_idx = 0; - const right_idx = posmaps.dims.at(-1) - 1; - - const posmaps_list = posmaps.tolist(); - posmaps_list.fill(false, 0, left_idx + 1); - posmaps_list.fill(false, right_idx); - - const input_ids_list = input_ids.tolist(); - return posmaps_list - .map((val, idx) => val ? idx : null) - .filter(idx => idx !== null) - .map(i => input_ids_list[i]); -} - -class GroundingDinoProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - - /** - * @typedef {import('../../utils/image.js').RawImage} RawImage - */ - /** - * - * @param {RawImage|RawImage[]|RawImage[][]} images - * @param {string|string[]} text - * @returns {Promise} - */ - async _call(images, text, options = {}) { - - const image_inputs = images ? await this.image_processor(images, options) : {}; - const text_inputs = text ? this.tokenizer(text, options) : {}; - - return { - ...text_inputs, - ...image_inputs, - } + } + function Zf(e, t, n, o, u, c) { + var h = P(); + try { + return wa(e, t, n, o, u, c); + } catch (m) { + if (D(h), m !== m + 0) throw m; + W(1, 0); } - post_process_grounded_object_detection(outputs, input_ids, { - box_threshold = 0.25, - text_threshold = 0.25, - target_sizes = null - } = {}) { - const { logits, pred_boxes } = outputs; - const batch_size = logits.dims[0]; - - if (target_sizes !== null && target_sizes.length !== batch_size) { - throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits") - } - const num_queries = logits.dims.at(1); - - const probs = logits.sigmoid(); // (batch_size, num_queries, 256) - const scores = probs.max(-1).tolist(); // (batch_size, num_queries) - - // Convert to [x0, y0, x1, y1] format - const boxes = pred_boxes.tolist() // (batch_size, num_queries, 4) - .map(batch => batch.map(box => (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_3__.center_to_corners_format)(box))); - - const results = []; - for (let i = 0; i < batch_size; ++i) { - const target_size = target_sizes !== null ? target_sizes[i] : null; - - // Convert from relative [0, 1] to absolute [0, height] coordinates - if (target_size !== null) { - boxes[i] = boxes[i].map(box => box.map((x, j) => x * target_size[(j + 1) % 2])); - } - - const batch_scores = scores[i]; - const final_scores = []; - const final_phrases = []; - const final_boxes = []; - for (let j = 0; j < num_queries; ++j) { - const score = batch_scores[j]; - if (score <= box_threshold) { - continue; - } - const box = boxes[i][j]; - const prob = probs[i][j]; - - final_scores.push(score); - final_boxes.push(box); - - const phrases = get_phrases_from_posmap(prob.gt(text_threshold), input_ids[i]); - final_phrases.push(phrases); - } - results.push({ scores: final_scores, boxes: final_boxes, labels: this.batch_decode(final_phrases) }); - } - return results; + } + function Kf(e, t, n, o, u, c) { + var h = P(); + try { + return ca(e, t, n, o, u, c); + } catch (m) { + if (D(h), m !== m + 0) throw m; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/idefics3/image_processing_idefics3.js": -/*!**********************************************************!*\ - !*** ./src/models/idefics3/image_processing_idefics3.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Idefics3ImageProcessor: () => (/* binding */ Idefics3ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - - -class Idefics3ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - constructor(config) { - super(config); - - this.do_image_splitting = config.do_image_splitting ?? true; - this.max_image_size = config.max_image_size; + } + function Qf(e, t, n, o, u, c) { + var h = P(); + try { + return Ta(e, t, n, o, u, c); + } catch (m) { + if (D(h), m !== m + 0) throw m; + W(1, 0); } - - /** - * @typedef {import('../../utils/image.js').RawImage} RawImage - * @typedef {import('../../utils/tensor.js').Tensor} Tensor - */ - - /** - * Calculate size to resize images to, to be multiples of `vision_encoder_max_size` while preserving the aspect ratio. - * @param {Tensor} pixel_values Tensor of the image to resize. - * @param {number} vision_encoder_max_size Maximum size of the output image. If the image is larger than this size, - * it will be split into patches of this size, and the original image will be concatenated with the patches, resized to max_size. - */ - get_resize_for_vision_encoder(pixel_values, vision_encoder_max_size) { - let [height, width] = pixel_values.dims.slice(-2); - - const aspect_ratio = width / height; - if (width >= height) { - width = Math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size; - height = Math.floor(width / aspect_ratio); - height = Math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size; - } else { - height = Math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size; - width = Math.floor(height * aspect_ratio); - width = Math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size; - } - return { height, width }; + } + function ec(e, t, n, o, u, c, h, m) { + var y = P(); + try { + return da(e, t, n, o, u, c, h, m); + } catch (x) { + if (D(y), x !== x + 0) throw x; + W(1, 0); } - - /** @param {RawImage|RawImage[]|RawImage[][]} images */ - async _call(images, { - do_image_splitting = null, - return_row_col_info = false, - } = {}) { - - /** @type {RawImage[][]} */ - let batched_2d_images; - if (!Array.isArray(images)) { - batched_2d_images = [[images]]; - } else { - if (images.length === 0 || !images[0]) { - throw new Error("No images provided."); - } - if (!Array.isArray(images[0])) { - batched_2d_images = [/** @type {RawImage[]} */(images)]; - } else { - batched_2d_images = /** @type {RawImage[][]} */(images); - } - } - - // List of tensors, each with shape [patches, channels, height, width] - let all_pixel_values = []; - let images_list_rows = []; - let images_list_cols = []; - - const original_sizes = []; - const reshaped_input_sizes = []; - for (const image_batch of batched_2d_images) { - - let images_list = await Promise.all(image_batch.map(x => this.preprocess(x))); - - // Original sizes of images - original_sizes.push(...images_list.map(x => x.original_size)); - - // Reshaped sizes of images, before padding or cropping - reshaped_input_sizes.push(...images_list.map(x => x.reshaped_input_size)); - - // Convert images to 4D tensors for easier processing - images_list.forEach(x => x.pixel_values.unsqueeze_(0)); - - const { longest_edge } = this.max_image_size; - - /** @type {Tensor[]} */ - let images_tensor; - if (do_image_splitting ?? this.do_image_splitting) { - let image_rows = new Array(images_list.length); - let image_cols = new Array(images_list.length); - - // We first resize both height and width of each image to the nearest max_image_size multiple, disregarding the aspect ratio - images_tensor = await Promise.all(images_list.map(async (x, i) => { - const new_size = this.get_resize_for_vision_encoder(x.pixel_values, longest_edge); - - const resized = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(x.pixel_values, { - size: [new_size.height, new_size.width], - }); - - const { frames, num_splits_h, num_splits_w } = await this.split_image(resized, this.max_image_size); - image_rows[i] = num_splits_h; - image_cols[i] = num_splits_w; - return (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(frames, 0); - })); - - images_list_rows.push(image_rows); - images_list_cols.push(image_cols); - - } else { - /** @type {[number, number]} */ - const size = [longest_edge, longest_edge]; - images_tensor = await Promise.all( - images_list.map(x => (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(x.pixel_values, { size })) - ); - - images_list_rows.push(new Array(images_list.length).fill(0)); - images_list_cols.push(new Array(images_list.length).fill(0)); - } - - all_pixel_values.push((0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(images_tensor, 0)); - } - - const batch_size = all_pixel_values.length; - const [n, c, h, w] = all_pixel_values[0].dims; - - // Stack pixel values - let pixel_values; - let pixel_attention_mask; - if (batch_size === 1) { - pixel_values = all_pixel_values[0].unsqueeze_(0); - pixel_attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([batch_size, n, h, w], true); - } else { - // Add padding (if necessary) to images with less patches than the maximum number of patches - const max_num_patches = Math.max(...all_pixel_values.map(x => x.dims.at(0))); - - pixel_attention_mask = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([batch_size, max_num_patches, h, w], true); - const pixel_attention_mask_data = pixel_attention_mask.data; - const pixel_attention_mask_stride = max_num_patches * h * w; - for (let i = 0; i < batch_size; ++i) { - const num_patches = all_pixel_values[i].dims[0]; - if (num_patches < max_num_patches) { - all_pixel_values[i] = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)([ - all_pixel_values[i], - (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.full)([max_num_patches - num_patches, c, h, w], 0), - ], 0); - - const start_offset = i * pixel_attention_mask_stride + num_patches * h * w; - const end_offset = (i + 1) * pixel_attention_mask_stride; - - // @ts-ignore - pixel_attention_mask_data.fill(false, start_offset, end_offset); - } - } - pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(all_pixel_values, 0); - } - - return { - pixel_values, - pixel_attention_mask, - - original_sizes, - reshaped_input_sizes, - ...( - return_row_col_info - ? { rows: images_list_rows, cols: images_list_cols } - : {} - ), - } + } + function tc(e, t, n, o, u) { + var c = P(); + try { + return va(e, t, n, o, u); + } catch (h) { + if (D(c), h !== h + 0) throw h; + return W(1, 0), 0n; + } + } + function rc(e, t, n, o) { + var u = P(); + try { + return Ea(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); + } + } + function nc(e, t, n, o) { + var u = P(); + try { + return Sa(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); + } + } + function oc(e, t, n, o, u, c, h, m, y, x, N, F) { + var L = P(); + try { + return xa(e, t, n, o, u, c, h, m, y, x, N, F); + } catch (q) { + if (D(L), q !== q + 0) throw q; + W(1, 0); + } + } + function ac(e, t, n, o, u, c, h, m, y, x, N) { + var F = P(); + try { + Aa(e, t, n, o, u, c, h, m, y, x, N); + } catch (L) { + if (D(F), L !== L + 0) throw L; + W(1, 0); + } + } + function sc(e, t, n, o, u, c, h, m, y, x, N, F, L, q, he, de) { + var Qe = P(); + try { + Ia(e, t, n, o, u, c, h, m, y, x, N, F, L, q, he, de); + } catch (et) { + if (D(Qe), et !== et + 0) throw et; + W(1, 0); + } + } + function ic(e, t, n) { + var o = P(); + try { + return ia(e, t, n); + } catch (u) { + if (D(o), u !== u + 0) throw u; + return W(1, 0), 0n; + } + } + function uc(e, t, n) { + var o = P(); + try { + return sa(e, t, n); + } catch (u) { + if (D(o), u !== u + 0) throw u; + W(1, 0); + } + } + function fc(e, t, n) { + var o = P(); + try { + return ua(e, t, n); + } catch (u) { + if (D(o), u !== u + 0) throw u; + W(1, 0); } - - async split_image(pixel_values, { longest_edge }) { - const max_height = longest_edge; - const max_width = longest_edge; - - const frames = []; - - const [height, width] = pixel_values.dims.slice(-2); - - let num_splits_h = 0, num_splits_w = 0; - - if (height > max_height || width > max_width) { - // Calculate the number of splits - num_splits_h = Math.ceil(height / max_height); - num_splits_w = Math.ceil(width / max_width); - - // Calculate the optimal width and height for the sub-images - const optimal_height = Math.ceil(height / num_splits_h); - const optimal_width = Math.ceil(width / num_splits_w); - - // Iterate through each row and column - for (let r = 0; r < num_splits_h; ++r) { - for (let c = 0; c < num_splits_w; ++c) { - let start_x, start_y, end_x, end_y; - if (r === num_splits_h - 1) { // At bottom - start_y = height - optimal_height; - end_y = height; - } else { - start_y = r * optimal_height; - end_y = (r + 1) * optimal_height; - } - if (c === num_splits_w - 1) { // At right - start_x = width - optimal_width; - end_x = width; - } else { - start_x = c * optimal_width; - end_x = (c + 1) * optimal_width; - } - - const starts = [start_y, start_x]; - const ends = [end_y, end_x]; - - const patch = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.slice)(pixel_values, starts, ends, [2, 3]); - frames.push(patch); - } - } - - // Resize the global image to match max dimensions for memory efficiency - const global_image_height = max_height; - const global_image_width = max_width; - - if (height !== global_image_height || width !== global_image_width) { - pixel_values = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(pixel_values, { - size: [global_image_height, global_image_width], - }) - } - } - - frames.push(pixel_values); - - return { frames, num_splits_h, num_splits_w }; + } + function cc(e, t, n, o) { + var u = P(); + try { + fa(e, t, n, o); + } catch (c) { + if (D(u), c !== c + 0) throw c; + W(1, 0); } -} - - -/***/ }), - -/***/ "./src/models/idefics3/processing_idefics3.js": -/*!****************************************************!*\ - !*** ./src/models/idefics3/processing_idefics3.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Idefics3Processor: () => (/* binding */ Idefics3Processor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/image.js */ "./src/utils/image.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils/core.js */ "./src/utils/core.js"); - - - - - - - -/** - * Prompt with expanded image tokens for when the image is split into patches. - * @private - */ -function _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token) { - let text_split_images = ""; - for (let n_h = 0; n_h < image_rows; ++n_h) { - for (let n_w = 0; n_w < image_cols; ++n_w) { - text_split_images += ( - fake_token_around_image + - `` + - image_token.repeat(image_seq_len) - ); - } - text_split_images += "\n"; + } + function jt() { + if (0 < Be) re = jt; + else if (i) C?.(r), wr(); + else { + for (var e = xe; 0 < e.length; ) e.shift()(r); + 0 < Be ? re = jt : (r.calledRun = true, $ || (wr(), C?.(r))); } - - text_split_images += ( - `\n${fake_token_around_image}` + - `${global_img_token}` + - image_token.repeat(image_seq_len) + - `${fake_token_around_image}` - ); - return text_split_images; -} - -/** - * Prompt with expanded image tokens for a single image. - * @private - */ -function _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token) { - return ( - `${fake_token_around_image}` + - `${global_img_token}` + - image_token.repeat(image_seq_len) + - `${fake_token_around_image}` - ); + } + return i || (Ne = await wt(), jt()), r.PTR_SIZE = 4, r.webgpuInit = (e) => { + let t = /* @__PURE__ */ new WeakMap(), n, o, u = 1; + r.webgpuRegisterDevice = (m) => { + if (o !== void 0) throw Error("another WebGPU EP inference session is being created."); + if (m) { + var y = t.get(m); + if (!y) { + let x = ((N, F = 0) => { + var L = Po(F); + return F = Do(F, L), fe[L >>> 0] = N.queue, fe[F >>> 0] = N, F; + })(m, y = Eo()); + y = [u++, y, x], t.set(m, y); + } + return n = m, o = y[0], y; + } + n = void 0, o = 0; + }; + let c = /* @__PURE__ */ new Map(); + r.webgpuOnCreateSession = (m) => { + if (o !== void 0) { + var y = o; + if (o = void 0, m) { + let x = Nr(y); + c.set(m, x), y === 0 && e(n ?? B(x)); + } + n = void 0; + } + }, r.webgpuOnReleaseSession = (m) => { + c.delete(m); + }; + let h = /* @__PURE__ */ Symbol("gpuBufferMetadata"); + r.webgpuRegisterBuffer = (m, y, x) => { + if (x) return m[h] = [x, NaN], x; + if (x = m[h]) return x[1]++, x[0]; + if ((y = c.get(y)) === void 0) throw Error("Invalid session handle passed to webgpuRegisterBuffer"); + return y = ((N, F = 0) => (N.mapState === "unmapped" || we(), F = Co(F), fe[F >>> 0] = N, F))(m, y), m[h] = [y, 1], y; + }, r.webgpuUnregisterBuffer = (m) => { + let y = m[h]; + if (!y) throw Error("Buffer is not registered"); + y[1]--, y[1] === 0 && (So(y[0]), delete m[h]); + }, r.webgpuGetBuffer = (m) => B(m), r.webgpuCreateDownloader = (m, y, x) => { + if ((x = c.get(x)) === void 0) throw Error("Invalid session handle passed to webgpuRegisterBuffer"); + let N = B(x), F = 16 * Math.ceil(Number(y) / 16); + return async () => { + let L = N.createBuffer({ size: F, usage: 9 }); + try { + let q = N.createCommandEncoder(); + return q.copyBufferToBuffer(m, 0, L, 0, F), N.queue.submit([q.finish()]), await L.mapAsync(GPUMapMode.READ), L.getMappedRange().slice(0, y); + } finally { + L.destroy(); + } + }; + }, r.pe = (m, y) => { + var x = y.buffer; + let N = y.byteOffset, F = y.byteLength; + if (y = 16 * Math.ceil(Number(F) / 16), m = B(m), !n) { + var L = Nr(o); + n = B(L); + } + let q = (L = n.createBuffer({ mappedAtCreation: true, size: y, usage: 6 })).getMappedRange(); + new Uint8Array(q).set(new Uint8Array(x, N, F)), L.unmap(), (x = n.createCommandEncoder()).copyBufferToBuffer(L, 0, m, 0, y), n.queue.submit([x.finish()]), L.destroy(); + }; + }, r.webnnInit = (e) => { + let t = e[0]; + [r.Pe, r.qe, r.webnnEnsureTensor, r.re, r.webnnDownloadTensor, r.Oe, r.webnnEnableTraceEvent] = e.slice(1), r.webnnReleaseTensorId = r.qe, r.webnnUploadTensor = r.re, r.webnnRegisterMLContext = r.Oe, r.webnnOnRunStart = (n) => t.onRunStart(n), r.webnnOnRunEnd = t.onRunEnd.bind(t), r.webnnOnReleaseSession = (n) => { + t.onReleaseSession(n); + }, r.webnnCreateMLTensorDownloader = (n, o) => t.createMLTensorDownloader(n, o), r.webnnRegisterMLTensor = (n, o, u, c) => t.registerMLTensor(n, o, u, c), r.webnnCreateMLContext = (n) => t.createMLContext(n), r.webnnRegisterGraphInput = t.registerGraphInput.bind(t), r.webnnIsGraphInput = t.isGraphInput.bind(t), r.webnnRegisterGraphOutput = t.registerGraphOutput.bind(t), r.webnnIsGraphOutput = t.isGraphOutput.bind(t), r.webnnCreateTemporaryTensor = t.createTemporaryTensor.bind(t), r.webnnIsGraphInputOutputTypeSupported = t.isGraphInputOutputTypeSupported.bind(t); + }, ne ? r : new Promise((e, t) => { + C = e, _ = t; + }); } - -function get_image_prompt_string(image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_img_token) { - if (image_rows === 0 && image_cols === 0) { - return _prompt_single_image( - image_seq_len, - fake_token_around_image, - image_token, - global_img_token - ); +var yc; +var wc; +var ms = G(() => { + "use strict"; + yc = ls, wc = globalThis.self?.name?.startsWith("em-pthread"); + wc && ls(); +}); +var gs; +var an; +var Tc; +var ye; +var ys; +var on; +var vc; +var Ec; +var ws; +var Sc; +var hs; +var Ts; +var bs; +var vs; +var Zt = G(() => { + "use strict"; + Xt(); + gs = typeof location > "u" ? void 0 : location.origin, an = import.meta.url > "file:" && import.meta.url < "file;", Tc = () => { + if (true) { + if (an) { + let a = URL; + return new URL(new a("ort.webgpu.bundle.min.mjs", import.meta.url).href, gs).href; + } + return import.meta.url; } - return _prompt_split_image( - image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token - ); -} - - -class Idefics3Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static uses_processor_config = true; - - fake_image_token = ""; - image_token = ""; - global_img_token = ""; - - /** - * - * @param {string|string[]} text - * @param {RawImage|RawImage[]|RawImage[][]} images - * @returns {Promise} - */ - async _call(text, images = null, options = {}) { - options.return_row_col_info ??= true; - - let image_inputs; - - if (images) { - image_inputs = await this.image_processor(images, options); - } - - // NOTE: We assume text is present - if (!Array.isArray(text)) { - text = [text]; - } - - const image_rows = image_inputs.rows ?? [new Array(text.length).fill(0)]; - const image_cols = image_inputs.cols ?? [new Array(text.length).fill(0)]; - - const image_seq_len = this.config.image_seq_len; - const n_images_in_text = [] - const prompt_strings = []; - for (let i = 0; i < text.length; ++i) { - const sample = text[i]; - const sample_rows = image_rows[i]; - const sample_cols = image_cols[i]; - - n_images_in_text.push((0,_utils_core_js__WEBPACK_IMPORTED_MODULE_4__.count)(sample, this.image_token)); - - // Replace the image token with fake tokens around the expanded image token sequence of length `image_seq_len` - const image_prompt_strings = sample_rows.map( - (n_rows, j) => get_image_prompt_string( - n_rows, - sample_cols[j], - image_seq_len, - this.fake_image_token, - this.image_token, - this.global_img_token, - ) - ); - - const split_sample = sample.split(this.image_token); - if (split_sample.length === 0) { - throw new Error("The image token should be present in the text."); - } - - // Place in the image prompt strings where the image tokens are - let new_sample = split_sample[0]; - for (let j = 0; j < image_prompt_strings.length; ++j) { - new_sample += image_prompt_strings[j] + split_sample[j + 1]; - } - prompt_strings.push(new_sample); - } - - const text_inputs = this.tokenizer(prompt_strings); - - return { - ...text_inputs, - ...image_inputs, - } - } -} - - -/***/ }), - -/***/ "./src/models/image_processors.js": -/*!****************************************!*\ - !*** ./src/models/image_processors.js ***! - \****************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ BeitFeatureExtractor: () => (/* reexport safe */ _beit_image_processing_beit_js__WEBPACK_IMPORTED_MODULE_0__.BeitFeatureExtractor), -/* harmony export */ BitImageProcessor: () => (/* reexport safe */ _bit_image_processing_bit_js__WEBPACK_IMPORTED_MODULE_1__.BitImageProcessor), -/* harmony export */ CLIPFeatureExtractor: () => (/* reexport safe */ _clip_image_processing_clip_js__WEBPACK_IMPORTED_MODULE_3__.CLIPFeatureExtractor), -/* harmony export */ CLIPImageProcessor: () => (/* reexport safe */ _clip_image_processing_clip_js__WEBPACK_IMPORTED_MODULE_3__.CLIPImageProcessor), -/* harmony export */ ChineseCLIPFeatureExtractor: () => (/* reexport safe */ _chinese_clip_image_processing_chinese_clip_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPFeatureExtractor), -/* harmony export */ ConvNextFeatureExtractor: () => (/* reexport safe */ _convnext_image_processing_convnext_js__WEBPACK_IMPORTED_MODULE_4__.ConvNextFeatureExtractor), -/* harmony export */ ConvNextImageProcessor: () => (/* reexport safe */ _convnext_image_processing_convnext_js__WEBPACK_IMPORTED_MODULE_4__.ConvNextImageProcessor), -/* harmony export */ DINOv3ViTImageProcessor: () => (/* reexport safe */ _dinov3_vit_image_processing_dinov3_vit_js__WEBPACK_IMPORTED_MODULE_7__.DINOv3ViTImageProcessor), -/* harmony export */ DPTFeatureExtractor: () => (/* reexport safe */ _dpt_image_processing_dpt_js__WEBPACK_IMPORTED_MODULE_9__.DPTFeatureExtractor), -/* harmony export */ DPTImageProcessor: () => (/* reexport safe */ _dpt_image_processing_dpt_js__WEBPACK_IMPORTED_MODULE_9__.DPTImageProcessor), -/* harmony export */ DeiTFeatureExtractor: () => (/* reexport safe */ _deit_image_processing_deit_js__WEBPACK_IMPORTED_MODULE_5__.DeiTFeatureExtractor), -/* harmony export */ DeiTImageProcessor: () => (/* reexport safe */ _deit_image_processing_deit_js__WEBPACK_IMPORTED_MODULE_5__.DeiTImageProcessor), -/* harmony export */ DetrFeatureExtractor: () => (/* reexport safe */ _detr_image_processing_detr_js__WEBPACK_IMPORTED_MODULE_6__.DetrFeatureExtractor), -/* harmony export */ DetrImageProcessor: () => (/* reexport safe */ _detr_image_processing_detr_js__WEBPACK_IMPORTED_MODULE_6__.DetrImageProcessor), -/* harmony export */ DonutFeatureExtractor: () => (/* reexport safe */ _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_8__.DonutFeatureExtractor), -/* harmony export */ DonutImageProcessor: () => (/* reexport safe */ _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_8__.DonutImageProcessor), -/* harmony export */ EfficientNetImageProcessor: () => (/* reexport safe */ _efficientnet_image_processing_efficientnet_js__WEBPACK_IMPORTED_MODULE_10__.EfficientNetImageProcessor), -/* harmony export */ GLPNFeatureExtractor: () => (/* reexport safe */ _glpn_image_processing_glpn_js__WEBPACK_IMPORTED_MODULE_11__.GLPNFeatureExtractor), -/* harmony export */ GroundingDinoImageProcessor: () => (/* reexport safe */ _grounding_dino_image_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_12__.GroundingDinoImageProcessor), -/* harmony export */ Idefics3ImageProcessor: () => (/* reexport safe */ _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_13__.Idefics3ImageProcessor), -/* harmony export */ JinaCLIPImageProcessor: () => (/* reexport safe */ _jina_clip_image_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_15__.JinaCLIPImageProcessor), -/* harmony export */ LlavaOnevisionImageProcessor: () => (/* reexport safe */ _llava_onevision_image_processing_llava_onevision_js__WEBPACK_IMPORTED_MODULE_16__.LlavaOnevisionImageProcessor), -/* harmony export */ Mask2FormerImageProcessor: () => (/* reexport safe */ _mask2former_image_processing_mask2former_js__WEBPACK_IMPORTED_MODULE_17__.Mask2FormerImageProcessor), -/* harmony export */ MaskFormerFeatureExtractor: () => (/* reexport safe */ _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_18__.MaskFormerFeatureExtractor), -/* harmony export */ MaskFormerImageProcessor: () => (/* reexport safe */ _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_18__.MaskFormerImageProcessor), -/* harmony export */ MobileNetV1FeatureExtractor: () => (/* reexport safe */ _mobilenet_v1_image_processing_mobilenet_v1_js__WEBPACK_IMPORTED_MODULE_19__.MobileNetV1FeatureExtractor), -/* harmony export */ MobileNetV1ImageProcessor: () => (/* reexport safe */ _mobilenet_v1_image_processing_mobilenet_v1_js__WEBPACK_IMPORTED_MODULE_19__.MobileNetV1ImageProcessor), -/* harmony export */ MobileNetV2FeatureExtractor: () => (/* reexport safe */ _mobilenet_v2_image_processing_mobilenet_v2_js__WEBPACK_IMPORTED_MODULE_20__.MobileNetV2FeatureExtractor), -/* harmony export */ MobileNetV2ImageProcessor: () => (/* reexport safe */ _mobilenet_v2_image_processing_mobilenet_v2_js__WEBPACK_IMPORTED_MODULE_20__.MobileNetV2ImageProcessor), -/* harmony export */ MobileNetV3FeatureExtractor: () => (/* reexport safe */ _mobilenet_v3_image_processing_mobilenet_v3_js__WEBPACK_IMPORTED_MODULE_21__.MobileNetV3FeatureExtractor), -/* harmony export */ MobileNetV3ImageProcessor: () => (/* reexport safe */ _mobilenet_v3_image_processing_mobilenet_v3_js__WEBPACK_IMPORTED_MODULE_21__.MobileNetV3ImageProcessor), -/* harmony export */ MobileNetV4FeatureExtractor: () => (/* reexport safe */ _mobilenet_v4_image_processing_mobilenet_v4_js__WEBPACK_IMPORTED_MODULE_22__.MobileNetV4FeatureExtractor), -/* harmony export */ MobileNetV4ImageProcessor: () => (/* reexport safe */ _mobilenet_v4_image_processing_mobilenet_v4_js__WEBPACK_IMPORTED_MODULE_22__.MobileNetV4ImageProcessor), -/* harmony export */ MobileViTFeatureExtractor: () => (/* reexport safe */ _mobilevit_image_processing_mobilevit_js__WEBPACK_IMPORTED_MODULE_23__.MobileViTFeatureExtractor), -/* harmony export */ MobileViTImageProcessor: () => (/* reexport safe */ _mobilevit_image_processing_mobilevit_js__WEBPACK_IMPORTED_MODULE_23__.MobileViTImageProcessor), -/* harmony export */ NougatImageProcessor: () => (/* reexport safe */ _nougat_image_processing_nougat_js__WEBPACK_IMPORTED_MODULE_24__.NougatImageProcessor), -/* harmony export */ OwlViTFeatureExtractor: () => (/* reexport safe */ _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_26__.OwlViTFeatureExtractor), -/* harmony export */ OwlViTImageProcessor: () => (/* reexport safe */ _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_26__.OwlViTImageProcessor), -/* harmony export */ Owlv2ImageProcessor: () => (/* reexport safe */ _owlv2_image_processing_owlv2_js__WEBPACK_IMPORTED_MODULE_25__.Owlv2ImageProcessor), -/* harmony export */ Phi3VImageProcessor: () => (/* reexport safe */ _phi3_v_image_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_27__.Phi3VImageProcessor), -/* harmony export */ PvtImageProcessor: () => (/* reexport safe */ _pvt_image_processing_pvt_js__WEBPACK_IMPORTED_MODULE_28__.PvtImageProcessor), -/* harmony export */ Qwen2VLImageProcessor: () => (/* reexport safe */ _qwen2_vl_image_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_29__.Qwen2VLImageProcessor), -/* harmony export */ RTDetrImageProcessor: () => (/* reexport safe */ _rt_detr_image_processing_rt_detr_js__WEBPACK_IMPORTED_MODULE_30__.RTDetrImageProcessor), -/* harmony export */ SamImageProcessor: () => (/* reexport safe */ _sam_image_processing_sam_js__WEBPACK_IMPORTED_MODULE_31__.SamImageProcessor), -/* harmony export */ SegformerFeatureExtractor: () => (/* reexport safe */ _segformer_image_processing_segformer_js__WEBPACK_IMPORTED_MODULE_32__.SegformerFeatureExtractor), -/* harmony export */ SegformerImageProcessor: () => (/* reexport safe */ _segformer_image_processing_segformer_js__WEBPACK_IMPORTED_MODULE_32__.SegformerImageProcessor), -/* harmony export */ SiglipImageProcessor: () => (/* reexport safe */ _siglip_image_processing_siglip_js__WEBPACK_IMPORTED_MODULE_33__.SiglipImageProcessor), -/* harmony export */ SmolVLMImageProcessor: () => (/* reexport safe */ _smolvlm_image_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_34__.SmolVLMImageProcessor), -/* harmony export */ Swin2SRImageProcessor: () => (/* reexport safe */ _swin2sr_image_processing_swin2sr_js__WEBPACK_IMPORTED_MODULE_35__.Swin2SRImageProcessor), -/* harmony export */ VLMImageProcessor: () => (/* reexport safe */ _janus_image_processing_janus_js__WEBPACK_IMPORTED_MODULE_14__.VLMImageProcessor), -/* harmony export */ ViTFeatureExtractor: () => (/* reexport safe */ _vit_image_processing_vit_js__WEBPACK_IMPORTED_MODULE_36__.ViTFeatureExtractor), -/* harmony export */ ViTImageProcessor: () => (/* reexport safe */ _vit_image_processing_vit_js__WEBPACK_IMPORTED_MODULE_36__.ViTImageProcessor), -/* harmony export */ VitMatteImageProcessor: () => (/* reexport safe */ _vitmatte_image_processing_vitmatte_js__WEBPACK_IMPORTED_MODULE_37__.VitMatteImageProcessor), -/* harmony export */ VitPoseImageProcessor: () => (/* reexport safe */ _vitpose_image_processing_vitpose_js__WEBPACK_IMPORTED_MODULE_38__.VitPoseImageProcessor), -/* harmony export */ YolosFeatureExtractor: () => (/* reexport safe */ _yolos_image_processing_yolos_js__WEBPACK_IMPORTED_MODULE_39__.YolosFeatureExtractor), -/* harmony export */ YolosImageProcessor: () => (/* reexport safe */ _yolos_image_processing_yolos_js__WEBPACK_IMPORTED_MODULE_39__.YolosImageProcessor) -/* harmony export */ }); -/* harmony import */ var _beit_image_processing_beit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./beit/image_processing_beit.js */ "./src/models/beit/image_processing_beit.js"); -/* harmony import */ var _bit_image_processing_bit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bit/image_processing_bit.js */ "./src/models/bit/image_processing_bit.js"); -/* harmony import */ var _chinese_clip_image_processing_chinese_clip_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./chinese_clip/image_processing_chinese_clip.js */ "./src/models/chinese_clip/image_processing_chinese_clip.js"); -/* harmony import */ var _clip_image_processing_clip_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./clip/image_processing_clip.js */ "./src/models/clip/image_processing_clip.js"); -/* harmony import */ var _convnext_image_processing_convnext_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./convnext/image_processing_convnext.js */ "./src/models/convnext/image_processing_convnext.js"); -/* harmony import */ var _deit_image_processing_deit_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./deit/image_processing_deit.js */ "./src/models/deit/image_processing_deit.js"); -/* harmony import */ var _detr_image_processing_detr_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./detr/image_processing_detr.js */ "./src/models/detr/image_processing_detr.js"); -/* harmony import */ var _dinov3_vit_image_processing_dinov3_vit_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./dinov3_vit/image_processing_dinov3_vit.js */ "./src/models/dinov3_vit/image_processing_dinov3_vit.js"); -/* harmony import */ var _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./donut/image_processing_donut.js */ "./src/models/donut/image_processing_donut.js"); -/* harmony import */ var _dpt_image_processing_dpt_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./dpt/image_processing_dpt.js */ "./src/models/dpt/image_processing_dpt.js"); -/* harmony import */ var _efficientnet_image_processing_efficientnet_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./efficientnet/image_processing_efficientnet.js */ "./src/models/efficientnet/image_processing_efficientnet.js"); -/* harmony import */ var _glpn_image_processing_glpn_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./glpn/image_processing_glpn.js */ "./src/models/glpn/image_processing_glpn.js"); -/* harmony import */ var _grounding_dino_image_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./grounding_dino/image_processing_grounding_dino.js */ "./src/models/grounding_dino/image_processing_grounding_dino.js"); -/* harmony import */ var _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./idefics3/image_processing_idefics3.js */ "./src/models/idefics3/image_processing_idefics3.js"); -/* harmony import */ var _janus_image_processing_janus_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./janus/image_processing_janus.js */ "./src/models/janus/image_processing_janus.js"); -/* harmony import */ var _jina_clip_image_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./jina_clip/image_processing_jina_clip.js */ "./src/models/jina_clip/image_processing_jina_clip.js"); -/* harmony import */ var _llava_onevision_image_processing_llava_onevision_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./llava_onevision/image_processing_llava_onevision.js */ "./src/models/llava_onevision/image_processing_llava_onevision.js"); -/* harmony import */ var _mask2former_image_processing_mask2former_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./mask2former/image_processing_mask2former.js */ "./src/models/mask2former/image_processing_mask2former.js"); -/* harmony import */ var _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./maskformer/image_processing_maskformer.js */ "./src/models/maskformer/image_processing_maskformer.js"); -/* harmony import */ var _mobilenet_v1_image_processing_mobilenet_v1_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./mobilenet_v1/image_processing_mobilenet_v1.js */ "./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"); -/* harmony import */ var _mobilenet_v2_image_processing_mobilenet_v2_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./mobilenet_v2/image_processing_mobilenet_v2.js */ "./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"); -/* harmony import */ var _mobilenet_v3_image_processing_mobilenet_v3_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./mobilenet_v3/image_processing_mobilenet_v3.js */ "./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"); -/* harmony import */ var _mobilenet_v4_image_processing_mobilenet_v4_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./mobilenet_v4/image_processing_mobilenet_v4.js */ "./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"); -/* harmony import */ var _mobilevit_image_processing_mobilevit_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./mobilevit/image_processing_mobilevit.js */ "./src/models/mobilevit/image_processing_mobilevit.js"); -/* harmony import */ var _nougat_image_processing_nougat_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./nougat/image_processing_nougat.js */ "./src/models/nougat/image_processing_nougat.js"); -/* harmony import */ var _owlv2_image_processing_owlv2_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./owlv2/image_processing_owlv2.js */ "./src/models/owlv2/image_processing_owlv2.js"); -/* harmony import */ var _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./owlvit/image_processing_owlvit.js */ "./src/models/owlvit/image_processing_owlvit.js"); -/* harmony import */ var _phi3_v_image_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./phi3_v/image_processing_phi3_v.js */ "./src/models/phi3_v/image_processing_phi3_v.js"); -/* harmony import */ var _pvt_image_processing_pvt_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./pvt/image_processing_pvt.js */ "./src/models/pvt/image_processing_pvt.js"); -/* harmony import */ var _qwen2_vl_image_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./qwen2_vl/image_processing_qwen2_vl.js */ "./src/models/qwen2_vl/image_processing_qwen2_vl.js"); -/* harmony import */ var _rt_detr_image_processing_rt_detr_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./rt_detr/image_processing_rt_detr.js */ "./src/models/rt_detr/image_processing_rt_detr.js"); -/* harmony import */ var _sam_image_processing_sam_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./sam/image_processing_sam.js */ "./src/models/sam/image_processing_sam.js"); -/* harmony import */ var _segformer_image_processing_segformer_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./segformer/image_processing_segformer.js */ "./src/models/segformer/image_processing_segformer.js"); -/* harmony import */ var _siglip_image_processing_siglip_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./siglip/image_processing_siglip.js */ "./src/models/siglip/image_processing_siglip.js"); -/* harmony import */ var _smolvlm_image_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./smolvlm/image_processing_smolvlm.js */ "./src/models/smolvlm/image_processing_smolvlm.js"); -/* harmony import */ var _swin2sr_image_processing_swin2sr_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./swin2sr/image_processing_swin2sr.js */ "./src/models/swin2sr/image_processing_swin2sr.js"); -/* harmony import */ var _vit_image_processing_vit_js__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./vit/image_processing_vit.js */ "./src/models/vit/image_processing_vit.js"); -/* harmony import */ var _vitmatte_image_processing_vitmatte_js__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./vitmatte/image_processing_vitmatte.js */ "./src/models/vitmatte/image_processing_vitmatte.js"); -/* harmony import */ var _vitpose_image_processing_vitpose_js__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./vitpose/image_processing_vitpose.js */ "./src/models/vitpose/image_processing_vitpose.js"); -/* harmony import */ var _yolos_image_processing_yolos_js__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./yolos/image_processing_yolos.js */ "./src/models/yolos/image_processing_yolos.js"); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/***/ }), - -/***/ "./src/models/janus/image_processing_janus.js": -/*!****************************************************!*\ - !*** ./src/models/janus/image_processing_janus.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ VLMImageProcessor: () => (/* binding */ VLMImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class VLMImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - constructor(config) { - super({ - do_pad: true, - pad_size: { - width: config.image_size, - height: config.image_size, - }, - ...config, - }); - // @ts-expect-error TS2339 - this.constant_values = this.config.background_color.map(x => x * this.rescale_factor) + }, ye = Tc(), ys = () => { + if (ye && !ye.startsWith("blob:")) return ye.substring(0, ye.lastIndexOf("/") + 1); + }, on = (a, r) => { + try { + let s = r ?? ye; + return (s ? new URL(a, s) : new URL(a)).origin === gs; + } catch { + return false; } - - pad_image(pixelData, imgDims, padSize, options) { - return super.pad_image(pixelData, imgDims, padSize, { - constant_values: this.constant_values, - center: true, - ...options, - }); + }, vc = (a, r) => { + let s = r ?? ye; + try { + return (s ? new URL(a, s) : new URL(a)).href; + } catch { + return; } -} - - -/***/ }), - -/***/ "./src/models/janus/processing_janus.js": -/*!**********************************************!*\ - !*** ./src/models/janus/processing_janus.js ***! - \**********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ VLChatProcessor: () => (/* binding */ VLChatProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils/image.js */ "./src/utils/image.js"); - - - - - - - - -class VLChatProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static uses_processor_config = true; - - constructor(config, components, chat_template) { - super(config, components, chat_template); - - 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; + }, Ec = (a, r) => `${r ?? "./"}${a}`, ws = async (a) => { + let s = await (await fetch(a, { credentials: "same-origin" })).blob(); + return URL.createObjectURL(s); + }, Sc = async (a) => (await import( + /*webpackIgnore:true*/ + /*@vite-ignore*/ + a + )).default, hs = (ds(), Ht(cs)).default, Ts = async () => { + if (!ye) throw new Error("Failed to load proxy worker: cannot determine the script source URL."); + if (on(ye)) return [void 0, hs()]; + let a = await ws(ye); + return [a, hs(a)]; + }, bs = (ms(), Ht(ps)).default, vs = async (a, r, s, f) => { + let i = bs && !(a || r); + if (i) if (ye) i = on(ye) || f && !s; + else if (f && !s) i = true; + else throw new Error("cannot determine the script source URL."); + if (i) return [void 0, bs]; + { + let p = "ort-wasm-simd-threaded.asyncify.mjs", l = a ?? vc(p, r), b = s && l && !on(l, r), g = b ? await ws(l) : l ?? Ec(p, r); + return [b ? g : void 0, await Sc(g)]; } - - /** - * @typedef {Object} MultimodalMessageProperties Additional properties for multimodal messages. - * @property {(RawImage | string | URL)[]} [images] The images in the message. - * @typedef {(import('../../tokenizers.js').Message & MultimodalMessageProperties)[]} MultimodalConversation The conversation possibly containing multimodal inputs. - */ - - /** - * @typedef {Object} VLCChatProcessorResult The processed input. - * @property {Tensor} input_ids The input IDs. - * @property {Tensor} attention_mask The attention mask. - * @property {Tensor} images_seq_mask The image sequence mask. - * @property {Tensor} images_emb_mask The image embedding mask. - */ - - /** - * @param {MultimodalConversation} conversation The chat messages to process. - * @param {Object} options Additional options for processing. - * @param {RawImage|RawImage[]} [options.images] The images to process, if not set in the conversation. - * @param {string} [options.chat_template="default"] The chat template to use. - * @returns {Promise} The processed input. - */ - async _call(conversation, { - images = null, - chat_template = "default", - }={}) { - if (!images) { - images = await Promise.all( - conversation - .filter((msg) => msg.images) - .flatMap((msg) => msg.images) - .map((img) => _utils_image_js__WEBPACK_IMPORTED_MODULE_5__.RawImage.read(img)) - ); - } else if (!Array.isArray(images)) { - images = [images]; - } - - const tokenizer = this.tokenizer; - const result = tokenizer.apply_chat_template(conversation, { - tokenize: false, - add_generation_prompt: true, - chat_template, - }); - - const encode = (text) => tokenizer.encode(text, { add_special_tokens: false }); - const parts = (/** @type {string} */(result)) - .split(this.image_tag); - const num_images = parts.length - 1; - if (images.length !== num_images) { - throw new Error(`Number of images provided (${images.length}) does not match number of "${this.image_tag}" image tags (${num_images})`); - } - - const [ - image_placeholder_tag_id, - image_start_tag_id, - image_end_tag_id, - ] = tokenizer.model.convert_tokens_to_ids([ - this.image_tag, - this.image_start_tag, - this.image_end_tag, - ]); - - let input_ids = encode(parts[0]); - let images_seq_mask = new Array(input_ids.length).fill(false); - for (let i = 1; i < parts.length; ++i) { - const placeholder_image_tokens = new Array(this.num_image_tokens).fill(image_placeholder_tag_id); - const tokens = encode(parts[i]); - input_ids = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_3__.mergeArrays)( - input_ids, - [image_start_tag_id], placeholder_image_tokens, [image_end_tag_id], - tokens, - ); - const image_mask = new Array(this.num_image_tokens).fill(true); - images_seq_mask = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_3__.mergeArrays)( - images_seq_mask, - [false], image_mask, [false], - new Array(tokens.length).fill(false), - ); - } - - const dims = [1, input_ids.length]; - const final = { - input_ids: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64', input_ids, dims), - attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64', new Array(input_ids.length).fill(1), dims), - images_seq_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('bool', images_seq_mask, dims), - images_emb_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor( - 'bool', - new Array(num_images * this.num_image_tokens).fill(true), - [1, num_images, this.num_image_tokens], - ), - } - - if (images && images.length > 0) { - const image_inputs = await this.image_processor(images); - // Set the batch_size dimension to 1 - image_inputs.pixel_values.unsqueeze_(0); - return { ...final, ...image_inputs }; - } - - return final; + }; +}); +var sn; +var un; +var sr; +var Es; +var xc; +var Ac; +var Ic; +var Kt; +var j; +var je = G(() => { + "use strict"; + Zt(); + un = false, sr = false, Es = false, xc = () => { + if (typeof SharedArrayBuffer > "u") return false; + 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 false; } -} - - -/***/ }), - -/***/ "./src/models/jina_clip/image_processing_jina_clip.js": -/*!************************************************************!*\ - !*** ./src/models/jina_clip/image_processing_jina_clip.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ JinaCLIPImageProcessor: () => (/* binding */ JinaCLIPImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class JinaCLIPImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - constructor(config) { - // JinaCLIPImageProcessor uses a custom preprocessor_config.json, so we configure it here - const { resize_mode, fill_color, interpolation, size, ...other } = config; - - const new_size = resize_mode === 'squash' - ? { width: size, height: size } - : resize_mode === 'shortest' - ? { shortest_edge: size } - : { longest_edge: size }; - - const resample = interpolation === 'bicubic' ? 3 : 2; - super({ - ...other, - size: new_size, - resample, - do_center_crop: true, - crop_size: size, - do_normalize: true, - }); + }, Ac = () => { + 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 false; } -} - - -/***/ }), - -/***/ "./src/models/jina_clip/processing_jina_clip.js": -/*!******************************************************!*\ - !*** ./src/models/jina_clip/processing_jina_clip.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ JinaCLIPProcessor: () => (/* binding */ JinaCLIPProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); - - - - - -class JinaCLIPProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - - async _call(text=null, images=null, kwargs = {}) { - - if (!text && !images){ - throw new Error('Either text or images must be provided'); - } - - const text_inputs = text ? this.tokenizer(text, kwargs) : {}; - const image_inputs = images ? await this.image_processor(images, kwargs) : {}; - - return { - ...text_inputs, - ...image_inputs, - } + }, Ic = () => { + try { + return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 19, 1, 17, 0, 65, 1, 253, 15, 65, 2, 253, 15, 65, 3, 253, 15, 253, 147, 2, 11])); + } catch { + return false; + } + }, Kt = async (a) => { + if (un) return Promise.resolve(); + if (sr) throw new Error("multiple calls to 'initializeWebAssembly()' detected."); + if (Es) throw new Error("previous call to 'initializeWebAssembly()' failed."); + sr = true; + let r = a.initTimeout, s = a.numThreads; + if (a.simd !== false) { + if (a.simd === "relaxed") { + if (!Ic()) throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment."); + } else if (!Ac()) throw new Error("WebAssembly SIMD is not supported in the current environment."); + } + let f = xc(); + s > 1 && !f && (typeof self < "u" && !self.crossOriginIsolated && console.warn("env.wasm.numThreads is set to " + s + ", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."), console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."), a.numThreads = s = 1); + let i = a.wasmPaths, p = typeof i == "string" ? i : void 0, l = i?.mjs, b = l?.href ?? l, g = i?.wasm, w = g?.href ?? g, S = a.wasmBinary, [v, T] = await vs(b, p, s > 1, !!S || !!w), A = false, C = []; + if (r > 0 && C.push(new Promise((_) => { + setTimeout(() => { + A = true, _(); + }, r); + })), C.push(new Promise((_, k) => { + let U = { numThreads: s }; + if (S) U.wasmBinary = S, U.locateFile = (M) => M; + else if (w || p) U.locateFile = (M) => w ?? p + M; + else if (b && b.indexOf("blob:") !== 0) U.locateFile = (M) => new URL(M, b).href; + else if (v) { + let M = ys(); + M && (U.locateFile = (Y) => M + Y); + } + T(U).then((M) => { + sr = false, un = true, sn = M, _(), v && URL.revokeObjectURL(v); + }, (M) => { + sr = false, Es = true, k(M); + }); + })), await Promise.race(C), A) throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`); + }, j = () => { + if (un && sn) return sn; + throw new Error("WebAssembly is not initialized yet."); + }; +}); +var be; +var Bt; +var V; +var ir = G(() => { + "use strict"; + je(); + be = (a, r) => { + let s = j(), f = s.lengthBytesUTF8(a) + 1, i = s._malloc(f); + return s.stringToUTF8(a, i, f), r.push(i), i; + }, Bt = (a, r, s, f) => { + if (typeof a == "object" && a !== null) { + if (s.has(a)) throw new Error("Circular reference in options"); + s.add(a); + } + Object.entries(a).forEach(([i, p]) => { + let l = r ? r + i : i; + if (typeof p == "object") Bt(p, l + ".", s, f); + else if (typeof p == "string" || typeof p == "number") f(l, p.toString()); + else if (typeof p == "boolean") f(l, p ? "1" : "0"); + else throw new Error(`Can't handle extra config type: ${typeof p}`); + }); + }, V = (a) => { + let r = j(), s = r.stackSave(); + try { + let f = r.PTR_SIZE, i = r.stackAlloc(2 * f); + r._OrtGetLastError(i, i + f); + let p = Number(r.getValue(i, f === 4 ? "i32" : "i64")), l = r.getValue(i + f, "*"), b = l ? r.UTF8ToString(l) : ""; + throw new Error(`${a} ERROR_CODE: ${p}, ERROR_MESSAGE: ${b}`); + } finally { + r.stackRestore(s); } -} - - -/***/ }), - -/***/ "./src/models/llava/processing_llava.js": -/*!**********************************************!*\ - !*** ./src/models/llava/processing_llava.js ***! - \**********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ LlavaProcessor: () => (/* binding */ LlavaProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); - - - - - -class LlavaProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - static uses_processor_config = true; - - /** - * @typedef {import('../../utils/image.js').RawImage} RawImage - */ - - // `images` is required, `text` is optional - async _call(/** @type {RawImage|RawImage[]} */ images, text = null, kwargs = {}) { - - const image_inputs = await this.image_processor(images, kwargs); - - if (text) { - const [height, width] = image_inputs.pixel_values.dims.slice(-2); - - const {image_token, patch_size, num_additional_image_tokens} = this.config; - const num_image_tokens = Math.floor( - height / patch_size - ) * Math.floor(width / patch_size) + num_additional_image_tokens; - - text = structuredClone(text); // Avoid modifying the original text input - if (!Array.isArray(text)) { - text = [text]; + }; +}); +var Ss; +var xs = G(() => { + "use strict"; + je(); + ir(); + Ss = (a) => { + let r = j(), s = 0, f = [], i = a || {}; + try { + if (a?.logSeverityLevel === void 0) i.logSeverityLevel = 2; + else if (typeof a.logSeverityLevel != "number" || !Number.isInteger(a.logSeverityLevel) || a.logSeverityLevel < 0 || a.logSeverityLevel > 4) throw new Error(`log severity level is not valid: ${a.logSeverityLevel}`); + if (a?.logVerbosityLevel === void 0) i.logVerbosityLevel = 0; + else if (typeof a.logVerbosityLevel != "number" || !Number.isInteger(a.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`); + a?.terminate === void 0 && (i.terminate = false); + let p = 0; + return a?.tag !== void 0 && (p = be(a.tag, f)), s = r._OrtCreateRunOptions(i.logSeverityLevel, i.logVerbosityLevel, !!i.terminate, p), s === 0 && V("Can't create run options."), a?.extra !== void 0 && Bt(a.extra, "", /* @__PURE__ */ new WeakSet(), (l, b) => { + let g = be(l, f), w = be(b, f); + r._OrtAddRunConfigEntry(s, g, w) !== 0 && V(`Can't set a run config entry: ${l} - ${b}.`); + }), [s, f]; + } catch (p) { + throw s !== 0 && r._OrtReleaseRunOptions(s), f.forEach((l) => r._free(l)), p; + } + }; +}); +var Lc; +var Bc; +var Oc; +var Ot; +var We; +var Mc; +var As; +var Is = G(() => { + "use strict"; + je(); + ir(); + Lc = (a) => { + switch (a) { + case "disabled": + return 0; + case "basic": + return 1; + case "extended": + return 2; + case "layout": + return 3; + case "all": + return 99; + default: + throw new Error(`unsupported graph optimization level: ${a}`); + } + }, Bc = (a) => { + switch (a) { + case "sequential": + return 0; + case "parallel": + return 1; + default: + throw new Error(`unsupported execution mode: ${a}`); + } + }, Oc = (a) => { + a.extra || (a.extra = {}), a.extra.session || (a.extra.session = {}); + let r = a.extra.session; + r.use_ort_model_bytes_directly || (r.use_ort_model_bytes_directly = "1"), a.executionProviders && a.executionProviders.some((s) => (typeof s == "string" ? s : s.name) === "webgpu") && (a.enableMemPattern = false); + }, Ot = (a, r, s, f) => { + let i = be(r, f), p = be(s, f); + j()._OrtAddSessionConfigEntry(a, i, p) !== 0 && V(`Can't set a session config entry: ${r} - ${s}.`); + }, We = (a, r, s, f) => { + let i = be(r, f), p = be(s, f); + a.push([i, p]); + }, Mc = async (a, r, s) => { + let f = r.executionProviders; + for (let i of f) { + let p = typeof i == "string" ? i : i.name, l = []; + switch (p) { + case "webnn": + if (p = "WEBNN", Ot(a, "session.disable_quant_qdq", "1", s), Ot(a, "session.disable_qdq_constant_folding", "1", s), typeof i != "string") { + let T = i?.deviceType; + T && Ot(a, "deviceType", T, s); + } + break; + case "webgpu": + { + p = "WebGPU"; + let v; + if (typeof i != "string") { + let A = i; + if (A.device) if (typeof GPUDevice < "u" && A.device instanceof GPUDevice) v = A.device; + else throw new Error("Invalid GPU device set in WebGPU EP options."); + let { enableGraphCapture: C } = r; + if (typeof C == "boolean" && C && We(l, "enableGraphCapture", "1", s), typeof A.preferredLayout == "string" && We(l, "preferredLayout", A.preferredLayout, s), A.forceCpuNodeNames) { + let _ = Array.isArray(A.forceCpuNodeNames) ? A.forceCpuNodeNames : [A.forceCpuNodeNames]; + We(l, "forceCpuNodeNames", _.join(` +`), s); + } + A.validationMode && We(l, "validationMode", A.validationMode, s), typeof A.enableMatmulFp32Accumulation == "boolean" && We(l, "enableMatmulFp32Accumulation", A.enableMatmulFp32Accumulation ? "1" : "0", s); + for (let _ of ["storageBufferCacheMode", "uniformBufferCacheMode", "queryResolveBufferCacheMode", "defaultBufferCacheMode"]) { + let k = A[_]; + if (k) { + if (k !== "disabled" && k !== "lazyRelease" && k !== "simple" && k !== "bucket") throw new Error(`${_} must be one of 'disabled', 'lazyRelease', 'simple' or 'bucket': ${k}`); + We(l, _, k, s); + } + } } - for (let i = 0; i < text.length; ++i) { - text[i] = text[i].replace(image_token, image_token.repeat(num_image_tokens)); + let T = j().webgpuRegisterDevice(v); + if (T) { + let [A, C, _] = T; + We(l, "deviceId", A.toString(), s), We(l, "webgpuInstance", C.toString(), s), We(l, "webgpuDevice", _.toString(), s); } - } - - const text_inputs = text ? this.tokenizer(text, kwargs) : {}; - - return { - ...image_inputs, - ...text_inputs, - } + } + break; + case "wasm": + case "cpu": + continue; + default: + throw new Error(`not supported execution provider: ${p}`); + } + let b = be(p, s), g = l.length, w = 0, S = 0; + if (g > 0) { + w = j()._malloc(g * j().PTR_SIZE), s.push(w), S = j()._malloc(g * j().PTR_SIZE), s.push(S); + for (let v = 0; v < g; v++) j().setValue(w + v * j().PTR_SIZE, l[v][0], "*"), j().setValue(S + v * j().PTR_SIZE, l[v][1], "*"); + } + await j()._OrtAppendExecutionProvider(a, b, w, S, g) !== 0 && V(`Can't append execution provider: ${p}.`); } -} - - -/***/ }), - -/***/ "./src/models/llava_onevision/image_processing_llava_onevision.js": -/*!************************************************************************!*\ - !*** ./src/models/llava_onevision/image_processing_llava_onevision.js ***! - \************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ LlavaOnevisionImageProcessor: () => (/* binding */ LlavaOnevisionImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class LlavaOnevisionImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor {} - - -/***/ }), - -/***/ "./src/models/mask2former/image_processing_mask2former.js": -/*!****************************************************************!*\ - !*** ./src/models/mask2former/image_processing_mask2former.js ***! - \****************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Mask2FormerImageProcessor: () => (/* binding */ Mask2FormerImageProcessor) -/* harmony export */ }); -/* harmony import */ var _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../maskformer/image_processing_maskformer.js */ "./src/models/maskformer/image_processing_maskformer.js"); - - - -// NOTE: extends MaskFormerImageProcessor -class Mask2FormerImageProcessor extends _maskformer_image_processing_maskformer_js__WEBPACK_IMPORTED_MODULE_0__.MaskFormerImageProcessor { } - - -/***/ }), - -/***/ "./src/models/maskformer/image_processing_maskformer.js": -/*!**************************************************************!*\ - !*** ./src/models/maskformer/image_processing_maskformer.js ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MaskFormerFeatureExtractor: () => (/* binding */ MaskFormerFeatureExtractor), -/* harmony export */ MaskFormerImageProcessor: () => (/* binding */ MaskFormerImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class MaskFormerImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - - /** @type {typeof post_process_panoptic_segmentation} */ - post_process_panoptic_segmentation(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_panoptic_segmentation)(...args); + }, As = async (a) => { + let r = j(), s = 0, f = [], i = a || {}; + Oc(i); + try { + let p = Lc(i.graphOptimizationLevel ?? "all"), l = Bc(i.executionMode ?? "sequential"), b = typeof i.logId == "string" ? be(i.logId, f) : 0, g = i.logSeverityLevel ?? 2; + if (!Number.isInteger(g) || g < 0 || g > 4) throw new Error(`log severity level is not valid: ${g}`); + let w = i.logVerbosityLevel ?? 0; + if (!Number.isInteger(w) || w < 0 || w > 4) throw new Error(`log verbosity level is not valid: ${w}`); + let S = typeof i.optimizedModelFilePath == "string" ? be(i.optimizedModelFilePath, f) : 0; + if (s = r._OrtCreateSessionOptions(p, !!i.enableCpuMemArena, !!i.enableMemPattern, l, !!i.enableProfiling, 0, b, g, w, S), s === 0 && V("Can't create session options."), i.executionProviders && await Mc(s, i, f), i.enableGraphCapture !== void 0) { + if (typeof i.enableGraphCapture != "boolean") throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`); + Ot(s, "enableGraphCapture", i.enableGraphCapture.toString(), f); + } + if (i.freeDimensionOverrides) for (let [v, T] of Object.entries(i.freeDimensionOverrides)) { + if (typeof v != "string") throw new Error(`free dimension override name must be a string: ${v}`); + if (typeof T != "number" || !Number.isInteger(T) || T < 0) throw new Error(`free dimension override value must be a non-negative integer: ${T}`); + let A = be(v, f); + r._OrtAddFreeDimensionOverride(s, A, T) !== 0 && V(`Can't set a free dimension override: ${v} - ${T}.`); + } + return i.extra !== void 0 && Bt(i.extra, "", /* @__PURE__ */ new WeakSet(), (v, T) => { + Ot(s, v, T, f); + }), [s, f]; + } catch (p) { + throw s !== 0 && r._OrtReleaseSessionOptions(s) !== 0 && V("Can't release session options."), f.forEach((l) => r._free(l)), p; } - /** @type {typeof post_process_instance_segmentation} */ - post_process_instance_segmentation(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_instance_segmentation)(...args); + }; +}); +var He; +var ur; +var bt; +var it; +var Mt; +var fr; +var cr; +var fn; +var ut = G(() => { + "use strict"; + He = (a) => { + switch (a) { + 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: ${a}`); + } + }, ur = (a) => { + switch (a) { + 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: ${a}`); + } + }, bt = (a, r) => { + let s = [-1, 4, 1, 1, 2, 2, 4, 8, -1, 1, 2, 8, 4, 8, -1, -1, -1, -1, -1, -1, -1, 0.5, 0.5][a], f = typeof r == "number" ? r : r.reduce((i, p) => i * p, 1); + return s > 0 ? Math.ceil(f * s) : void 0; + }, it = (a) => { + switch (a) { + case "float16": + return typeof Float16Array < "u" ? 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: ${a}`); } -} -class MaskFormerFeatureExtractor extends MaskFormerImageProcessor { } - - -/***/ }), - -/***/ "./src/models/mgp_str/processing_mgp_str.js": -/*!**************************************************!*\ - !*** ./src/models/mgp_str/processing_mgp_str.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MgpstrProcessor: () => (/* binding */ MgpstrProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/maths.js */ "./src/utils/maths.js"); - - - - - -const DECODE_TYPE_MAPPING = { - 'char': ['char_decode', 1], - 'bpe': ['bpe_decode', 2], - 'wp': ['wp_decode', 102], -} -class MgpstrProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - - /** - * @returns {import('../../tokenizers.js').MgpstrTokenizer} The character tokenizer. - */ - get char_tokenizer() { - return this.components.char_tokenizer; + }, Mt = (a) => { + switch (a) { + 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: ${a}`); } - - /** - * @returns {import('../../tokenizers.js').GPT2Tokenizer} The BPE tokenizer. - */ - get bpe_tokenizer() { - return this.components.bpe_tokenizer; + }, fr = (a) => a === "float32" || a === "float16" || a === "int32" || a === "int64" || a === "uint32" || a === "uint8" || a === "bool" || a === "uint4" || a === "int4", cr = (a) => a === "float32" || a === "float16" || a === "int32" || a === "int64" || a === "uint32" || a === "uint64" || a === "int8" || a === "uint8" || a === "bool" || a === "uint4" || a === "int4", fn = (a) => { + switch (a) { + 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: ${a}`); } - - /** - * @returns {import('../../tokenizers.js').BertTokenizer} The WordPiece tokenizer. - */ - get wp_tokenizer() { - return this.components.wp_tokenizer; + }; +}); +var Ct; +var cn = G(() => { + "use strict"; + Xt(); + Ct = async (a) => { + if (typeof a == "string") if (false) try { + let { readFile: r } = Xr("node:fs/promises"); + return new Uint8Array(await r(a)); + } catch (r) { + if (r.code === "ERR_FS_FILE_TOO_LARGE") { + let { createReadStream: s } = Xr("node:fs"), f = s(a), i = []; + for await (let p of f) i.push(p); + return new Uint8Array(Buffer.concat(i)); + } + throw r; } - - /** - * Helper function to decode the model prediction logits. - * @param {import('../../utils/tensor.js').Tensor} pred_logits Model prediction logits. - * @param {string} format Type of model prediction. Must be one of ['char', 'bpe', 'wp']. - * @returns {[string[], number[]]} The decoded sentences and their confidence scores. - */ - _decode_helper(pred_logits, format) { - if (!DECODE_TYPE_MAPPING.hasOwnProperty(format)) { - throw new Error(`Format ${format} is not supported.`); - } - - const [decoder_name, eos_token] = DECODE_TYPE_MAPPING[format]; - const decoder = this[decoder_name].bind(this); - - const [batch_size, batch_max_length] = pred_logits.dims; - const conf_scores = []; - const all_ids = []; - - /** @type {number[][][]} */ - const pred_logits_list = pred_logits.tolist(); - for (let i = 0; i < batch_size; ++i) { - const logits = pred_logits_list[i]; - const ids = []; - const scores = []; - - // Start and index=1 to skip the first token - for (let j = 1; j < batch_max_length; ++j) { - // NOTE: == to match bigint and number - const [max_prob, max_prob_index] = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.softmax)(logits[j])); - scores.push(max_prob); - if (max_prob_index == eos_token) { - break; - } - ids.push(max_prob_index); - } - - const confidence_score = scores.length > 0 - ? scores.reduce((a, b) => a * b, 1) - : 0; - - all_ids.push(ids); - conf_scores.push(confidence_score); - } - - const decoded = decoder(all_ids); - return [decoded, conf_scores]; + else { + let r = await fetch(a); + if (!r.ok) throw new Error(`failed to load external data file: ${a}`); + let s = r.headers.get("Content-Length"), f = s ? parseInt(s, 10) : 0; + if (f < 1073741824) return new Uint8Array(await r.arrayBuffer()); + { + if (!r.body) throw new Error(`failed to load external data file: ${a}, no response body.`); + let i = r.body.getReader(), p; + try { + p = new ArrayBuffer(f); + } catch (b) { + if (b instanceof RangeError) { + let g = Math.ceil(f / 65536); + p = new WebAssembly.Memory({ initial: g, maximum: g }).buffer; + } else throw b; + } + let l = 0; + for (; ; ) { + let { done: b, value: g } = await i.read(); + if (b) break; + let w = g.byteLength; + new Uint8Array(p, l, w).set(g), l += w; + } + return new Uint8Array(p, 0, f); + } } - - /** - * Convert a list of lists of char token ids into a list of strings by calling char tokenizer. - * @param {number[][]} sequences List of tokenized input ids. - * @returns {string[]} The list of char decoded sentences. - */ - char_decode(sequences) { - return this.char_tokenizer.batch_decode(sequences).map(str => str.replaceAll(' ', '')); + else return a instanceof Blob ? new Uint8Array(await a.arrayBuffer()) : a instanceof Uint8Array ? a : new Uint8Array(a); + }; +}); +var Ls; +var Bs = G(() => { + "use strict"; + ut(); + Ls = (a, r) => new (it(r))(a); +}); +var Cc; +var Dc; +var Os; +var Ms; +var Cs; +var Pc; +var le; +var dn = G(() => { + "use strict"; + ut(); + Cc = ["V", "I", "W", "E", "F"], Dc = (a, r) => { + console.log(`[${Cc[a]},${(/* @__PURE__ */ new Date()).toISOString()}]${r}`); + }, Cs = (a, r) => { + Os = a, Ms = r; + }, Pc = (a, r) => { + let s = Mt(a), f = Mt(Os); + s >= f && Dc(s, typeof r == "function" ? r() : r); + }, le = (...a) => { + Ms && Pc(...a); + }; +}); +var Ps; +var Uc; +var Us; +var _c; +var Ds; +var Rc; +var _s; +var dr; +var lr; +var ln; +var Rs; +var Ns = G(() => { + "use strict"; + ut(); + dn(); + Ps = /* @__PURE__ */ new Map([["float32", 32], ["float16", 16], ["int32", 32], ["uint32", 32], ["int64", 64], ["uint64", 64], ["int8", 8], ["uint8", 8], ["int4", 4], ["uint4", 4]]), Uc = (a, r) => { + if (r === "int32") return a; + let s = Ps.get(r); + if (!s) throw new Error(`WebNN backend does not support data type: ${r}`); + let f = s / 8; + if (a.byteLength % f !== 0) throw new Error(`Invalid Uint8Array length - must be a multiple of ${f}.`); + let i = a.byteLength / f, p = new (it(r))(a.buffer, a.byteOffset, i); + switch (r) { + case "int64": + case "uint64": { + let l = new Int32Array(i); + for (let b = 0; b < i; b++) { + let g = p[b]; + if (g > 2147483647n || g < -2147483648n) throw new Error("Can not convert int64 data to int32 - value out of range."); + l[b] = Number(g); + } + return new Uint8Array(l.buffer); + } + case "int8": + case "uint8": + case "uint32": { + if (r === "uint32" && p.some((b) => b > 2147483647)) throw new Error("Can not convert uint32 data to int32 - value out of range."); + let l = Int32Array.from(p, Number); + return new Uint8Array(l.buffer); + } + default: + throw new Error(`Unsupported data conversion from ${r} to 'int32'`); + } + }, Us = (a, r) => { + if (r === "int32") return a; + if (a.byteLength % 4 !== 0) throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32)."); + let s = a.byteLength / 4, f = new Int32Array(a.buffer, a.byteOffset, s); + switch (r) { + case "int64": { + let i = BigInt64Array.from(f, BigInt); + return new Uint8Array(i.buffer); + } + case "uint64": { + if (f.some((p) => p < 0)) throw new Error("Can not convert int32 data to uin64 - negative value found."); + let i = BigUint64Array.from(f, BigInt); + return new Uint8Array(i.buffer); + } + case "int8": { + if (f.some((p) => p < -128 || p > 127)) throw new Error("Can not convert int32 data to int8 - value out of range."); + let i = Int8Array.from(f, Number); + return new Uint8Array(i.buffer); + } + case "uint8": { + if (f.some((i) => i < 0 || i > 255)) throw new Error("Can not convert int32 data to uint8 - value out of range."); + return Uint8Array.from(f, Number); + } + case "uint32": { + if (f.some((p) => p < 0)) throw new Error("Can not convert int32 data to uint32 - negative value found."); + let i = Uint32Array.from(f, Number); + return new Uint8Array(i.buffer); + } + default: + throw new Error(`Unsupported data conversion from 'int32' to ${r}`); } - - /** - * Convert a list of lists of BPE token ids into a list of strings by calling BPE tokenizer. - * @param {number[][]} sequences List of tokenized input ids. - * @returns {string[]} The list of BPE decoded sentences. - */ - bpe_decode(sequences) { - return this.bpe_tokenizer.batch_decode(sequences) + }, _c = 1, Ds = () => _c++, Rc = /* @__PURE__ */ new Map([["int8", "int32"], ["uint8", "int32"], ["uint32", "int32"], ["int64", "int32"]]), _s = (a, r) => { + let s = Ps.get(a); + if (!s) throw new Error(`WebNN backend does not support data type: ${a}`); + return r.length > 0 ? Math.ceil(r.reduce((f, i) => f * i) * s / 8) : 0; + }, dr = class { + constructor(r) { + this.isDataConverted = false; + let { sessionId: s, context: f, tensor: i, dataType: p, shape: l, fallbackDataType: b } = r; + this.sessionId = s, this.mlContext = f, this.mlTensor = i, this.dataType = p, this.tensorShape = l, this.fallbackDataType = b; } - - /** - * Convert a list of lists of word piece token ids into a list of strings by calling word piece tokenizer. - * @param {number[][]} sequences List of tokenized input ids. - * @returns {string[]} The list of wp decoded sentences. - */ - wp_decode(sequences) { - return this.wp_tokenizer.batch_decode(sequences).map(str => str.replaceAll(' ', '')); + get tensor() { + return this.mlTensor; } - - /** - * Convert a list of lists of token ids into a list of strings by calling decode. - * @param {import('../../utils/tensor.js').Tensor[]} sequences List of tokenized input ids. - * @returns {{generated_text: string[], scores: number[], char_preds: string[], bpe_preds: string[], wp_preds: string[]}} - * Dictionary of all the outputs of the decoded results. - * - generated_text: The final results after fusion of char, bpe, and wp. - * - scores: The final scores after fusion of char, bpe, and wp. - * - char_preds: The list of character decoded sentences. - * - bpe_preds: The list of BPE decoded sentences. - * - wp_preds: The list of wp decoded sentences. - */ - // @ts-expect-error The type of this method is not compatible with the one - // in the base class. It might be a good idea to fix this. - batch_decode([char_logits, bpe_logits, wp_logits]) { - const [char_preds, char_scores] = this._decode_helper(char_logits, 'char'); - const [bpe_preds, bpe_scores] = this._decode_helper(bpe_logits, 'bpe'); - const [wp_preds, wp_scores] = this._decode_helper(wp_logits, 'wp'); - - const generated_text = []; - const scores = []; - for (let i = 0; i < char_preds.length; ++i) { - const [max_score, max_score_index] = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)([char_scores[i], bpe_scores[i], wp_scores[i]]); - generated_text.push([char_preds[i], bpe_preds[i], wp_preds[i]][max_score_index]); - scores.push(max_score); - } - - return { - generated_text, - scores, - char_preds, - bpe_preds, - wp_preds, - } + get type() { + return this.dataType; } - /** @type {typeof Processor.from_pretrained} */ - static async from_pretrained(...args) { - const base = await super.from_pretrained(...args); - - // Load Transformers.js-compatible versions of the BPE and WordPiece tokenizers - const bpe_tokenizer = await _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer.from_pretrained("Xenova/gpt2") // openai-community/gpt2 - const wp_tokenizer = await _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased") // google-bert/bert-base-uncased - - // Update components - base.components = { - image_processor: base.image_processor, - char_tokenizer: base.tokenizer, - bpe_tokenizer: bpe_tokenizer, - wp_tokenizer: wp_tokenizer, - } - return base; + get fallbackType() { + return this.fallbackDataType; } - - async _call(images, text = null) { - const result = await this.image_processor(images); - - if (text) { - result.labels = this.tokenizer(text).input_ids - } - - return result; + get shape() { + return this.tensorShape; } -} - - -/***/ }), - -/***/ "./src/models/mobilenet_v1/image_processing_mobilenet_v1.js": -/*!******************************************************************!*\ - !*** ./src/models/mobilenet_v1/image_processing_mobilenet_v1.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MobileNetV1FeatureExtractor: () => (/* binding */ MobileNetV1FeatureExtractor), -/* harmony export */ MobileNetV1ImageProcessor: () => (/* binding */ MobileNetV1ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class MobileNetV1ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class MobileNetV1FeatureExtractor extends MobileNetV1ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/mobilenet_v2/image_processing_mobilenet_v2.js": -/*!******************************************************************!*\ - !*** ./src/models/mobilenet_v2/image_processing_mobilenet_v2.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MobileNetV2FeatureExtractor: () => (/* binding */ MobileNetV2FeatureExtractor), -/* harmony export */ MobileNetV2ImageProcessor: () => (/* binding */ MobileNetV2ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class MobileNetV2ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class MobileNetV2FeatureExtractor extends MobileNetV2ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/mobilenet_v3/image_processing_mobilenet_v3.js": -/*!******************************************************************!*\ - !*** ./src/models/mobilenet_v3/image_processing_mobilenet_v3.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MobileNetV3FeatureExtractor: () => (/* binding */ MobileNetV3FeatureExtractor), -/* harmony export */ MobileNetV3ImageProcessor: () => (/* binding */ MobileNetV3ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class MobileNetV3ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class MobileNetV3FeatureExtractor extends MobileNetV3ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/mobilenet_v4/image_processing_mobilenet_v4.js": -/*!******************************************************************!*\ - !*** ./src/models/mobilenet_v4/image_processing_mobilenet_v4.js ***! - \******************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MobileNetV4FeatureExtractor: () => (/* binding */ MobileNetV4FeatureExtractor), -/* harmony export */ MobileNetV4ImageProcessor: () => (/* binding */ MobileNetV4ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class MobileNetV4ImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class MobileNetV4FeatureExtractor extends MobileNetV4ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/mobilevit/image_processing_mobilevit.js": -/*!************************************************************!*\ - !*** ./src/models/mobilevit/image_processing_mobilevit.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MobileViTFeatureExtractor: () => (/* binding */ MobileViTFeatureExtractor), -/* harmony export */ MobileViTImageProcessor: () => (/* binding */ MobileViTImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class MobileViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class MobileViTFeatureExtractor extends MobileViTImageProcessor { } - - -/***/ }), - -/***/ "./src/models/moonshine/feature_extraction_moonshine.js": -/*!**************************************************************!*\ - !*** ./src/models/moonshine/feature_extraction_moonshine.js ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MoonshineFeatureExtractor: () => (/* binding */ MoonshineFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - -class MoonshineFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - /** - * Asynchronously extracts input values from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. - */ - async _call(audio) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'MoonshineFeatureExtractor'); - - if (audio instanceof Float64Array) { - audio = new Float32Array(audio); - } - - const shape = [ - 1, /* batch_size */ - audio.length, /* num_samples */ - ]; - return { - input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('float32', audio, shape), - }; + get byteLength() { + return _s(this.dataType, this.tensorShape); } -} - - -/***/ }), - -/***/ "./src/models/moonshine/processing_moonshine.js": -/*!******************************************************!*\ - !*** ./src/models/moonshine/processing_moonshine.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MoonshineProcessor: () => (/* binding */ MoonshineProcessor) -/* harmony export */ }); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); - - - - -/** - * Represents a MoonshineProcessor that extracts features from an audio input. - */ -class MoonshineProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor - - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio); + destroy() { + le("verbose", () => "[WebNN] TensorWrapper.destroy"), this.mlTensor.destroy(); } -} - - -/***/ }), - -/***/ "./src/models/nougat/image_processing_nougat.js": -/*!******************************************************!*\ - !*** ./src/models/nougat/image_processing_nougat.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ NougatImageProcessor: () => (/* binding */ NougatImageProcessor) -/* harmony export */ }); -/* harmony import */ var _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../donut/image_processing_donut.js */ "./src/models/donut/image_processing_donut.js"); - - - -// NOTE: extends DonutImageProcessor -class NougatImageProcessor extends _donut_image_processing_donut_js__WEBPACK_IMPORTED_MODULE_0__.DonutImageProcessor { } - - -/***/ }), - -/***/ "./src/models/owlv2/image_processing_owlv2.js": -/*!****************************************************!*\ - !*** ./src/models/owlv2/image_processing_owlv2.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Owlv2ImageProcessor: () => (/* binding */ Owlv2ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../owlvit/image_processing_owlvit.js */ "./src/models/owlvit/image_processing_owlvit.js"); - - - -// NOTE: extends OwlViTImageProcessor -class Owlv2ImageProcessor extends _owlvit_image_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_0__.OwlViTImageProcessor { } - - -/***/ }), - -/***/ "./src/models/owlvit/image_processing_owlvit.js": -/*!******************************************************!*\ - !*** ./src/models/owlvit/image_processing_owlvit.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ OwlViTFeatureExtractor: () => (/* binding */ OwlViTFeatureExtractor), -/* harmony export */ OwlViTImageProcessor: () => (/* binding */ OwlViTImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class OwlViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** @type {typeof post_process_object_detection} */ - post_process_object_detection(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + write(r) { + this.mlContext.writeTensor(this.mlTensor, r); } -} -class OwlViTFeatureExtractor extends OwlViTImageProcessor { } - - -/***/ }), - -/***/ "./src/models/owlvit/processing_owlvit.js": -/*!************************************************!*\ - !*** ./src/models/owlvit/processing_owlvit.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ OwlViTProcessor: () => (/* binding */ OwlViTProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); - - - -class OwlViTProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor -} - - -/***/ }), - -/***/ "./src/models/paligemma/processing_paligemma.js": -/*!******************************************************!*\ - !*** ./src/models/paligemma/processing_paligemma.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ PaliGemmaProcessor: () => (/* binding */ PaliGemmaProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); - - - - -const IMAGE_TOKEN = ""; - -function build_string_from_input( - prompt, - bos_token, - image_seq_len, - image_token, - num_images, -) { - return `${image_token.repeat(image_seq_len * num_images)}${bos_token}${prompt}\n` -} - -class PaliGemmaProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - static uses_processor_config = false; - - /** - * @typedef {import('../../utils/image.js').RawImage} RawImage - */ - - // `images` is required, `text` is optional - async _call(/** @type {RawImage|RawImage[]} */ images, text = null, kwargs = {}) { - if (!text) { - console.warn( - "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model." - ) - text = "" - } - - if (!Array.isArray(images)) { - images = [images] - } - - if (!Array.isArray(text)) { - text = [text] - } - - const bos_token = this.tokenizer.bos_token; - // @ts-expect-error TS2339 - const image_seq_length = this.image_processor.config.image_seq_length; - let input_strings; - if (text.some((t) => t.includes(IMAGE_TOKEN))) { - input_strings = text.map( - sample => { - const expanded_sample = sample.replaceAll(IMAGE_TOKEN, IMAGE_TOKEN.repeat(image_seq_length)); - const bos_rfind_index = expanded_sample.lastIndexOf(IMAGE_TOKEN); - const bos_index = bos_rfind_index === -1 ? 0 : bos_rfind_index + IMAGE_TOKEN.length; - return expanded_sample.slice(0, bos_index) + bos_token + expanded_sample.slice(bos_index) + "\n"; - } - ) - } else { - 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." - ) - - input_strings = text.map( - sample => build_string_from_input( - sample, - bos_token, - image_seq_length, - IMAGE_TOKEN, - images.length, - ) - ) - } - - const text_inputs = this.tokenizer(input_strings, kwargs); - const image_inputs = await this.image_processor(images, kwargs); - - return { - ...image_inputs, - ...text_inputs, - } + async read(r) { + if (this.fallbackDataType) { + let s = await this.mlContext.readTensor(this.mlTensor), f = Us(new Uint8Array(s), this.dataType); + if (r) { + (r instanceof ArrayBuffer ? new Uint8Array(r) : new Uint8Array(r.buffer, r.byteOffset, r.byteLength)).set(f); + return; + } else return new Uint8Array(f).buffer; + } else return r ? this.mlContext.readTensor(this.mlTensor, r) : this.mlContext.readTensor(this.mlTensor); } -} - - -/***/ }), - -/***/ "./src/models/phi3_v/image_processing_phi3_v.js": -/*!******************************************************!*\ - !*** ./src/models/phi3_v/image_processing_phi3_v.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Phi3VImageProcessor: () => (/* binding */ Phi3VImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - -const IMAGE_SIZE = 336; -const SLICE_AXES = [2, 3]; // axes to slice on -const { ceil, floor, sqrt } = Math; - -class Phi3VImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - constructor(config) { - super({ - ...config, - do_normalize: true, - do_pad: true, - pad_size: 'custom', - do_convert_rgb: true, - do_resize: true, // Smart resizing "hd_transform" - }); - - this._num_crops = config.num_crops; + canReuseTensor(r, s, f) { + return this.mlContext === r && this.dataType === s && this.tensorShape.length === f.length && this.tensorShape.every((i, p) => i === f[p]); } - calc_num_image_tokens_from_image_size(width, height) { - // @ts-expect-error - const { num_img_tokens } = this.config; - return floor(((floor((height / IMAGE_SIZE)) * floor((width / IMAGE_SIZE)) + 1) * num_img_tokens) + 1 + (floor(height / IMAGE_SIZE) + 1) * sqrt(num_img_tokens)); + setIsDataConverted(r) { + this.isDataConverted = r; } - - /** @type {ImageProcessor['get_resize_output_image_size']} */ - get_resize_output_image_size(image, size) { - const hd_num = this._num_crops; - const [width, height] = image.size - - let ratio = width / height; - let scale = 1; - - // Calculate the scaling factor - while (scale * Math.ceil(scale / ratio) <= hd_num) { - scale += 1; - } - scale -= 1; - - // Compute the new dimensions - const new_w = Math.floor(scale * 336); - const new_h = Math.floor(new_w / ratio); - - return [new_w, new_h] + }, lr = class { + constructor(r, s) { + this.tensorManager = r; + this.wrapper = s; } - - - /** @type {ImageProcessor['pad_image']} */ - pad_image(pixelData, imgDims, padSize, options = {}) { - // Phi3V uses a custom padding strategy: - // - Pad to a multiple of 336 - // - Pad with white pixels - const [imageHeight, imageWidth] = imgDims; - const height = IMAGE_SIZE * ceil(imageHeight / IMAGE_SIZE); - const width = IMAGE_SIZE * ceil(imageWidth / IMAGE_SIZE); - - // NOTE: Since padding is done after normalization, we need to fill with the normalized values - const constant_values = [1, 1, 1].map((x, i) => (x - this.image_mean[i]) / this.image_std[i]); - return super.pad_image(pixelData, imgDims, { width, height }, { - center: true, - constant_values, - ...options, - }); + get tensorWrapper() { + return this.wrapper; } - - async _call(images, { - num_crops = null, - } = {}) { - // @ts-expect-error - this._num_crops = num_crops ??= this.config.num_crops; - if (num_crops < 4 || sqrt(num_crops) % 1 !== 0) { - throw new Error("num_crops must be a square number >= 4"); - } - - if (!Array.isArray(images)) { - images = [images]; - } - - const num_images = images.length; - const imageData = await Promise.all(images.map(x => this.preprocess(x))); - - const original_sizes = imageData.map(x => x.original_size); - const reshaped_input_sizes = imageData.map(x => x.reshaped_input_size); - - // Process each image in batch - const all_pixel_values = []; - for (const { pixel_values } of imageData) { - pixel_values.unsqueeze_(0); // Easier processing as 4D tensor - - const [height, width] = pixel_values.dims.slice(-2); - - // Global image (Tensor of shape [num_channels, height, width]) - const batch_pixel_values = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)(pixel_values, { - size: [IMAGE_SIZE, IMAGE_SIZE], - mode: 'bicubic', - }); - - if (num_crops > 0) { - const patches = []; - const sqrt_patches = sqrt(num_crops); - const patch_width = floor(width / sqrt_patches); - const patch_height = floor(height / sqrt_patches); - for (let y = 0; y < sqrt_patches; ++y) { - for (let x = 0; x < sqrt_patches; ++x) { - let start_x, start_y, end_x, end_y; - if (y === sqrt_patches - 1) { // At bottom - start_y = height - patch_height; - end_y = height; - } else { - start_y = y * patch_height; - end_y = (y + 1) * patch_height; - } - if (x === sqrt_patches - 1) { // At right - start_x = width - patch_width; - end_x = width; - } else { - start_x = x * patch_width; - end_x = (x + 1) * patch_width; - } - - const starts = [start_y, start_x]; - const ends = [end_y, end_x]; - const patch = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.slice)(pixel_values, starts, ends, SLICE_AXES); - patches.push(patch); - } - } - - const resized_tensors = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.interpolate_4d)((0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(patches, 0), { - size: [IMAGE_SIZE, IMAGE_SIZE], - mode: 'bicubic', - }); // [num_crops, 3, 336, 336] - - // Concatenate the global image with the patches - all_pixel_values.push((0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)([batch_pixel_values, resized_tensors], 0)); - } else { - // Only use the global image - // NOTE: Not currently supported in modelling code - all_pixel_values.push(batch_pixel_values); - } - } - - // [num_images, 1 + num_crops, num_channels=3, height, width] - const pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(all_pixel_values, 0); - - // Calculate padded image sizes - const sizes = reshaped_input_sizes.map(x => x.map(y => IMAGE_SIZE * ceil(y / IMAGE_SIZE))); - - const image_sizes = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - 'int64', - sizes.flat(), - [num_images, 2], - ); - - const num_img_tokens = sizes.map( - ([height, width]) => this.calc_num_image_tokens_from_image_size(width, height), - ); - - return { pixel_values, original_sizes, reshaped_input_sizes, image_sizes, num_img_tokens }; + releaseTensor() { + this.tensorWrapper && (this.tensorManager.releaseTensor(this.tensorWrapper), this.wrapper = void 0); } -} - - -/***/ }), - -/***/ "./src/models/phi3_v/processing_phi3_v.js": -/*!************************************************!*\ - !*** ./src/models/phi3_v/processing_phi3_v.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Phi3VProcessor: () => (/* binding */ Phi3VProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/image.js */ "./src/utils/image.js"); - - - - - -const IMAGE_TOKEN = "<|image|>"; -const IMAGE_TOKEN_PATTERN = /<\|image_\d+\|>/g; - -class Phi3VProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - - /** - * - * @param {string|string[]} text - * @param {RawImage|RawImage[]} images - * @param { { padding?: boolean, truncation?: boolean, num_crops?: number } | undefined } options - * @returns {Promise} - */ - async _call(text, images = null, { - padding = true, - truncation = true, - num_crops = null, - } = {}) { - - if (!Array.isArray(text)) { - text = [text]; + async ensureTensor(r, s, f, i) { + let p = this.tensorManager.getMLContext(r), l = this.tensorManager.getMLOpSupportLimits(r), b; + if (!l?.input.dataTypes.includes(s)) { + if (b = Rc.get(s), !b || !l?.input.dataTypes.includes(b)) throw new Error(`WebNN backend does not support data type: ${s}`); + le("verbose", () => `[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${s} to ${b}`); + } + if (this.wrapper) { + if (this.wrapper.canReuseTensor(p, s, f)) return this.wrapper.tensor; + if (i) { + if (this.wrapper.byteLength !== _s(s, f)) throw new Error("Unable to copy data to tensor with different size."); + this.activeUpload = new Uint8Array(await this.wrapper.read()); } - - let text_inputs, image_inputs; - if (images) { - image_inputs = await this.image_processor(images, { num_crops }); - const { num_img_tokens } = image_inputs; - - // The original implementation adds a bos_token before the image tokens - // TODO: Check if this affects performance, since it looks like a bug in the original implementation - const prompt_chunks = text.map((t, i) => t.split(IMAGE_TOKEN_PATTERN).join(IMAGE_TOKEN.repeat(num_img_tokens[i]))); - - text_inputs = this.tokenizer(prompt_chunks, { padding, truncation }); - - // The model expects image tokens to be negative, so we negate the image token ids - const image_token_id = this.tokenizer.model.convert_tokens_to_ids([IMAGE_TOKEN])[0]; - text_inputs.input_ids.map_(id => (id == image_token_id) ? -id : id); - } else { - text_inputs = this.tokenizer(text); + this.tensorManager.releaseTensor(this.wrapper); + } + let g = typeof MLTensorUsage > "u" ? void 0 : MLTensorUsage.READ | MLTensorUsage.WRITE; + return this.wrapper = await this.tensorManager.getCachedTensor(r, s, f, g, true, true, b), i && this.activeUpload && (this.wrapper.write(this.activeUpload), this.activeUpload = void 0), this.wrapper.tensor; + } + upload(r) { + let s = r; + if (this.wrapper) { + if (this.wrapper.fallbackType) if (this.wrapper.fallbackType === "int32") s = Uc(r, this.wrapper.type), this.wrapper.setIsDataConverted(true); + else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`); + if (r.byteLength === this.wrapper.byteLength) { + this.wrapper.write(s); + return; + } else le("verbose", () => "Data size does not match tensor size. Releasing tensor."), this.releaseTensor(); + } + this.activeUpload ? this.activeUpload.set(s) : this.activeUpload = new Uint8Array(s); + } + async download(r) { + if (this.activeUpload) { + let s = this.wrapper?.isDataConverted ? Us(this.activeUpload, this.wrapper?.type) : this.activeUpload; + if (r) { + r instanceof ArrayBuffer ? new Uint8Array(r).set(s) : new Uint8Array(r.buffer, r.byteOffset, r.byteLength).set(s); + return; + } else return s.buffer; + } + if (!this.wrapper) throw new Error("Tensor has not been created."); + return r ? this.wrapper.read(r) : this.wrapper.read(); + } + }, ln = class { + constructor(r) { + this.backend = r; + this.tensorTrackersById = /* @__PURE__ */ new Map(); + this.freeTensors = []; + this.externalTensors = /* @__PURE__ */ new Set(); + } + getMLContext(r) { + let s = this.backend.getMLContext(r); + if (!s) throw new Error("MLContext not found for session."); + return s; + } + getMLOpSupportLimits(r) { + return this.backend.getMLOpSupportLimits(r); + } + reserveTensorId() { + let r = Ds(); + return this.tensorTrackersById.set(r, new lr(this)), r; + } + releaseTensorId(r) { + let s = this.tensorTrackersById.get(r); + s && (this.tensorTrackersById.delete(r), s.tensorWrapper && this.releaseTensor(s.tensorWrapper)); + } + async ensureTensor(r, s, f, i, p) { + le("verbose", () => `[WebNN] TensorManager.ensureTensor {tensorId: ${s}, dataType: ${f}, shape: ${i}, copyOld: ${p}}`); + let l = this.tensorTrackersById.get(s); + if (!l) throw new Error("Tensor not found."); + return l.ensureTensor(r, f, i, p); + } + upload(r, s) { + let f = this.tensorTrackersById.get(r); + if (!f) throw new Error("Tensor not found."); + f.upload(s); + } + async download(r, s) { + le("verbose", () => `[WebNN] TensorManager.download {tensorId: ${r}, dstBuffer: ${s?.byteLength}}`); + let f = this.tensorTrackersById.get(r); + if (!f) throw new Error("Tensor not found."); + return f.download(s); + } + releaseTensorsForSession(r) { + for (let s of this.freeTensors) s.sessionId === r && s.destroy(); + this.freeTensors = this.freeTensors.filter((s) => s.sessionId !== r); + } + registerTensor(r, s, f, i) { + let p = this.getMLContext(r), l = Ds(), b = new dr({ sessionId: r, context: p, tensor: s, dataType: f, shape: i }); + return this.tensorTrackersById.set(l, new lr(this, b)), this.externalTensors.add(b), l; + } + async getCachedTensor(r, s, f, i, p, l, b) { + let g = this.getMLContext(r); + for (let [S, v] of this.freeTensors.entries()) if (v.canReuseTensor(g, s, f)) { + le("verbose", () => `[WebNN] Reusing tensor {dataType: ${s}, ${b ? `fallbackDataType: ${b},` : ""} shape: ${f}`); + let T = this.freeTensors.splice(S, 1)[0]; + return T.sessionId = r, T; + } + le("verbose", () => `[WebNN] MLContext.createTensor {dataType: ${s}, ${b ? `fallbackDataType: ${b},` : ""} shape: ${f}}`); + let w = await g.createTensor({ dataType: b ?? s, shape: f, dimensions: f, usage: i, writable: p, readable: l }); + return new dr({ sessionId: r, context: g, tensor: w, dataType: s, shape: f, fallbackDataType: b }); + } + releaseTensor(r) { + this.externalTensors.has(r) && this.externalTensors.delete(r), this.freeTensors.push(r); + } + }, Rs = (...a) => new ln(...a); +}); +var Ws = {}; +At(Ws, { WebNNBackend: () => pn }); +var pr; +var Nc; +var pn; +var ks = G(() => { + "use strict"; + ut(); + je(); + Bs(); + Ns(); + dn(); + pr = /* @__PURE__ */ new Map([[1, "float32"], [10, "float16"], [6, "int32"], [12, "uint32"], [7, "int64"], [13, "uint64"], [22, "int4"], [21, "uint4"], [3, "int8"], [2, "uint8"], [9, "uint8"]]), Nc = (a, r) => { + if (a === r) return true; + if (a === void 0 || r === void 0) return false; + let s = Object.keys(a).sort(), f = Object.keys(r).sort(); + return s.length === f.length && s.every((i, p) => i === f[p] && a[i] === r[i]); + }, pn = class { + constructor(r) { + this.tensorManager = Rs(this); + this.mlContextBySessionId = /* @__PURE__ */ new Map(); + this.sessionIdsByMLContext = /* @__PURE__ */ new Map(); + this.mlContextCache = []; + this.sessionGraphInputs = /* @__PURE__ */ new Map(); + this.sessionGraphOutputs = /* @__PURE__ */ new Map(); + this.temporaryGraphInputs = []; + this.temporaryGraphOutputs = []; + this.temporarySessionTensorIds = /* @__PURE__ */ new Map(); + this.mlOpSupportLimitsBySessionId = /* @__PURE__ */ new Map(); + Cs(r.logLevel, !!r.debug); + } + get currentSessionId() { + if (this.activeSessionId === void 0) throw new Error("No active session"); + return this.activeSessionId; + } + onRunStart(r) { + le("verbose", () => `[WebNN] onRunStart {sessionId: ${r}}`), this.activeSessionId = r; + } + onRunEnd(r) { + le("verbose", () => `[WebNN] onRunEnd {sessionId: ${r}}`); + let s = this.temporarySessionTensorIds.get(r); + if (s) { + for (let f of s) le("verbose", () => `[WebNN] releasing temporary tensor {tensorId: ${f}}`), this.tensorManager.releaseTensorId(f); + this.temporarySessionTensorIds.delete(r), this.activeSessionId = void 0; + } + } + async createMLContext(r) { + if (r instanceof GPUDevice) { + let f = this.mlContextCache.findIndex((i) => i.gpuDevice === r); + if (f !== -1) return this.mlContextCache[f].mlContext; + { + let i = await navigator.ml.createContext(r); + return this.mlContextCache.push({ gpuDevice: r, mlContext: i }), i; } - - return { - ...text_inputs, - ...image_inputs, + } else if (r === void 0) { + let f = this.mlContextCache.findIndex((i) => i.options === void 0 && i.gpuDevice === void 0); + if (f !== -1) return this.mlContextCache[f].mlContext; + { + let i = await navigator.ml.createContext(); + return this.mlContextCache.push({ mlContext: i }), i; } + } + let s = this.mlContextCache.findIndex((f) => Nc(f.options, r)); + if (s !== -1) return this.mlContextCache[s].mlContext; + { + let f = await navigator.ml.createContext(r); + return this.mlContextCache.push({ options: r, mlContext: f }), f; + } } -} - - -/***/ }), - -/***/ "./src/models/processors.js": -/*!**********************************!*\ - !*** ./src/models/processors.js ***! - \**********************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Florence2Processor: () => (/* reexport safe */ _florence2_processing_florence2_js__WEBPACK_IMPORTED_MODULE_0__.Florence2Processor), -/* harmony export */ Gemma3nProcessor: () => (/* reexport safe */ _gemma3n_processing_gemma3n_js__WEBPACK_IMPORTED_MODULE_1__.Gemma3nProcessor), -/* harmony export */ GroundingDinoProcessor: () => (/* reexport safe */ _grounding_dino_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_2__.GroundingDinoProcessor), -/* harmony export */ Idefics3Processor: () => (/* reexport safe */ _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_3__.Idefics3Processor), -/* harmony export */ JinaCLIPProcessor: () => (/* reexport safe */ _jina_clip_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_5__.JinaCLIPProcessor), -/* harmony export */ LlavaProcessor: () => (/* reexport safe */ _llava_processing_llava_js__WEBPACK_IMPORTED_MODULE_6__.LlavaProcessor), -/* harmony export */ MgpstrProcessor: () => (/* reexport safe */ _mgp_str_processing_mgp_str_js__WEBPACK_IMPORTED_MODULE_7__.MgpstrProcessor), -/* harmony export */ MoonshineProcessor: () => (/* reexport safe */ _moonshine_processing_moonshine_js__WEBPACK_IMPORTED_MODULE_8__.MoonshineProcessor), -/* harmony export */ OwlViTProcessor: () => (/* reexport safe */ _owlvit_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_9__.OwlViTProcessor), -/* harmony export */ PaliGemmaProcessor: () => (/* reexport safe */ _paligemma_processing_paligemma_js__WEBPACK_IMPORTED_MODULE_11__.PaliGemmaProcessor), -/* harmony export */ Phi3VProcessor: () => (/* reexport safe */ _phi3_v_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_10__.Phi3VProcessor), -/* harmony export */ PyAnnoteProcessor: () => (/* reexport safe */ _pyannote_processing_pyannote_js__WEBPACK_IMPORTED_MODULE_12__.PyAnnoteProcessor), -/* harmony export */ Qwen2VLProcessor: () => (/* reexport safe */ _qwen2_vl_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_13__.Qwen2VLProcessor), -/* harmony export */ SamProcessor: () => (/* reexport safe */ _sam_processing_sam_js__WEBPACK_IMPORTED_MODULE_14__.SamProcessor), -/* harmony export */ SmolVLMProcessor: () => (/* reexport safe */ _smolvlm_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_15__.SmolVLMProcessor), -/* harmony export */ SpeechT5Processor: () => (/* reexport safe */ _speecht5_processing_speecht5_js__WEBPACK_IMPORTED_MODULE_16__.SpeechT5Processor), -/* harmony export */ UltravoxProcessor: () => (/* reexport safe */ _ultravox_processing_ultravox_js__WEBPACK_IMPORTED_MODULE_17__.UltravoxProcessor), -/* harmony export */ VLChatProcessor: () => (/* reexport safe */ _janus_processing_janus_js__WEBPACK_IMPORTED_MODULE_4__.VLChatProcessor), -/* harmony export */ VoxtralProcessor: () => (/* reexport safe */ _voxtral_processing_voxtral_js__WEBPACK_IMPORTED_MODULE_18__.VoxtralProcessor), -/* harmony export */ Wav2Vec2Processor: () => (/* reexport safe */ _wav2vec2_processing_wav2vec2_js__WEBPACK_IMPORTED_MODULE_19__.Wav2Vec2Processor), -/* harmony export */ Wav2Vec2ProcessorWithLM: () => (/* reexport safe */ _wav2vec2_with_lm_processing_wav2vec2_with_lm_js__WEBPACK_IMPORTED_MODULE_20__.Wav2Vec2ProcessorWithLM), -/* harmony export */ WhisperProcessor: () => (/* reexport safe */ _whisper_processing_whisper_js__WEBPACK_IMPORTED_MODULE_21__.WhisperProcessor) -/* harmony export */ }); -/* harmony import */ var _florence2_processing_florence2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./florence2/processing_florence2.js */ "./src/models/florence2/processing_florence2.js"); -/* harmony import */ var _gemma3n_processing_gemma3n_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gemma3n/processing_gemma3n.js */ "./src/models/gemma3n/processing_gemma3n.js"); -/* harmony import */ var _grounding_dino_processing_grounding_dino_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./grounding_dino/processing_grounding_dino.js */ "./src/models/grounding_dino/processing_grounding_dino.js"); -/* harmony import */ var _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./idefics3/processing_idefics3.js */ "./src/models/idefics3/processing_idefics3.js"); -/* harmony import */ var _janus_processing_janus_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./janus/processing_janus.js */ "./src/models/janus/processing_janus.js"); -/* harmony import */ var _jina_clip_processing_jina_clip_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./jina_clip/processing_jina_clip.js */ "./src/models/jina_clip/processing_jina_clip.js"); -/* harmony import */ var _llava_processing_llava_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./llava/processing_llava.js */ "./src/models/llava/processing_llava.js"); -/* harmony import */ var _mgp_str_processing_mgp_str_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./mgp_str/processing_mgp_str.js */ "./src/models/mgp_str/processing_mgp_str.js"); -/* harmony import */ var _moonshine_processing_moonshine_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./moonshine/processing_moonshine.js */ "./src/models/moonshine/processing_moonshine.js"); -/* harmony import */ var _owlvit_processing_owlvit_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./owlvit/processing_owlvit.js */ "./src/models/owlvit/processing_owlvit.js"); -/* harmony import */ var _phi3_v_processing_phi3_v_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./phi3_v/processing_phi3_v.js */ "./src/models/phi3_v/processing_phi3_v.js"); -/* harmony import */ var _paligemma_processing_paligemma_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./paligemma/processing_paligemma.js */ "./src/models/paligemma/processing_paligemma.js"); -/* harmony import */ var _pyannote_processing_pyannote_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./pyannote/processing_pyannote.js */ "./src/models/pyannote/processing_pyannote.js"); -/* harmony import */ var _qwen2_vl_processing_qwen2_vl_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./qwen2_vl/processing_qwen2_vl.js */ "./src/models/qwen2_vl/processing_qwen2_vl.js"); -/* harmony import */ var _sam_processing_sam_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./sam/processing_sam.js */ "./src/models/sam/processing_sam.js"); -/* harmony import */ var _smolvlm_processing_smolvlm_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./smolvlm/processing_smolvlm.js */ "./src/models/smolvlm/processing_smolvlm.js"); -/* harmony import */ var _speecht5_processing_speecht5_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./speecht5/processing_speecht5.js */ "./src/models/speecht5/processing_speecht5.js"); -/* harmony import */ var _ultravox_processing_ultravox_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./ultravox/processing_ultravox.js */ "./src/models/ultravox/processing_ultravox.js"); -/* harmony import */ var _voxtral_processing_voxtral_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./voxtral/processing_voxtral.js */ "./src/models/voxtral/processing_voxtral.js"); -/* harmony import */ var _wav2vec2_processing_wav2vec2_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./wav2vec2/processing_wav2vec2.js */ "./src/models/wav2vec2/processing_wav2vec2.js"); -/* harmony import */ var _wav2vec2_with_lm_processing_wav2vec2_with_lm_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./wav2vec2_with_lm/processing_wav2vec2_with_lm.js */ "./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"); -/* harmony import */ var _whisper_processing_whisper_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./whisper/processing_whisper.js */ "./src/models/whisper/processing_whisper.js"); - - - - - - - - - - - - - - - - - - - - - - - - -/***/ }), - -/***/ "./src/models/pvt/image_processing_pvt.js": -/*!************************************************!*\ - !*** ./src/models/pvt/image_processing_pvt.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ PvtImageProcessor: () => (/* binding */ PvtImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class PvtImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/pyannote/feature_extraction_pyannote.js": -/*!************************************************************!*\ - !*** ./src/models/pyannote/feature_extraction_pyannote.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ PyAnnoteFeatureExtractor: () => (/* binding */ PyAnnoteFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/maths.js */ "./src/utils/maths.js"); - - - - - -class PyAnnoteFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor; }>} The extracted input features. - */ - async _call(audio) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'PyAnnoteFeatureExtractor'); - - if (audio instanceof Float64Array) { - audio = new Float32Array(audio); - } - - const shape = [ - 1, /* batch_size */ - 1, /* num_channels */ - audio.length, /* num_samples */ - ]; - return { - input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('float32', audio, shape), - }; + registerMLContext(r, s) { + this.mlContextBySessionId.set(r, s); + let f = this.sessionIdsByMLContext.get(s); + f || (f = /* @__PURE__ */ new Set(), this.sessionIdsByMLContext.set(s, f)), f.add(r), this.mlOpSupportLimitsBySessionId.has(r) || this.mlOpSupportLimitsBySessionId.set(r, s.opSupportLimits()), this.temporaryGraphInputs.length > 0 && (this.sessionGraphInputs.set(r, this.temporaryGraphInputs), this.temporaryGraphInputs = []), this.temporaryGraphOutputs.length > 0 && (this.sessionGraphOutputs.set(r, this.temporaryGraphOutputs), this.temporaryGraphOutputs = []); + } + onReleaseSession(r) { + this.sessionGraphInputs.delete(r), this.sessionGraphOutputs.delete(r); + let s = this.mlContextBySessionId.get(r); + if (!s) return; + this.tensorManager.releaseTensorsForSession(r), this.mlContextBySessionId.delete(r), this.mlOpSupportLimitsBySessionId.delete(r); + let f = this.sessionIdsByMLContext.get(s); + if (f.delete(r), f.size === 0) { + this.sessionIdsByMLContext.delete(s); + let i = this.mlContextCache.findIndex((p) => p.mlContext === s); + i !== -1 && this.mlContextCache.splice(i, 1); + } } - - /** - * NOTE: Can return fractional values. `Math.ceil` will ensure correct value. - * @param {number} samples The number of frames in the audio. - * @returns {number} The number of frames in the audio. - */ - samples_to_frames(samples) { - return ((samples - this.config.offset) / this.config.step); + getMLContext(r) { + return this.mlContextBySessionId.get(r); } - - /** - * Post-processes the speaker diarization logits output by the model. - * @param {import('../../utils/tensor.js').Tensor} logits The speaker diarization logits output by the model. - * @param {number} num_samples Number of samples in the input audio. - * @returns {Array>} The post-processed speaker diarization results. - */ - post_process_speaker_diarization(logits, num_samples) { - const ratio = ( - num_samples / this.samples_to_frames(num_samples) - ) / this.config.sampling_rate; - - const results = []; - for (const scores of logits.tolist()) { - const accumulated_segments = []; - - let current_speaker = -1; - for (let i = 0; i < scores.length; ++i) { - /** @type {number[]} */ - const probabilities = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.softmax)(scores[i]); - const [score, id] = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_2__.max)(probabilities); - const [start, end] = [i, i + 1]; - - if (id !== current_speaker) { - // Speaker has changed - current_speaker = id; - accumulated_segments.push({ id, start, end, score }); - } else { - // Continue the current segment - accumulated_segments.at(-1).end = end; - accumulated_segments.at(-1).score += score; - } - } - - results.push(accumulated_segments.map( - // Convert frame-space to time-space - // and compute the confidence - ({ id, start, end, score }) => ({ - id, - start: start * ratio, - end: end * ratio, - confidence: score / (end - start), - }) - )); - } - return results; + getMLOpSupportLimits(r) { + return this.mlOpSupportLimitsBySessionId.get(r); } - -} - - -/***/ }), - -/***/ "./src/models/pyannote/processing_pyannote.js": -/*!****************************************************!*\ - !*** ./src/models/pyannote/processing_pyannote.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ PyAnnoteProcessor: () => (/* binding */ PyAnnoteProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./feature_extraction_pyannote.js */ "./src/models/pyannote/feature_extraction_pyannote.js"); - - - -class PyAnnoteProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static feature_extractor_class = _feature_extraction_pyannote_js__WEBPACK_IMPORTED_MODULE_1__.PyAnnoteFeatureExtractor - - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio) + reserveTensorId() { + return this.tensorManager.reserveTensorId(); } - - /** @type {PyAnnoteFeatureExtractor['post_process_speaker_diarization']} */ - post_process_speaker_diarization(...args) { - return /** @type {PyAnnoteFeatureExtractor} */(this.feature_extractor).post_process_speaker_diarization(...args); + releaseTensorId(r) { + le("verbose", () => `[WebNN] releaseTensorId {tensorId: ${r}}`), this.tensorManager.releaseTensorId(r); } - - get sampling_rate() { - return this.feature_extractor.config.sampling_rate; + async ensureTensor(r, s, f, i, p) { + let l = pr.get(f); + if (!l) throw new Error(`Unsupported ONNX data type: ${f}`); + return this.tensorManager.ensureTensor(r ?? this.currentSessionId, s, l, i, p); } -} - - -/***/ }), - -/***/ "./src/models/qwen2_vl/image_processing_qwen2_vl.js": -/*!**********************************************************!*\ - !*** ./src/models/qwen2_vl/image_processing_qwen2_vl.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Qwen2VLImageProcessor: () => (/* binding */ Qwen2VLImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - -class Qwen2VLImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - async _call(images, ...args) { - const { pixel_values, original_sizes, reshaped_input_sizes } = await super._call(images, ...args); - - let patches = pixel_values; - - // @ts-ignore - const { temporal_patch_size, merge_size, patch_size } = this.config; - if (patches.dims[0] === 1) { - // Equivalent to np.tile(patches, (self.temporal_patch_size, 1, 1, 1)) - patches = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)(Array.from({ length: temporal_patch_size }, () => patches), 0); - } - - const grid_t = patches.dims[0] / temporal_patch_size; - const channel = patches.dims[1]; - const grid_h = Math.floor(patches.dims[2] / patch_size); - const grid_w = Math.floor(patches.dims[3] / patch_size); - - const flatten_patches = patches - .view( - grid_t, - temporal_patch_size, - channel, - Math.floor(grid_h / merge_size), - merge_size, - patch_size, - Math.floor(grid_w / merge_size), - merge_size, - patch_size, - ) - .permute(0, 3, 6, 4, 7, 2, 1, 5, 8) - .view( - grid_t * grid_h * grid_w, - channel * temporal_patch_size * patch_size * patch_size, - ) - - const image_grid_thw = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('int64', [grid_t, grid_h, grid_w], [1, 3]); - - return { - pixel_values: flatten_patches, - image_grid_thw, - original_sizes, - reshaped_input_sizes, - } + async createTemporaryTensor(r, s, f) { + le("verbose", () => `[WebNN] createTemporaryTensor {onnxDataType: ${s}, shape: ${f}}`); + let i = pr.get(s); + if (!i) throw new Error(`Unsupported ONNX data type: ${s}`); + let p = this.tensorManager.reserveTensorId(); + await this.tensorManager.ensureTensor(r, p, i, f, false); + let l = this.temporarySessionTensorIds.get(r); + return l ? l.push(p) : this.temporarySessionTensorIds.set(r, [p]), p; } -} - - - -/***/ }), - -/***/ "./src/models/qwen2_vl/processing_qwen2_vl.js": -/*!****************************************************!*\ - !*** ./src/models/qwen2_vl/processing_qwen2_vl.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Qwen2VLProcessor: () => (/* binding */ Qwen2VLProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/image.js */ "./src/utils/image.js"); - - - - - -class Qwen2VLProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_2__.AutoTokenizer - - /** - * - * @param {string|string[]} text - * @param {RawImage|RawImage[]} images - * @param {...any} args - * @returns {Promise} - */ - async _call(text, images = null, ...args) { - - if (!Array.isArray(text)) { - text = [text]; - } - - let image_inputs, image_grid_thw; - - if (images) { - image_inputs = await this.image_processor(images); - image_grid_thw = image_inputs.image_grid_thw; - } - - if (image_grid_thw) { - // @ts-expect-error TS2551 - let merge_length = this.image_processor.config.merge_size ** 2; - let index = 0; - - const image_grid_thw_list = image_grid_thw.tolist(); - text = text.map(t => { - while (t.includes("<|image_pad|>")) { - const prod = Number(image_grid_thw_list[index++].reduce((a, b) => a * b, 1n)); - t = t.replace("<|image_pad|>", "<|placeholder|>".repeat(Math.floor(prod / merge_length))); - } - return t.replaceAll("<|placeholder|>", "<|image_pad|>"); - }); - } - - const text_inputs = this.tokenizer(text); - - return { - ...text_inputs, - ...image_inputs, - // TODO: ...videos_inputs, - } + uploadTensor(r, s) { + if (!j().shouldTransferToMLTensor) throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false"); + le("verbose", () => `[WebNN] uploadTensor {tensorId: ${r}, data: ${s.byteLength}}`), this.tensorManager.upload(r, s); } -} - - -/***/ }), - -/***/ "./src/models/rt_detr/image_processing_rt_detr.js": -/*!********************************************************!*\ - !*** ./src/models/rt_detr/image_processing_rt_detr.js ***! - \********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ RTDetrImageProcessor: () => (/* binding */ RTDetrImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class RTDetrImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** @type {typeof post_process_object_detection} */ - post_process_object_detection(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + async downloadTensor(r, s) { + return this.tensorManager.download(r, s); } -} - - -/***/ }), - -/***/ "./src/models/sam/image_processing_sam.js": -/*!************************************************!*\ - !*** ./src/models/sam/image_processing_sam.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SamImageProcessor: () => (/* binding */ SamImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - - - -/** - * @typedef {object} SamImageProcessorResult - * @property {Tensor} pixel_values - * @property {import("../../base/image_processors_utils.js").HeightWidth[]} original_sizes - * @property {import("../../base/image_processors_utils.js").HeightWidth[]} reshaped_input_sizes - * @property {Tensor} [input_points] - * @property {Tensor} [input_labels] - * @property {Tensor} [input_boxes] - */ - -class SamImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - - /** - * - * @param {any} input_points - * @param {import("../../base/image_processors_utils.js").HeightWidth[]} original_sizes - * @param {import("../../base/image_processors_utils.js").HeightWidth[]} reshaped_input_sizes - * @returns {Tensor} - */ - reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) { - - // Make deep copy to avoid altering user's input - input_points = structuredClone(input_points); - let shape = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.calculateDimensions)(input_points); - - // TODO: add support for 2D input_points - if (shape.length === 3) { - // Correct user's input - if (!is_bounding_box) { - shape = [1, ...shape]; - } - input_points = [input_points]; - } else if (shape.length !== 4) { - throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.") - } - - // Reshape input points - for (let i = 0; i < input_points.length; ++i) { // batch_size - let originalImageSize = original_sizes[i]; - let reshapedImageSize = reshaped_input_sizes[i]; - - let resizeFactors = [ - reshapedImageSize[0] / originalImageSize[0], - reshapedImageSize[1] / originalImageSize[1] - ] - - for (let j = 0; j < input_points[i].length; ++j) { // point_batch_size - for (let k = 0; k < input_points[i][j].length; ++k) { // nb_points_per_image - for (let w = 0; w < input_points[i][j][k].length; ++w) { // 2 or 4 - input_points[i][j][k][w] *= resizeFactors[w % 2]; - } - } - } + createMLTensorDownloader(r, s) { + return async () => { + let f = await this.tensorManager.download(r); + return Ls(f, s); + }; + } + registerMLTensor(r, s, f, i) { + let p = pr.get(f); + if (!p) throw new Error(`Unsupported ONNX data type: ${f}`); + let l = this.tensorManager.registerTensor(r, s, p, i); + return le("verbose", () => `[WebNN] registerMLTensor {tensor: ${s}, dataType: ${p}, dimensions: ${i}} -> {tensorId: ${l}}`), l; + } + registerGraphInput(r) { + this.temporaryGraphInputs.push(r); + } + registerGraphOutput(r) { + this.temporaryGraphOutputs.push(r); + } + isGraphInput(r, s) { + let f = this.sessionGraphInputs.get(r); + return f ? f.includes(s) : false; + } + isGraphOutput(r, s) { + let f = this.sessionGraphOutputs.get(r); + return f ? f.includes(s) : false; + } + isGraphInputOutputTypeSupported(r, s, f = true) { + let i = pr.get(He(s)), p = this.mlOpSupportLimitsBySessionId.get(r); + return typeof i > "u" ? false : f ? !!p?.input.dataTypes.includes(i) : !!p?.output.dataTypes.includes(i); + } + flush() { + } + }; +}); +var Wc; +var Qt; +var er; +var ft; +var kc; +var Fs; +var Lt; +var tr; +var rr; +var Gs; +var nr; +var or; +var ar; +var nn = G(() => { + "use strict"; + Ve(); + xs(); + Is(); + ut(); + je(); + ir(); + cn(); + Wc = (a, r) => { + j()._OrtInit(a, r) !== 0 && V("Can't initialize onnxruntime."); + }, Qt = async (a) => { + Wc(a.wasm.numThreads, Mt(a.logLevel)); + }, er = async (a, r) => { + j().asyncInit?.(); + let s = a.webgpu.adapter; + if (r === "webgpu") { + if (typeof navigator > "u" || !navigator.gpu) throw new Error("WebGPU is not supported in current environment"); + 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 f = a.webgpu.powerPreference; + if (f !== void 0 && f !== "low-power" && f !== "high-performance") throw new Error(`Invalid powerPreference setting: "${f}"`); + let i = a.webgpu.forceFallbackAdapter; + if (i !== void 0 && typeof i != "boolean") throw new Error(`Invalid forceFallbackAdapter setting: "${i}"`); + if (s = await navigator.gpu.requestAdapter({ powerPreference: f, forceFallbackAdapter: i }), !s) throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.'); + } + } + if (r === "webnn" && (typeof navigator > "u" || !navigator.ml)) throw new Error("WebNN is not supported in current environment"); + if (r === "webgpu" && j().webgpuInit((f) => { + a.webgpu.device = f; + }), r === "webnn") { + let f = new (ks(), Ht(Ws)).WebNNBackend(a); + j().webnnInit([f, () => f.reserveTensorId(), (i) => f.releaseTensorId(i), async (i, p, l, b, g) => f.ensureTensor(i, p, l, b, g), (i, p) => { + f.uploadTensor(i, p); + }, async (i, p) => f.downloadTensor(i, p), (i, p) => f.registerMLContext(i, p), !!a.trace]); + } + }, ft = /* @__PURE__ */ new Map(), kc = (a) => { + let r = j(), s = r.stackSave(); + try { + let f = r.PTR_SIZE, i = r.stackAlloc(2 * f); + r._OrtGetInputOutputCount(a, i, i + f) !== 0 && V("Can't get session input/output count."); + let l = f === 4 ? "i32" : "i64"; + return [Number(r.getValue(i, l)), Number(r.getValue(i + f, l))]; + } finally { + r.stackRestore(s); + } + }, Fs = (a, r) => { + let s = j(), f = s.stackSave(), i = 0; + try { + let p = s.PTR_SIZE, l = s.stackAlloc(2 * p); + s._OrtGetInputOutputMetadata(a, r, l, l + p) !== 0 && V("Can't get session input/output metadata."); + let g = Number(s.getValue(l, "*")); + i = Number(s.getValue(l + p, "*")); + let w = s.HEAP32[i / 4]; + if (w === 0) return [g, 0]; + let S = s.HEAPU32[i / 4 + 1], v = []; + for (let T = 0; T < S; T++) { + let A = Number(s.getValue(i + 8 + T * p, "*")); + v.push(A !== 0 ? s.UTF8ToString(A) : Number(s.getValue(i + 8 + (T + S) * p, "*"))); + } + return [g, w, v]; + } finally { + s.stackRestore(f), i !== 0 && s._OrtFree(i); + } + }, Lt = (a) => { + let r = j(), s = r._malloc(a.byteLength); + if (s === 0) throw new Error(`Can't create a session. failed to allocate a buffer of size ${a.byteLength}.`); + return r.HEAPU8.set(a, s), [s, a.byteLength]; + }, tr = async (a, r) => { + let s, f, i = j(); + Array.isArray(a) ? [s, f] = a : a.buffer === i.HEAPU8.buffer ? [s, f] = [a.byteOffset, a.byteLength] : [s, f] = Lt(a); + let p = 0, l = 0, b = 0, g = [], w = [], S = []; + try { + if ([l, g] = await As(r), r?.externalData && i.mountExternalData) { + let O = []; + for (let $ of r.externalData) { + let oe = typeof $ == "string" ? $ : $.path, d = typeof $ == "string" ? $ : $.data; + O.push(Ct(d).then((te) => { + i.mountExternalData(oe, te); + })); + } + await Promise.all(O); + } + for (let O of r?.executionProviders ?? []) if ((typeof O == "string" ? O : O.name) === "webnn") { + if (i.shouldTransferToMLTensor = false, typeof O != "string") { + let oe = O, d = oe?.context, te = oe?.gpuDevice, Z = oe?.deviceType, X = oe?.powerPreference; + d ? i.currentContext = d : te ? i.currentContext = await i.webnnCreateMLContext(te) : i.currentContext = await i.webnnCreateMLContext({ deviceType: Z, powerPreference: X }); + } else i.currentContext = await i.webnnCreateMLContext(); + break; + } + p = await i._OrtCreateSession(s, f, l), i.webgpuOnCreateSession?.(p), p === 0 && V("Can't create a session."), i.jsepOnCreateSession?.(), i.currentContext && (i.webnnRegisterMLContext(p, i.currentContext), i.currentContext = void 0, i.shouldTransferToMLTensor = true); + let [v, T] = kc(p), A = !!r?.enableGraphCapture, C = [], _ = [], k = [], U = [], M = []; + for (let O = 0; O < v; O++) { + let [$, oe, d] = Fs(p, O); + $ === 0 && V("Can't get an input name."), w.push($); + let te = i.UTF8ToString($); + C.push(te), k.push(oe === 0 ? { name: te, isTensor: false } : { name: te, isTensor: true, type: ur(oe), shape: d }); + } + for (let O = 0; O < T; O++) { + let [$, oe, d] = Fs(p, O + v); + $ === 0 && V("Can't get an output name."), S.push($); + let te = i.UTF8ToString($); + _.push(te), U.push(oe === 0 ? { name: te, isTensor: false } : { name: te, isTensor: true, type: ur(oe), shape: d }); + { + if (A && r?.preferredOutputLocation === void 0) { + M.push("gpu-buffer"); + continue; + } + let Z = typeof r?.preferredOutputLocation == "string" ? r.preferredOutputLocation : r?.preferredOutputLocation?.[te] ?? "cpu", X = i.webnnIsGraphOutput; + if (Z === "cpu" && X && X(p, te)) { + M.push("ml-tensor-cpu-output"); + continue; + } + if (Z !== "cpu" && Z !== "cpu-pinned" && Z !== "gpu-buffer" && Z !== "ml-tensor") throw new Error(`Not supported preferred output location: ${Z}.`); + if (A && Z !== "gpu-buffer") throw new Error(`Not supported preferred output location: ${Z}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`); + M.push(Z); } - - return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor( - 'float32', - Float32Array.from(input_points.flat(Infinity)), - shape - ) - - } - - /** - * - * @param {any} input_labels - * @param {Tensor} input_points - * @returns {Tensor} - */ - add_input_labels(input_labels, input_points) { - let shape = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.calculateDimensions)(input_labels); - if (shape.length === 2) { - // Correct user's input - shape = [1, ...shape]; - input_labels = [input_labels]; - } else if (shape.length !== 3) { - throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.") - } - - if (shape.some((x, i) => x !== input_points.dims[i])) { - throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`) - } - return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor( - 'int64', - input_labels.flat(Infinity).map(BigInt), - shape, - ) + } + let Y = null; + return M.some((O) => O === "gpu-buffer" || O === "ml-tensor" || O === "ml-tensor-cpu-output") && (b = i._OrtCreateBinding(p), b === 0 && V("Can't create IO binding."), Y = { handle: b, outputPreferredLocations: M, outputPreferredLocationsEncoded: M.map((O) => O === "ml-tensor-cpu-output" ? "ml-tensor" : O).map((O) => fn(O)) }), ft.set(p, [p, w, S, Y, A, false]), [p, C, _, k, U]; + } catch (v) { + throw w.forEach((T) => i._OrtFree(T)), S.forEach((T) => i._OrtFree(T)), b !== 0 && i._OrtReleaseBinding(b) !== 0 && V("Can't release IO binding."), p !== 0 && i._OrtReleaseSession(p) !== 0 && V("Can't release session."), v; + } finally { + i._free(s), l !== 0 && i._OrtReleaseSessionOptions(l) !== 0 && V("Can't release session options."), g.forEach((v) => i._free(v)), i.unmountExternalData?.(); + } + }, rr = (a) => { + let r = j(), s = ft.get(a); + if (!s) throw new Error(`cannot release session. invalid session id: ${a}`); + let [f, i, p, l, b] = s; + l && (b && r._OrtClearBoundOutputs(l.handle) !== 0 && V("Can't clear bound outputs."), r._OrtReleaseBinding(l.handle) !== 0 && V("Can't release IO binding.")), r.jsepOnReleaseSession?.(a), r.webnnOnReleaseSession?.(a), r.webgpuOnReleaseSession?.(a), i.forEach((g) => r._OrtFree(g)), p.forEach((g) => r._OrtFree(g)), r._OrtReleaseSession(f) !== 0 && V("Can't release session."), ft.delete(a); + }, Gs = async (a, r, s, f, i, p, l = false) => { + if (!a) { + r.push(0); + return; } - /** - * @param {any[]} images The URL(s) of the image(s) to extract features from. - * @param {Object} [options] Additional options for the processor. - * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user. - * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. - * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. - * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. - * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. - * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. - * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user. - * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. - * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size, - * the number of boxes per image and the coordinates of the top left and botton right point of the box. - * In the order (`x1`, `y1`, `x2`, `y2`): - * - `x1`: the x coordinate of the top left point of the input box - * - `y1`: the y coordinate of the top left point of the input box - * - `x2`: the x coordinate of the bottom right point of the input box - * - `y2`: the y coordinate of the bottom right point of the input box - * @returns {Promise} - */ - async _call(images, { - input_points = null, - input_labels = null, - input_boxes = null - } = {}) { - // TODO allow user to use preprocessed images - /** @type {SamImageProcessorResult} */ - const processed = await super._call(images); - - if (input_points) { - processed.input_points = this.reshape_input_points( - input_points, processed.original_sizes, processed.reshaped_input_sizes - ); + let b = j(), g = b.PTR_SIZE, w = a[0], S = a[1], v = a[3], T = v, A, C; + if (w === "string" && (v === "gpu-buffer" || v === "ml-tensor")) throw new Error("String tensor is not supported on GPU."); + if (l && v !== "gpu-buffer") throw new Error(`External buffer must be provided for input/output index ${p} when enableGraphCapture is true.`); + if (v === "gpu-buffer") { + let U = a[2].gpuBuffer; + C = bt(He(w), S); + { + let M = b.webgpuRegisterBuffer; + if (!M) throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.'); + A = M(U, f); + } + } else if (v === "ml-tensor") { + let U = a[2].mlTensor; + C = bt(He(w), S); + let M = b.webnnRegisterMLTensor; + if (!M) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.'); + A = M(f, U, He(w), S); + } else { + let U = a[2]; + if (Array.isArray(U)) { + C = g * U.length, A = b._malloc(C), s.push(A); + for (let M = 0; M < U.length; M++) { + if (typeof U[M] != "string") throw new TypeError(`tensor data at index ${M} is not a string`); + b.setValue(A + M * g, be(U[M], s), "*"); } - - if (input_labels) { - if (!processed.input_points) { - throw Error("`input_points` must be provided if `input_labels` are provided.") - } - processed.input_labels = this.add_input_labels(input_labels, processed.input_points); + } else { + let M = b.webnnIsGraphInput, Y = b.webnnIsGraphOutput; + if (w !== "string" && M && Y) { + let O = b.UTF8ToString(i); + if (M(f, O) || Y(f, O)) { + let $ = He(w); + C = bt($, S), T = "ml-tensor"; + let oe = b.webnnCreateTemporaryTensor, d = b.webnnUploadTensor; + if (!oe || !d) throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.'); + let te = await oe(f, $, S); + d(te, new Uint8Array(U.buffer, U.byteOffset, U.byteLength)), A = te; + } else C = U.byteLength, A = b._malloc(C), s.push(A), b.HEAPU8.set(new Uint8Array(U.buffer, U.byteOffset, C), A); + } else C = U.byteLength, A = b._malloc(C), s.push(A), b.HEAPU8.set(new Uint8Array(U.buffer, U.byteOffset, C), A); + } + } + let _ = b.stackSave(), k = b.stackAlloc(4 * S.length); + try { + S.forEach((M, Y) => b.setValue(k + Y * g, M, g === 4 ? "i32" : "i64")); + let U = b._OrtCreateTensor(He(w), A, C, k, S.length, fn(T)); + U === 0 && V(`Can't create tensor for input/output. session=${f}, index=${p}.`), r.push(U); + } finally { + b.stackRestore(_); + } + }, nr = async (a, r, s, f, i, p) => { + let l = j(), b = l.PTR_SIZE, g = ft.get(a); + if (!g) throw new Error(`cannot run inference. invalid session id: ${a}`); + let w = g[0], S = g[1], v = g[2], T = g[3], A = g[4], C = g[5], _ = r.length, k = f.length, U = 0, M = [], Y = [], O = [], $ = [], oe = [], d = l.stackSave(), te = l.stackAlloc(_ * b), Z = l.stackAlloc(_ * b), X = l.stackAlloc(k * b), De = l.stackAlloc(k * b); + try { + [U, M] = Ss(p), $e("wasm prepareInputOutputTensor"); + for (let R = 0; R < _; R++) await Gs(s[R], Y, $, a, S[r[R]], r[R], A); + for (let R = 0; R < k; R++) await Gs(i[R], O, $, a, v[f[R]], _ + f[R], A); + ze("wasm prepareInputOutputTensor"); + for (let R = 0; R < _; R++) l.setValue(te + R * b, Y[R], "*"), l.setValue(Z + R * b, S[r[R]], "*"); + for (let R = 0; R < k; R++) l.setValue(X + R * b, O[R], "*"), l.setValue(De + R * b, v[f[R]], "*"); + if (T && !C) { + let { handle: R, outputPreferredLocations: ae, outputPreferredLocationsEncoded: pe } = T; + if (S.length !== _) throw new Error(`input count from feeds (${_}) is expected to be always equal to model's input count (${S.length}).`); + $e("wasm bindInputsOutputs"); + for (let J = 0; J < _; J++) { + let ge = r[J]; + await l._OrtBindInput(R, S[ge], Y[J]) !== 0 && V(`Can't bind input[${J}] for session=${a}.`); + } + for (let J = 0; J < k; J++) { + let ge = f[J]; + i[J]?.[3] ? (oe.push(O[J]), l._OrtBindOutput(R, v[ge], O[J], 0) !== 0 && V(`Can't bind pre-allocated output[${J}] for session=${a}.`)) : l._OrtBindOutput(R, v[ge], 0, pe[ge]) !== 0 && V(`Can't bind output[${J}] to ${ae[J]} for session=${a}.`); + } + ze("wasm bindInputsOutputs"), ft.set(a, [w, S, v, T, A, true]); + } + l.jsepOnRunStart?.(w), l.webnnOnRunStart?.(w); + let K; + T ? K = await l._OrtRunWithBinding(w, T.handle, k, X, U) : K = await l._OrtRun(w, Z, te, _, De, k, X, U), K !== 0 && V("failed to call OrtRun()."); + let I = [], E = []; + $e("wasm ProcessOutputTensor"); + for (let R = 0; R < k; R++) { + let ae = Number(l.getValue(X + R * b, "*")); + if (ae === O[R] || oe.includes(O[R])) { + I.push(i[R]), ae !== O[R] && l._OrtReleaseTensor(ae) !== 0 && V("Can't release tensor."); + continue; } - - if (input_boxes) { - processed.input_boxes = this.reshape_input_points( - input_boxes, processed.original_sizes, processed.reshaped_input_sizes, true, - ); + let pe = l.stackSave(), J = l.stackAlloc(4 * b), ge = false, ne, se = 0; + try { + l._OrtGetTensorData(ae, J, J + b, J + 2 * b, J + 3 * b) !== 0 && V(`Can't access output tensor data on index ${R}.`); + let we = b === 4 ? "i32" : "i64", qe = Number(l.getValue(J, we)); + se = l.getValue(J + b, "*"); + let wt = l.getValue(J + b * 2, "*"), Tt = Number(l.getValue(J + b * 3, we)), Se = []; + for (let re = 0; re < Tt; re++) Se.push(Number(l.getValue(wt + re * b, we))); + l._OrtFree(wt) !== 0 && V("Can't free memory for tensor dims."); + let xe = Se.reduce((re, Q) => re * Q, 1); + ne = ur(qe); + let Be = T?.outputPreferredLocations[f[R]]; + if (ne === "string") { + if (Be === "gpu-buffer" || Be === "ml-tensor") throw new Error("String tensor is not supported on GPU."); + let re = []; + for (let Q = 0; Q < xe; Q++) { + let z = l.getValue(se + Q * b, "*"), H = l.getValue(se + (Q + 1) * b, "*"), Ye = Q === xe - 1 ? void 0 : H - z; + re.push(l.UTF8ToString(z, Ye)); + } + I.push([ne, Se, re, "cpu"]); + } else if (Be === "gpu-buffer" && xe > 0) { + let re = l.webgpuGetBuffer; + if (!re) throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.'); + let Q = re(se), z = bt(qe, xe); + if (z === void 0 || !fr(ne)) throw new Error(`Unsupported data type: ${ne}`); + ge = true; + { + l.webgpuRegisterBuffer(Q, a, se); + let H = l.webgpuCreateDownloader(Q, z, a); + I.push([ne, Se, { gpuBuffer: Q, download: async () => { + let Ye = await H(); + return new (it(ne))(Ye); + }, dispose: () => { + l._OrtReleaseTensor(ae) !== 0 && V("Can't release tensor."); + } }, "gpu-buffer"]); + } + } else if (Be === "ml-tensor" && xe > 0) { + let re = l.webnnEnsureTensor, Q = l.webnnIsGraphInputOutputTypeSupported; + if (!re || !Q) throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.'); + if (bt(qe, xe) === void 0 || !cr(ne)) throw new Error(`Unsupported data type: ${ne}`); + if (!Q(a, ne, false)) throw new Error(`preferredLocation "ml-tensor" for ${ne} output is not supported by current WebNN Context.`); + let H = await re(a, se, qe, Se, false); + ge = true, I.push([ne, Se, { mlTensor: H, download: l.webnnCreateMLTensorDownloader(se, ne), dispose: () => { + l.webnnReleaseTensorId(se), l._OrtReleaseTensor(ae); + } }, "ml-tensor"]); + } else if (Be === "ml-tensor-cpu-output" && xe > 0) { + let re = l.webnnCreateMLTensorDownloader(se, ne)(), Q = I.length; + ge = true, E.push((async () => { + let z = [Q, await re]; + return l.webnnReleaseTensorId(se), l._OrtReleaseTensor(ae), z; + })()), I.push([ne, Se, [], "cpu"]); + } else { + let re = it(ne), Q = new re(xe); + new Uint8Array(Q.buffer, Q.byteOffset, Q.byteLength).set(l.HEAPU8.subarray(se, se + Q.byteLength)), I.push([ne, Se, Q, "cpu"]); + } + } finally { + l.stackRestore(pe), ne === "string" && se && l._free(se), ge || l._OrtReleaseTensor(ae); } - - return processed; + } + T && !A && (l._OrtClearBoundOutputs(T.handle) !== 0 && V("Can't clear bound outputs."), ft.set(a, [w, S, v, T, A, false])); + for (let [R, ae] of await Promise.all(E)) I[R][2] = ae; + return ze("wasm ProcessOutputTensor"), I; + } finally { + l.webnnOnRunEnd?.(w), l.stackRestore(d), s.forEach((K) => { + K && K[3] === "gpu-buffer" && l.webgpuUnregisterBuffer(K[2].gpuBuffer); + }), i.forEach((K) => { + K && K[3] === "gpu-buffer" && l.webgpuUnregisterBuffer(K[2].gpuBuffer); + }), Y.forEach((K) => l._OrtReleaseTensor(K)), O.forEach((K) => l._OrtReleaseTensor(K)), $.forEach((K) => l._free(K)), U !== 0 && l._OrtReleaseRunOptions(U), M.forEach((K) => l._free(K)); + } + }, or = (a) => { + let r = j(), s = ft.get(a); + if (!s) throw new Error("invalid session id"); + let f = s[0], i = r._OrtEndProfiling(f); + i === 0 && V("Can't get an profile file name."), r._OrtFree(i); + }, ar = (a) => { + let r = []; + for (let s of a) { + let f = s[2]; + !Array.isArray(f) && "buffer" in f && r.push(f.buffer); + } + return r; + }; +}); +var ct; +var Ee; +var Dt; +var hr; +var br; +var mr; +var mn; +var hn; +var gt; +var yt; +var Gc; +var $s; +var zs; +var Vs; +var js; +var Hs; +var qs; +var Ys; +var bn = G(() => { + "use strict"; + Ve(); + nn(); + je(); + Zt(); + ct = () => !!ee.wasm.proxy && typeof document < "u", Dt = false, hr = false, br = false, hn = /* @__PURE__ */ new Map(), gt = (a, r) => { + let s = hn.get(a); + s ? s.push(r) : hn.set(a, [r]); + }, yt = () => { + if (Dt || !hr || br || !Ee) throw new Error("worker not ready"); + }, Gc = (a) => { + switch (a.data.type) { + case "init-wasm": + Dt = false, a.data.err ? (br = true, mn[1](a.data.err)) : (hr = true, mn[0]()), mr && (URL.revokeObjectURL(mr), mr = void 0); + break; + case "init-ep": + case "copy-from": + case "create": + case "release": + case "run": + case "end-profiling": { + let r = hn.get(a.data.type); + a.data.err ? r.shift()[1](a.data.err) : r.shift()[0](a.data.out); + break; + } + default: } - - /** - * Remove padding and upscale masks to the original image size. - * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. - * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. - * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. - * @param {Object} options Optional parameters for post-processing. - * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. - * @param {boolean} [options.binarize] Whether to binarize the masks. - * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. - * @param {number} [options.pad_size.height] The height the images were padded to. - * @param {number} [options.pad_size.width] The width the images were padded to. - * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. - */ - async post_process_masks(masks, original_sizes, reshaped_input_sizes, { - mask_threshold = 0.0, - binarize = true, - pad_size = null, - } = {}) { - // masks: [1, 1, 3, 256, 256] - - const output_masks = []; - - pad_size = pad_size ?? this.pad_size; - - /** @type {[number, number]} */ - const target_image_size = [pad_size.height, pad_size.width]; - - for (let i = 0; i < original_sizes.length; ++i) { - const original_size = original_sizes[i]; - const reshaped_input_size = reshaped_input_sizes[i]; - - // Upscale mask to padded size - let interpolated_mask = (await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.interpolate_4d)( - masks[i], - { mode: 'bilinear', size: target_image_size } - )); - - // Crop mask - interpolated_mask = interpolated_mask.slice(null, null, [0, reshaped_input_size[0]], [0, reshaped_input_size[1]]); - - // Downscale mask - interpolated_mask = (await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.interpolate_4d)( - interpolated_mask, - { mode: 'bilinear', size: original_size } - )); - - if (binarize) { - const data = interpolated_mask.data; - const binarizedMaskData = new Uint8Array(data.length); - for (let i = 0; i < data.length; ++i) { - if (data[i] > mask_threshold) { - binarizedMaskData[i] = 1; - } - } - interpolated_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_2__.Tensor( - 'bool', - binarizedMaskData, - interpolated_mask.dims - ) - } - - output_masks.push(interpolated_mask); - } - - return output_masks; + }, $s = async () => { + if (!hr) { + if (Dt) throw new Error("multiple calls to 'initWasm()' detected."); + if (br) throw new Error("previous call to 'initWasm()' failed."); + if (Dt = true, ct()) return new Promise((a, r) => { + Ee?.terminate(), Ts().then(([s, f]) => { + try { + Ee = f, Ee.onerror = (p) => r(p), Ee.onmessage = Gc, mn = [a, r]; + let i = { type: "init-wasm", in: ee }; + !i.in.wasm.wasmPaths && (s || an) && (i.in.wasm.wasmPaths = { wasm: new URL("ort-wasm-simd-threaded.asyncify.wasm", import.meta.url).href }), Ee.postMessage(i), mr = s; + } catch (i) { + r(i); + } + }, r); + }); + try { + await Kt(ee.wasm), await Qt(ee), hr = true; + } catch (a) { + throw br = true, a; + } finally { + Dt = false; + } } - - /** - * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. - * @param {import("../../utils/image.js").RawImage} image Input original image - * @param {number} target_size Target size of the resized image - * @param {Object} options Options for generating crop boxes - * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image. - * Sets the number of layers to run, where each layer has 2**i_layer number of image crops. - * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer, - * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. - * @param {number} [options.points_per_crop] Number of points to sample from each crop. - * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is - * scaled down by crop_n_points_downscale_factor**n. - * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels. - */ - generate_crop_boxes(image, target_size, { - crop_n_layers = 0, - overlap_ratio = 512 / 1500, - points_per_crop = 32, - crop_n_points_downscale_factor = 1, - } = {}) { - // TODO: Implement - // return { crop_boxes, points_per_crop, cropped_images, input_labels } + }, zs = async (a) => { + if (ct()) return yt(), new Promise((r, s) => { + gt("init-ep", [r, s]); + let f = { type: "init-ep", in: { epName: a, env: ee } }; + Ee.postMessage(f); + }); + await er(ee, a); + }, Vs = async (a) => ct() ? (yt(), new Promise((r, s) => { + gt("copy-from", [r, s]); + let f = { type: "copy-from", in: { buffer: a } }; + Ee.postMessage(f, [a.buffer]); + })) : Lt(a), js = async (a, r) => { + if (ct()) { + if (r?.preferredOutputLocation) throw new Error('session option "preferredOutputLocation" is not supported for proxy.'); + return yt(), new Promise((s, f) => { + gt("create", [s, f]); + let i = { type: "create", in: { model: a, options: { ...r } } }, p = []; + a instanceof Uint8Array && p.push(a.buffer), Ee.postMessage(i, p); + }); + } else return tr(a, r); + }, Hs = async (a) => { + if (ct()) return yt(), new Promise((r, s) => { + gt("release", [r, s]); + let f = { type: "release", in: a }; + Ee.postMessage(f); + }); + rr(a); + }, qs = async (a, r, s, f, i, p) => { + if (ct()) { + if (s.some((l) => l[3] !== "cpu")) throw new Error("input tensor on GPU is not supported for proxy."); + if (i.some((l) => l)) throw new Error("pre-allocated output tensor is not supported for proxy."); + return yt(), new Promise((l, b) => { + gt("run", [l, b]); + let g = s, w = { type: "run", in: { sessionId: a, inputIndices: r, inputs: g, outputIndices: f, options: p } }; + Ee.postMessage(w, ar(g)); + }); + } else return nr(a, r, s, f, i, p); + }, Ys = async (a) => { + if (ct()) return yt(), new Promise((r, s) => { + gt("end-profiling", [r, s]); + let f = { type: "end-profiling", in: a }; + Ee.postMessage(f); + }); + or(a); + }; +}); +var Js; +var $c; +var gr; +var Xs = G(() => { + "use strict"; + Ve(); + bn(); + ut(); + Xt(); + cn(); + Js = (a, r) => { + switch (a.location) { + case "cpu": + return [a.type, a.dims, a.data, "cpu"]; + case "gpu-buffer": + return [a.type, a.dims, { gpuBuffer: a.gpuBuffer }, "gpu-buffer"]; + case "ml-tensor": + return [a.type, a.dims, { mlTensor: a.mlTensor }, "ml-tensor"]; + default: + throw new Error(`invalid data location: ${a.location} for ${r()}`); + } + }, $c = (a) => { + switch (a[3]) { + case "cpu": + return new Le(a[0], a[2], a[1]); + case "gpu-buffer": { + let r = a[0]; + if (!fr(r)) throw new Error(`not supported data type: ${r} for deserializing GPU tensor`); + let { gpuBuffer: s, download: f, dispose: i } = a[2]; + return Le.fromGpuBuffer(s, { dataType: r, dims: a[1], download: f, dispose: i }); + } + case "ml-tensor": { + let r = a[0]; + if (!cr(r)) throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`); + let { mlTensor: s, download: f, dispose: i } = a[2]; + return Le.fromMLTensor(s, { dataType: r, dims: a[1], download: f, dispose: i }); + } + default: + throw new Error(`invalid data location: ${a[3]}`); } -} - - - -/***/ }), - -/***/ "./src/models/sam/processing_sam.js": -/*!******************************************!*\ - !*** ./src/models/sam/processing_sam.js ***! - \******************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SamProcessor: () => (/* binding */ SamProcessor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); - - - -class SamProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static image_processor_class = _auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoImageProcessor - - async _call(...args) { - return await this.image_processor(...args); + }, gr = class { + async fetchModelAndCopyToWasmMemory(r) { + return Vs(await Ct(r)); } - - post_process_masks(...args) { - // @ts-ignore - return this.image_processor.post_process_masks(...args); + async loadModel(r, s) { + ot(); + let f; + typeof r == "string" ? f = await this.fetchModelAndCopyToWasmMemory(r) : f = r, [this.sessionId, this.inputNames, this.outputNames, this.inputMetadata, this.outputMetadata] = await js(f, s), at(); } - - reshape_input_points(...args) { - // @ts-ignore - return this.image_processor.reshape_input_points(...args); + async dispose() { + return Hs(this.sessionId); + } + async run(r, s, f) { + ot(); + let i = [], p = []; + Object.entries(r).forEach((T) => { + let A = T[0], C = T[1], _ = this.inputNames.indexOf(A); + if (_ === -1) throw new Error(`invalid input '${A}'`); + i.push(C), p.push(_); + }); + let l = [], b = []; + Object.entries(s).forEach((T) => { + let A = T[0], C = T[1], _ = this.outputNames.indexOf(A); + if (_ === -1) throw new Error(`invalid output '${A}'`); + l.push(C), b.push(_); + }); + let g = i.map((T, A) => Js(T, () => `input "${this.inputNames[p[A]]}"`)), w = l.map((T, A) => T ? Js(T, () => `output "${this.outputNames[b[A]]}"`) : null), S = await qs(this.sessionId, p, g, b, w, f), v = {}; + for (let T = 0; T < S.length; T++) v[this.outputNames[b[T]]] = l[T] ?? $c(S[T]); + return at(), v; + } + startProfiling() { + } + endProfiling() { + Ys(this.sessionId); + } + }; +}); +var Ks = {}; +At(Ks, { OnnxruntimeWebAssemblyBackend: () => yr, initializeFlags: () => Zs, wasmBackend: () => zc }); +var Zs; +var yr; +var zc; +var Qs = G(() => { + "use strict"; + Ve(); + bn(); + Xs(); + Zs = () => { + (typeof ee.wasm.initTimeout != "number" || ee.wasm.initTimeout < 0) && (ee.wasm.initTimeout = 0); + let a = ee.wasm.simd; + if (typeof a != "boolean" && a !== void 0 && a !== "fixed" && a !== "relaxed" && (console.warn(`Property "env.wasm.simd" is set to unknown value "${a}". Reset it to \`false\` and ignore SIMD feature checking.`), ee.wasm.simd = false), typeof ee.wasm.proxy != "boolean" && (ee.wasm.proxy = false), typeof ee.wasm.trace != "boolean" && (ee.wasm.trace = false), typeof ee.wasm.numThreads != "number" || !Number.isInteger(ee.wasm.numThreads) || ee.wasm.numThreads <= 0) if (typeof self < "u" && !self.crossOriginIsolated) ee.wasm.numThreads = 1; + else { + let r = typeof navigator > "u" ? Xr("node:os").cpus().length : navigator.hardwareConcurrency; + ee.wasm.numThreads = Math.min(4, Math.ceil((r || 1) / 2)); + } + }, yr = class { + async init(r) { + Zs(), await $s(), await zs(r); + } + async createInferenceSessionHandler(r, s) { + let f = new gr(); + return await f.loadModel(r, s), f; + } + }, zc = new yr(); +}); +Ve(); +Ve(); +Ve(); +var is = "1.31.0-dev.20260914-8d85527a0"; +var $l = rn; +{ + let a = (Qs(), Ht(Ks)).wasmBackend; + rt("webgpu", a, 5), rt("webnn", a, 5), rt("cpu", a, 10), rt("wasm", a, 10); +} +Object.defineProperty(ee.versions, "web", { value: is, enumerable: true }); + +// src/backends/utils/cacheWasm.js +async function loadAndCacheFile(url) { + const fileName = url.split("/").pop(); + let cache2; + try { + cache2 = await getCache(); + if (cache2) { + const result = await cache2.match(url); + if (result) { + return result; + } } + } catch (error) { + logger.warn(`Failed to load ${fileName} from cache:`, error); + } + const response = await env.fetch(url); + if (!response.ok) { + throw new Error(`Failed to fetch ${fileName}: ${response.status} ${response.statusText}`); + } + if (cache2) { + try { + await cache2.put(url, response.clone()); + } catch (e) { + logger.warn(`Failed to cache ${fileName}:`, e); + } + } + return response; +} +async function loadWasmBinary(wasmURL) { + const response = await loadAndCacheFile(wasmURL); + if (!response || typeof response === "string") return null; + try { + return await response.arrayBuffer(); + } catch (error) { + logger.warn("Failed to read WASM binary:", error); + return null; + } +} +async function loadWasmFactory(libURL) { + if (apis.IS_SERVICE_WORKER_ENV || apis.IS_CHROME_AVAILABLE) { + return libURL; + } + const response = await loadAndCacheFile(libURL); + if (!response || typeof response === "string") return null; + try { + let code = await response.text(); + code = code.replaceAll("globalThis.process?.versions?.node", "false"); + const blob = new Blob([code], { type: "text/javascript" }); + return URL.createObjectURL(blob); + } catch (error) { + logger.warn("Failed to read WASM factory:", error); + return null; + } } -/***/ }), - -/***/ "./src/models/seamless_m4t/feature_extraction_seamless_m4t.js": -/*!********************************************************************!*\ - !*** ./src/models/seamless_m4t/feature_extraction_seamless_m4t.js ***! - \********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SeamlessM4TFeatureExtractor: () => (/* binding */ SeamlessM4TFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); - - - - -class SeamlessM4TFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - - constructor(config) { - super(config); - - const sampling_rate = this.config.sampling_rate; - const mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - 257, // num_frequency_bins - this.config.num_mel_bins, // num_mel_filters - 20, // min_frequency - Math.floor(sampling_rate / 2), // max_frequency - sampling_rate, // sampling_rate - null, // norm - "kaldi", // mel_scale - true, // triangularize_in_mel_space - ); - this.mel_filters = mel_filters; +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/version.js +var version = "1.30.0"; - this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(400, 'povey', { - periodic: false, - }) +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/env-impl.js +var logLevelValue = "warning"; +var env2 = { + wasm: {}, + webgl: {}, + webgpu: {}, + versions: { common: version }, + set logLevel(value) { + if (value === void 0) { + return; } - - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @param {number} max_length The maximum number of frames to return. - * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - async _extract_fbank_features(waveform, max_length) { - // NOTE: We don't pad/truncate since that is passed in as `max_num_frames` - - // Kaldi compliance: 16-bit signed integers - // 32768 == 2 ** 15 - waveform = waveform.map((/** @type {number} */ x) => x * 32768) - - return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( - waveform, - this.window, // window - 400, // frame_length - 160, // hop_length - { - fft_length: 512, - power: 2.0, - center: false, - preemphasis: 0.97, - mel_filters: this.mel_filters, - log_mel: 'log', - mel_floor: 1.192092955078125e-07, - remove_dc_offset: true, - - // Custom - max_num_frames: max_length, - transpose: true, - } - ) + if (typeof value !== "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(value) === -1) { + throw new Error(`Unsupported logging level: ${value}`); } - - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @param {Object} options Optional parameters for feature extraction. - * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. - * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of. - * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel. - * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask. - * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. - */ - async _call(audio, { - padding = true, - pad_to_multiple_of = 2, - do_normalize_per_mel_bins = true, - return_attention_mask = true, - } = {}) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'SeamlessM4TFeatureExtractor'); - - let features = await this._extract_fbank_features(audio, this.config.max_length); - - if (do_normalize_per_mel_bins) { - const [num_features, feature_size] = features.dims; - const data = features.data; - for (let i = 0; i < feature_size; ++i) { - let sum = 0; - for (let j = 0; j < num_features; ++j) { - sum += data[j * feature_size + i]; - } - - const mean = sum / num_features; - - let variance = 0; - for (let j = 0; j < num_features; ++j) { - variance += (data[j * feature_size + i] - mean) ** 2; - } - variance /= num_features - 1; // NOTE: We use ddof=1 - - const std = Math.sqrt(variance + 1e-7); - for (let j = 0; j < num_features; ++j) { - const index = j * feature_size + i; - data[index] = (data[index] - mean) / std; - } - } + logLevelValue = value; + }, + get logLevel() { + return logLevelValue; + } +}; +Object.defineProperty(env2, "logLevel", { enumerable: true }); + +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/tensor-conversion-impl.js +var tensorToDataURL = (tensor, options) => { + const canvas = typeof document !== "undefined" ? document.createElement("canvas") : new OffscreenCanvas(1, 1); + canvas.width = tensor.dims[3]; + canvas.height = tensor.dims[2]; + const pixels2DContext = canvas.getContext("2d"); + if (pixels2DContext != null) { + let width; + let height; + if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") { + width = tensor.dims[2]; + height = tensor.dims[3]; + } else { + width = tensor.dims[3]; + height = tensor.dims[2]; + } + const inputformat = options?.format !== void 0 ? options.format : "RGB"; + const norm = options?.norm; + let normMean; + let normBias; + if (norm === void 0 || norm.mean === void 0) { + normMean = [255, 255, 255, 255]; + } else { + if (typeof norm.mean === "number") { + normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; + } else { + normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 0]; + if (norm.mean[3] !== void 0) { + normMean[3] = norm.mean[3]; } - - let padded_attention_mask; - if (padding) { - const [num_frames, num_channels] = features.dims; - const data = /** @type {Float32Array} */(features.data); - - const pad_size = num_frames % pad_to_multiple_of; - if (pad_size > 0) { - const padded_data = new Float32Array(num_channels * (num_frames + pad_size)); - padded_data.set(data) - padded_data.fill(this.config.padding_value, data.length) - - const numPaddedFrames = num_frames + pad_size; - features = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - features.type, - padded_data, - [numPaddedFrames, num_channels], - ) - - if (return_attention_mask) { - padded_attention_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - 'int64', - new BigInt64Array(numPaddedFrames), - [1, numPaddedFrames], - ); - /** @type {BigInt64Array} */ (padded_attention_mask.data).fill(1n, 0, num_frames); - } - } + } + } + if (norm === void 0 || norm.bias === void 0) { + normBias = [0, 0, 0, 0]; + } else { + if (typeof norm.bias === "number") { + normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; + } else { + normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0]; + if (norm.bias[3] !== void 0) { + normBias[3] = norm.bias[3]; } - - const [num_frames, num_channels] = features.dims; - - const stride = this.config.stride; - const remainder = num_frames % stride; - if (remainder !== 0) { - throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`) + } + } + const stride = height * width; + let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; + if (inputformat === "RGBA") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + aTensorPointer = stride * 3; + } else if (inputformat === "RGB") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + } else if (inputformat === "RBG") { + rTensorPointer = 0; + bTensorPointer = stride; + gTensorPointer = stride * 2; + } + for (let i = 0; i < height; i++) { + for (let j2 = 0; j2 < width; j2++) { + const R = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; + const G2 = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; + const B = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; + const A = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; + pixels2DContext.fillStyle = "rgba(" + R + "," + G2 + "," + B + "," + A + ")"; + pixels2DContext.fillRect(j2, i, 1, 1); + } + } + if ("toDataURL" in canvas) { + return canvas.toDataURL(); + } else { + throw new Error("toDataURL is not supported"); + } + } else { + throw new Error("Can not access image data"); + } +}; +var tensorToImageData = (tensor, options) => { + const pixels2DContext = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : new OffscreenCanvas(1, 1).getContext("2d"); + let image; + if (pixels2DContext != null) { + let width; + let height; + let channels; + if (options?.tensorLayout !== void 0 && options.tensorLayout === "NHWC") { + width = tensor.dims[2]; + height = tensor.dims[1]; + channels = tensor.dims[3]; + } else { + width = tensor.dims[3]; + height = tensor.dims[2]; + channels = tensor.dims[1]; + } + const inputformat = options !== void 0 ? options.format !== void 0 ? options.format : "RGB" : "RGB"; + const norm = options?.norm; + let normMean; + let normBias; + if (norm === void 0 || norm.mean === void 0) { + normMean = [255, 255, 255, 255]; + } else { + if (typeof norm.mean === "number") { + normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; + } else { + normMean = [norm.mean[0], norm.mean[1], norm.mean[2], 255]; + if (norm.mean[3] !== void 0) { + normMean[3] = norm.mean[3]; } - - const input_features = features.view( - 1, - Math.floor(num_frames / stride), - num_channels * stride, - ); - - const result = { input_features } - - if (return_attention_mask) { - const reshapedNumFrames = input_features.dims[1]; - - const attention_mask_data = new BigInt64Array(reshapedNumFrames); - - if (padded_attention_mask) { - const padded_attention_mask_data = padded_attention_mask.data; - for (let i = 1, j = 0; i < num_frames; i += stride, ++j) { - attention_mask_data[j] = padded_attention_mask_data[i]; - } - } else { - attention_mask_data.fill(1n); - } - result.attention_mask = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - 'int64', - attention_mask_data, - [1, reshapedNumFrames], - ); + } + } + if (norm === void 0 || norm.bias === void 0) { + normBias = [0, 0, 0, 0]; + } else { + if (typeof norm.bias === "number") { + normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; + } else { + normBias = [norm.bias[0], norm.bias[1], norm.bias[2], 0]; + if (norm.bias[3] !== void 0) { + normBias[3] = norm.bias[3]; } - - return result; + } } -} - - -/***/ }), - -/***/ "./src/models/segformer/image_processing_segformer.js": -/*!************************************************************!*\ - !*** ./src/models/segformer/image_processing_segformer.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SegformerFeatureExtractor: () => (/* binding */ SegformerFeatureExtractor), -/* harmony export */ SegformerImageProcessor: () => (/* binding */ SegformerImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - - -class SegformerImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** @type {typeof post_process_semantic_segmentation} */ - post_process_semantic_segmentation(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_semantic_segmentation)(...args); + const stride = height * width; + if (options !== void 0) { + if (options.format !== void 0 && channels === 4 && options.format !== "RGBA" || channels === 3 && options.format !== "RGB" && options.format !== "BGR") { + throw new Error("Tensor format doesn't match input tensor dims"); + } } -} -class SegformerFeatureExtractor extends SegformerImageProcessor { } - - -/***/ }), - -/***/ "./src/models/siglip/image_processing_siglip.js": -/*!******************************************************!*\ - !*** ./src/models/siglip/image_processing_siglip.js ***! - \******************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SiglipImageProcessor: () => (/* binding */ SiglipImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class SiglipImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } - - -/***/ }), - -/***/ "./src/models/smolvlm/image_processing_smolvlm.js": -/*!********************************************************!*\ - !*** ./src/models/smolvlm/image_processing_smolvlm.js ***! - \********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SmolVLMImageProcessor: () => (/* reexport safe */ _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__.Idefics3ImageProcessor) -/* harmony export */ }); -/* harmony import */ var _idefics3_image_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../idefics3/image_processing_idefics3.js */ "./src/models/idefics3/image_processing_idefics3.js"); - - - - -/***/ }), - -/***/ "./src/models/smolvlm/processing_smolvlm.js": -/*!**************************************************!*\ - !*** ./src/models/smolvlm/processing_smolvlm.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SmolVLMProcessor: () => (/* reexport safe */ _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__.Idefics3Processor) -/* harmony export */ }); -/* harmony import */ var _idefics3_processing_idefics3_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../idefics3/processing_idefics3.js */ "./src/models/idefics3/processing_idefics3.js"); - - - - -/***/ }), - -/***/ "./src/models/snac/feature_extraction_snac.js": -/*!****************************************************!*\ - !*** ./src/models/snac/feature_extraction_snac.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SnacFeatureExtractor: () => (/* binding */ SnacFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../dac/feature_extraction_dac.js */ "./src/models/dac/feature_extraction_dac.js"); - - -class SnacFeatureExtractor extends _dac_feature_extraction_dac_js__WEBPACK_IMPORTED_MODULE_0__.DacFeatureExtractor { } - - -/***/ }), - -/***/ "./src/models/speecht5/feature_extraction_speecht5.js": -/*!************************************************************!*\ - !*** ./src/models/speecht5/feature_extraction_speecht5.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SpeechT5FeatureExtractor: () => (/* binding */ SpeechT5FeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); - - - -class SpeechT5FeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { } - - -/***/ }), - -/***/ "./src/models/speecht5/processing_speecht5.js": -/*!****************************************************!*\ - !*** ./src/models/speecht5/processing_speecht5.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ SpeechT5Processor: () => (/* binding */ SpeechT5Processor) -/* harmony export */ }); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); - - - - -class SpeechT5Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_0__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoFeatureExtractor - - /** - * Calls the feature_extractor function with the given input. - * @param {any} input The input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(input) { - return await this.feature_extractor(input) + const step = 4; + let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; + let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; + if (inputformat === "RGBA") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + aTensorPointer = stride * 3; + } else if (inputformat === "RGB") { + rTensorPointer = 0; + gTensorPointer = stride; + bTensorPointer = stride * 2; + } else if (inputformat === "RBG") { + rTensorPointer = 0; + bTensorPointer = stride; + gTensorPointer = stride * 2; + } + image = pixels2DContext.createImageData(width, height); + for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) { + image.data[rImagePointer] = (tensor.data[rTensorPointer++] - normBias[0]) * normMean[0]; + image.data[gImagePointer] = (tensor.data[gTensorPointer++] - normBias[1]) * normMean[1]; + image.data[bImagePointer] = (tensor.data[bTensorPointer++] - normBias[2]) * normMean[2]; + image.data[aImagePointer] = aTensorPointer === -1 ? 255 : (tensor.data[aTensorPointer++] - normBias[3]) * normMean[3]; } -} - - -/***/ }), - -/***/ "./src/models/swin2sr/image_processing_swin2sr.js": -/*!********************************************************!*\ - !*** ./src/models/swin2sr/image_processing_swin2sr.js ***! - \********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Swin2SRImageProcessor: () => (/* binding */ Swin2SRImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class Swin2SRImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - pad_image(pixelData, imgDims, padSize, options = {}) { - // NOTE: In this case, `padSize` represents the size of the sliding window for the local attention. - // In other words, the image is padded so that its width and height are multiples of `padSize`. - const [imageHeight, imageWidth, imageChannels] = imgDims; + } else { + throw new Error("Can not access image data"); + } + return image; +}; - return super.pad_image(pixelData, imgDims, { - // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already - // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19). - // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`. - width: imageWidth + (padSize - imageWidth % padSize) % padSize, - height: imageHeight + (padSize - imageHeight % padSize) % padSize, - }, { - mode: 'symmetric', - center: false, - constant_values: -1, - ...options, - }) +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/tensor-factory-impl.js +var bufferToTensor = (buffer, options) => { + if (buffer === void 0) { + throw new Error("Image buffer must be defined"); + } + if (options.height === void 0 || options.width === void 0) { + throw new Error("Image height and width must be defined"); + } + if (options.tensorLayout === "NHWC") { + throw new Error("NHWC Tensor layout is not supported yet"); + } + const { height, width } = options; + const norm = options.norm ?? { mean: 255, bias: 0 }; + let normMean; + let normBias; + if (typeof norm.mean === "number") { + normMean = [norm.mean, norm.mean, norm.mean, norm.mean]; + } else { + normMean = [norm.mean[0], norm.mean[1], norm.mean[2], norm.mean[3] ?? 255]; + } + if (typeof norm.bias === "number") { + normBias = [norm.bias, norm.bias, norm.bias, norm.bias]; + } else { + normBias = [norm.bias[0], norm.bias[1], norm.bias[2], norm.bias[3] ?? 0]; + } + const inputformat = options.format !== void 0 ? options.format : "RGBA"; + const outputformat = options.tensorFormat !== void 0 ? options.tensorFormat !== void 0 ? options.tensorFormat : "RGB" : "RGB"; + const stride = height * width; + const float32Data = outputformat === "RGBA" ? new Float32Array(stride * 4) : new Float32Array(stride * 3); + let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; + let rTensorPointer = 0, gTensorPointer = stride, bTensorPointer = stride * 2, aTensorPointer = -1; + if (inputformat === "RGB") { + step = 3; + rImagePointer = 0; + gImagePointer = 1; + bImagePointer = 2; + aImagePointer = -1; + } + if (outputformat === "RGBA") { + aTensorPointer = stride * 3; + } else if (outputformat === "RBG") { + rTensorPointer = 0; + bTensorPointer = stride; + gTensorPointer = stride * 2; + } else if (outputformat === "BGR") { + bTensorPointer = 0; + gTensorPointer = stride; + rTensorPointer = stride * 2; + } + for (let i = 0; i < stride; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) { + float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias[0]) / normMean[0]; + float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias[1]) / normMean[1]; + float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias[2]) / normMean[2]; + if (aTensorPointer !== -1 && aImagePointer !== -1) { + float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias[3]) / normMean[3]; } -} - -/***/ }), - -/***/ "./src/models/ultravox/processing_ultravox.js": -/*!****************************************************!*\ - !*** ./src/models/ultravox/processing_ultravox.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ UltravoxProcessor: () => (/* binding */ UltravoxProcessor) -/* harmony export */ }); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); - - - - -/** - * Represents a UltravoxProcessor that extracts features from an audio input. - */ -class UltravoxProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor - static uses_processor_config = true; - - /** - * @param {string} text The text input to process. - * @param {Float32Array} audio The audio input to process. - */ - async _call(text, audio = null, kwargs = {}) { - // TODO: Support batched inputs - if (Array.isArray(text)) { - throw new Error("Batched inputs are not supported yet."); - } - - let audio_inputs = {}; - if (audio) { - const audio_len = audio.length; - const { input_features } = await this.feature_extractor(audio, { - ...kwargs, - max_length: audio_len, - }); - const nb_encoder_frames = Math.round(audio_len / this.config.encoder_ds_factor + 1e-4); - - // NOTE: The python version appears to have an off-by-one error. - const audio_embed_frames = 1 + Math.ceil(nb_encoder_frames / this.config.stack_factor); - audio_inputs["audio_token_len"] = [audio_embed_frames]; - audio_inputs["audio_values"] = input_features; - - const image_token = this.config.audio_placeholder; - if (!text.includes(image_token)) { - throw new Error(`The input text does not contain the image token ${image_token}.`); - } - text = text.replaceAll(image_token, image_token.repeat(audio_embed_frames)); - } - - const text_inputs = this.tokenizer(text, { - add_special_tokens: false, - ...kwargs, - }); - - return { - ...text_inputs, - ...audio_inputs, + } + const outputTensor = outputformat === "RGBA" ? new Tensor("float32", float32Data, [1, 4, height, width]) : new Tensor("float32", float32Data, [1, 3, height, width]); + return outputTensor; +}; +var tensorFromImage = async (image, options) => { + const isHTMLImageEle = typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement; + const isImageDataEle = typeof ImageData !== "undefined" && image instanceof ImageData; + const isImageBitmap = typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap; + const isString = typeof image === "string"; + let data; + let bufferToTensorOptions = options ?? {}; + const createCanvas = () => { + if (typeof document !== "undefined") { + return document.createElement("canvas"); + } else if (typeof OffscreenCanvas !== "undefined") { + return new OffscreenCanvas(1, 1); + } else { + throw new Error("Canvas is not supported"); + } + }; + const createCanvasContext = (canvas) => { + if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { + return canvas.getContext("2d"); + } else if (canvas instanceof OffscreenCanvas) { + return canvas.getContext("2d"); + } else { + return null; + } + }; + if (isHTMLImageEle) { + const canvas = createCanvas(); + canvas.width = image.width; + canvas.height = image.height; + const pixels2DContext = createCanvasContext(canvas); + if (pixels2DContext != null) { + let height = image.height; + let width = image.width; + if (options !== void 0 && options.resizedHeight !== void 0 && options.resizedWidth !== void 0) { + height = options.resizedHeight; + width = options.resizedWidth; + } + if (options !== void 0) { + bufferToTensorOptions = options; + if (options.tensorFormat !== void 0) { + throw new Error("Image input config format must be RGBA for HTMLImageElement"); + } else { + bufferToTensorOptions.tensorFormat = "RGBA"; } + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + } else { + bufferToTensorOptions.tensorFormat = "RGBA"; + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + } + pixels2DContext.drawImage(image, 0, 0); + data = pixels2DContext.getImageData(0, 0, width, height).data; + } else { + throw new Error("Can not access image data"); + } + } else if (isImageDataEle) { + let height; + let width; + if (options !== void 0 && options.resizedWidth !== void 0 && options.resizedHeight !== void 0) { + height = options.resizedHeight; + width = options.resizedWidth; + } else { + height = image.height; + width = image.width; + } + if (options !== void 0) { + bufferToTensorOptions = options; + } + bufferToTensorOptions.format = "RGBA"; + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + if (options !== void 0) { + const tempCanvas = createCanvas(); + tempCanvas.width = width; + tempCanvas.height = height; + const pixels2DContext = createCanvasContext(tempCanvas); + if (pixels2DContext != null) { + pixels2DContext.putImageData(image, 0, 0); + data = pixels2DContext.getImageData(0, 0, width, height).data; + } else { + throw new Error("Can not access image data"); + } + } else { + data = image.data; } -} - - -/***/ }), - -/***/ "./src/models/vit/image_processing_vit.js": -/*!************************************************!*\ - !*** ./src/models/vit/image_processing_vit.js ***! - \************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ViTFeatureExtractor: () => (/* binding */ ViTFeatureExtractor), -/* harmony export */ ViTImageProcessor: () => (/* binding */ ViTImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class ViTImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { } -class ViTFeatureExtractor extends ViTImageProcessor { } - - - -/***/ }), - -/***/ "./src/models/vitmatte/image_processing_vitmatte.js": -/*!**********************************************************!*\ - !*** ./src/models/vitmatte/image_processing_vitmatte.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ VitMatteImageProcessor: () => (/* binding */ VitMatteImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - + } else if (isImageBitmap) { + if (options === void 0) { + throw new Error("Please provide image config with format for Imagebitmap"); + } + const canvas = createCanvas(); + canvas.width = image.width; + canvas.height = image.height; + const pixels2DContext = createCanvasContext(canvas); + if (pixels2DContext != null) { + const height = image.height; + const width = image.width; + pixels2DContext.drawImage(image, 0, 0, width, height); + data = pixels2DContext.getImageData(0, 0, width, height).data; + bufferToTensorOptions.height = height; + bufferToTensorOptions.width = width; + return bufferToTensor(data, bufferToTensorOptions); + } else { + throw new Error("Can not access image data"); + } + } else if (isString) { + return new Promise((resolve, reject) => { + const canvas = createCanvas(); + const context = createCanvasContext(canvas); + if (!image || !context) { + return reject(); + } + const newImage = new Image(); + newImage.crossOrigin = "Anonymous"; + newImage.src = image; + newImage.onload = () => { + canvas.width = newImage.width; + canvas.height = newImage.height; + context.drawImage(newImage, 0, 0, canvas.width, canvas.height); + const img = context.getImageData(0, 0, canvas.width, canvas.height); + bufferToTensorOptions.height = canvas.height; + bufferToTensorOptions.width = canvas.width; + resolve(bufferToTensor(img.data, bufferToTensorOptions)); + }; + }); + } else { + throw new Error("Input data provided is not supported - aborted tensor creation"); + } + if (data !== void 0) { + return bufferToTensor(data, bufferToTensorOptions); + } else { + throw new Error("Input data provided is not supported - aborted tensor creation"); + } +}; +var tensorFromTexture = (texture, options) => { + const { width, height, download, dispose } = options; + const dims = [1, height, width, 4]; + return new Tensor({ location: "texture", type: "float32", texture, dims, download, dispose }); +}; +var tensorFromGpuBuffer = (gpuBuffer, options) => { + const { dataType, dims, download, dispose } = options; + return new Tensor({ location: "gpu-buffer", type: dataType ?? "float32", gpuBuffer, dims, download, dispose }); +}; +var tensorFromMLTensor = (mlTensor, options) => { + const { dataType, dims, download, dispose } = options; + return new Tensor({ location: "ml-tensor", type: dataType ?? "float32", mlTensor, dims, download, dispose }); +}; +var tensorFromPinnedBuffer = (type, buffer, dims) => new Tensor({ location: "cpu-pinned", type, data: buffer, dims: dims ?? [buffer.length] }); + +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/tensor-impl-type-mapping.js +var NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = /* @__PURE__ */ new Map([ + ["float32", Float32Array], + ["uint8", Uint8Array], + ["int8", Int8Array], + ["uint16", Uint16Array], + ["int16", Int16Array], + ["int32", Int32Array], + ["bool", Uint8Array], + ["float64", Float64Array], + ["uint32", Uint32Array], + ["int4", Uint8Array], + ["uint4", Uint8Array] +]); +var NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = /* @__PURE__ */ new Map([ + [Float32Array, "float32"], + [Uint8Array, "uint8"], + [Int8Array, "int8"], + [Uint16Array, "uint16"], + [Int16Array, "int16"], + [Int32Array, "int32"], + [Float64Array, "float64"], + [Uint32Array, "uint32"] +]); +var isTypedArrayChecked = false; +var checkTypedArray = () => { + if (!isTypedArrayChecked) { + isTypedArrayChecked = true; + const isBigInt64ArrayAvailable = typeof BigInt64Array !== "undefined" && BigInt64Array.from; + const isBigUint64ArrayAvailable = typeof BigUint64Array !== "undefined" && BigUint64Array.from; + const Float16Array2 = globalThis.Float16Array; + const isFloat16ArrayAvailable = typeof Float16Array2 !== "undefined" && Float16Array2.from; + if (isBigInt64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64", BigInt64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, "int64"); + } + if (isBigUint64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64", BigUint64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, "uint64"); + } + if (isFloat16ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Float16Array2); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(Float16Array2, "float16"); + } else { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16", Uint16Array); + } + } +}; +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/tensor-utils-impl.js +var calculateSize = (dims) => { + let size = 1; + for (let i = 0; i < dims.length; i++) { + const dim = dims[i]; + if (typeof dim !== "number" || !Number.isSafeInteger(dim)) { + throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`); + } + if (dim < 0) { + throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`); + } + size *= dim; + } + return size; +}; +var tensorReshape = (tensor, dims) => { + switch (tensor.location) { + case "cpu": + return new Tensor(tensor.type, tensor.data, dims); + case "cpu-pinned": + return new Tensor({ + location: "cpu-pinned", + data: tensor.data, + type: tensor.type, + dims + }); + case "texture": + return new Tensor({ + location: "texture", + texture: tensor.texture, + type: tensor.type, + dims + }); + case "gpu-buffer": + return new Tensor({ + location: "gpu-buffer", + gpuBuffer: tensor.gpuBuffer, + type: tensor.type, + dims + }); + case "ml-tensor": + return new Tensor({ + location: "ml-tensor", + mlTensor: tensor.mlTensor, + type: tensor.type, + dims + }); + default: + throw new Error(`tensorReshape: tensor location ${tensor.location} is not supported`); + } +}; -class VitMatteImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** - * Calls the feature extraction process on an array of images, preprocesses - * each image, and concatenates the resulting features into a single Tensor. - * @param {import("../../utils/image.js").RawImage[]} images The image(s) to extract features from. - * @param {import("../../utils/image.js").RawImage[]} trimaps The trimaps(s) to extract features from. - * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. - */ - async _call(images, trimaps) { - if (!Array.isArray(images)) { - images = [images]; +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/tensor-impl.js +var Tensor = class { + /** + * implementation. + */ + constructor(arg0, arg1, arg2) { + checkTypedArray(); + let type; + let dims; + if (typeof arg0 === "object" && "location" in arg0) { + this.dataLocation = arg0.location; + type = arg0.type; + dims = arg0.dims; + switch (arg0.location) { + case "cpu-pinned": { + const expectedTypedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(type); + if (!expectedTypedArrayConstructor) { + throw new TypeError(`unsupported type "${type}" to create tensor from pinned buffer`); + } + if (!(arg0.data instanceof expectedTypedArrayConstructor)) { + throw new TypeError(`buffer should be of type ${expectedTypedArrayConstructor.name}`); + } + this.cpuData = arg0.data; + break; } - if (!Array.isArray(trimaps)) { - trimaps = [trimaps]; + case "texture": { + if (type !== "float32") { + throw new TypeError(`unsupported type "${type}" to create tensor from texture`); + } + this.gpuTextureData = arg0.texture; + this.downloader = arg0.download; + this.disposer = arg0.dispose; + break; } - - const imageData = await Promise.all(images.map(x => this.preprocess(x))); - const trimapData = await Promise.all(trimaps.map(x => this.preprocess(x, { - do_normalize: false, - do_convert_rgb: false, - do_convert_grayscale: true, - }))); - - - // Stack pixel values - const pixel_values = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.stack)(imageData.map( - // Concatenate images and trimaps - (x, i) => (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.cat)([x.pixel_values, trimapData[i].pixel_values], 0) - ), 0); - - return { - pixel_values, - - // Original sizes of images - original_sizes: imageData.map(x => x.original_size), - - // Reshaped sizes of images, before padding or cropping - reshaped_input_sizes: imageData.map(x => x.reshaped_input_size), + case "gpu-buffer": { + if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") { + throw new TypeError(`unsupported type "${type}" to create tensor from gpu buffer`); + } + this.gpuBufferData = arg0.gpuBuffer; + this.downloader = arg0.download; + this.disposer = arg0.dispose; + break; } - } -} - - -/***/ }), - -/***/ "./src/models/vitpose/image_processing_vitpose.js": -/*!********************************************************!*\ - !*** ./src/models/vitpose/image_processing_vitpose.js ***! - \********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ VitPoseImageProcessor: () => (/* binding */ VitPoseImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class VitPoseImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - - /** - * Transform the heatmaps into keypoint predictions and transform them back to the image. - * NOTE: This is a naive implementation and does not include advanced post-processing techniques, - * so the results may not be as accurate as the original implementation. - * @param {import('../../utils/tensor.js').Tensor} outputs The model outputs. - * @param {[number, number, number, number][][]} boxes List or array of bounding boxes for each image. - * Each box should be a list of 4 floats representing the bounding box coordinates in COCO format (top_left_x, top_left_y, width, height). - * @returns {{ - * bbox: [number, number, number, number], - * scores: number[], - * labels: number[], - * keypoints: [number, number][] - * }[][]} List of keypoints predictions for each image. - */ - post_process_pose_estimation(outputs, boxes, { - threshold = null, - // TODO: - // kernel_size = 11, - // target_sizes = null, - } = {}) { - // NOTE: boxes are 3D (batch_size, num_boxes, 4) - const heatmaps = outputs.tolist(); - const [batch_size, num_classes, height, width] = outputs.dims; - - const results = []; - for (let b = 0; b < batch_size; ++b) { - const heatmap = heatmaps[b]; - const bboxes = boxes[b]; - - const batch_results = []; - for (let n = 0; n < bboxes.length; ++n) { - const bbox = bboxes[n]; - - const keypoints = []; - const scores = []; - const labels = []; - - const xScale = bbox.at(-2) / width; - const yScale = bbox.at(-1) / height; - for (let c = 0; c < heatmap.length; ++c) { - let [xWeightedSum, yWeightedSum] = [0, 0]; - let sum = 0; - let score = -Infinity; - const row = heatmap[c]; - for (let y = 0; y < row.length; ++y) { - const col = row[y]; - for (let x = 0; x < col.length; ++x) { - const value = col[x]; - sum += value; - - score = Math.max(score, value); - - // Get weighted sum of positions - // TODO: Determine best offsets - xWeightedSum += (x + 0.5) * value; - yWeightedSum += (y) * value; - } - } - - // Ignore low scores, if threshold is set - if (threshold != null && score < threshold) continue; - - /** @type {[number, number]} */ - const keypoint = [ - xScale * xWeightedSum / sum, - yScale * yWeightedSum / sum, - ] - keypoints.push(keypoint); - labels.push(c); - scores.push(score); - } - batch_results.push({ - bbox, - scores, - labels, - keypoints, - }); + case "ml-tensor": { + if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint64" && type !== "int8" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") { + throw new TypeError(`unsupported type "${type}" to create tensor from MLTensor`); + } + this.mlTensorData = arg0.mlTensor; + this.downloader = arg0.download; + this.disposer = arg0.dispose; + break; + } + default: + throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`); + } + } else { + let data; + let maybeDims; + if (typeof arg0 === "string") { + type = arg0; + maybeDims = arg2; + if (arg0 === "string") { + if (!Array.isArray(arg1)) { + throw new TypeError("A string tensor's data must be a string array."); + } + data = arg1; + } else { + const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0); + if (typedArrayConstructor === void 0) { + throw new TypeError(`Unsupported tensor type: ${arg0}.`); + } + if (Array.isArray(arg1)) { + if (arg0 === "float16" && typedArrayConstructor === Uint16Array || arg0 === "uint4" || arg0 === "int4") { + throw new TypeError(`Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} as data.`); + } else if (arg0 === "uint64" || arg0 === "int64") { + data = typedArrayConstructor.from(arg1, BigInt); + } else { + data = typedArrayConstructor.from(arg1); + } + } else if (arg1 instanceof typedArrayConstructor) { + data = arg1; + } else if (arg1 instanceof Uint8ClampedArray) { + if (arg0 === "uint8") { + data = Uint8Array.from(arg1); + } else { + throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`); } - results.push(batch_results); + } else if (arg0 === "float16" && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) { + data = new globalThis.Float16Array(arg1.buffer, arg1.byteOffset, arg1.length); + } else { + throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`); + } + } + } else { + maybeDims = arg1; + if (Array.isArray(arg0)) { + if (arg0.length === 0) { + throw new TypeError("Tensor type cannot be inferred from an empty array."); + } + const firstElementType = typeof arg0[0]; + if (firstElementType === "string") { + type = "string"; + data = arg0; + } else if (firstElementType === "boolean") { + type = "bool"; + data = Uint8Array.from(arg0); + } else { + throw new TypeError(`Invalid element type of data array: ${firstElementType}.`); + } + } else if (arg0 instanceof Uint8ClampedArray) { + type = "uint8"; + data = Uint8Array.from(arg0); + } else { + const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor); + if (mappedType === void 0) { + throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`); + } + type = mappedType; + data = arg0; } - return results; + } + if (maybeDims === void 0) { + maybeDims = [data.length]; + } else if (!Array.isArray(maybeDims)) { + throw new TypeError("A tensor's dims must be a number array"); + } + dims = maybeDims; + this.cpuData = data; + this.dataLocation = "cpu"; } -} - - -/***/ }), - -/***/ "./src/models/voxtral/processing_voxtral.js": -/*!**************************************************!*\ - !*** ./src/models/voxtral/processing_voxtral.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ VoxtralProcessor: () => (/* binding */ VoxtralProcessor) -/* harmony export */ }); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - - - -const AUDIO_TOKEN = "[AUDIO]"; -const BEGIN_AUDIO_TOKEN = "[BEGIN_AUDIO]"; -const NUM_AUDIO_TOKENS = 375; - -/** - * Helper function to split audio into non-overlapping chunks of n_samples - * @param {Float32Array} audio - * @param {number} n_samples - * @returns {Float32Array[]} - */ -function chunk(audio, n_samples) { - const chunks = []; - for (let i = 0; i < audio.length; i += n_samples) { - chunks.push(audio.subarray(i, Math.min(i + n_samples, audio.length))); + const size = calculateSize(dims); + if (this.cpuData && size !== this.cpuData.length) { + if ((type === "uint4" || type === "int4") && Math.ceil(size / 2) === this.cpuData.length) { + } else { + throw new Error(`Tensor's size(${size}) does not match data length(${this.cpuData.length}).`); + } } - return chunks; -} - -/** - * Represents a VoxtralProcessor that extracts features from an audio input. - */ -class VoxtralProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor - static uses_processor_config = false; - - /** - * @param {string} text The text input to process. - * @param {Float32Array|Float32Array[]} audio The audio input(s) to process. - */ - async _call(text, audio = null, kwargs = {}) { - if (Array.isArray(text)) { - throw new Error("Batched inputs are not supported yet."); + this.type = type; + this.dims = dims; + this.size = size; + } + // #endregion + // #region factory + static async fromImage(image, options) { + return tensorFromImage(image, options); + } + static fromTexture(texture, options) { + return tensorFromTexture(texture, options); + } + static fromGpuBuffer(gpuBuffer, options) { + return tensorFromGpuBuffer(gpuBuffer, options); + } + static fromMLTensor(mlTensor, options) { + return tensorFromMLTensor(mlTensor, options); + } + static fromPinnedBuffer(type, buffer, dims) { + return tensorFromPinnedBuffer(type, buffer, dims); + } + // #endregion + // #region conversions + toDataURL(options) { + return tensorToDataURL(this, options); + } + toImageData(options) { + return tensorToImageData(this, options); + } + // #endregion + // #region properties + get data() { + this.ensureValid(); + if (!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() { + this.ensureValid(); + if (!this.gpuTextureData) { + throw new Error("The data is not stored as a WebGL texture."); + } + return this.gpuTextureData; + } + get gpuBuffer() { + this.ensureValid(); + if (!this.gpuBufferData) { + throw new Error("The data is not stored as a WebGPU buffer."); + } + return this.gpuBufferData; + } + get mlTensor() { + this.ensureValid(); + if (!this.mlTensorData) { + throw new Error("The data is not stored as a WebNN MLTensor."); + } + return this.mlTensorData; + } + // #endregion + // #region methods + async getData(releaseData) { + this.ensureValid(); + switch (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."); } - - const audio_inputs = {}; - if (audio) { - if (!text.includes(AUDIO_TOKEN)) { - throw new Error(`The input text does not contain the audio token ${AUDIO_TOKEN}.`); - } - if (!Array.isArray(audio)) { - audio = [audio]; - } - const text_parts = text.split(AUDIO_TOKEN); - const num_audio_tokens = text_parts.length - 1; - if (num_audio_tokens !== audio.length) { - throw new Error(`The number of audio inputs (${audio.length}) does not match the number of audio tokens in the text (${num_audio_tokens}).`); - } - - const n_samples = this.feature_extractor.config.n_samples; - - // Split each audio input into chunks and keep track of chunk counts - const audio_chunks = audio.map(a => chunk(a, n_samples)); - const chunk_counts = audio_chunks.map(chunks => chunks.length); - - // Flatten all chunks for feature extraction - const all_chunks = audio_chunks.flat(); - const features = (await Promise.all( - all_chunks.map((audio_input) => this.feature_extractor(audio_input, kwargs)) - )).map(x => x.input_features); - - audio_inputs["audio_values"] = features.length > 1 ? (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_3__.cat)(features, 0) : features[0]; - - // Replace text tokens for each audio input, expanding for chunk count - let new_text = text_parts[0]; - for (let i = 0; i < chunk_counts.length; ++i) { - new_text += BEGIN_AUDIO_TOKEN; - for (let j = 0; j < chunk_counts[i]; ++j) { - new_text += AUDIO_TOKEN.repeat(NUM_AUDIO_TOKENS); - } - new_text += text_parts[i + 1]; - } - text = new_text; + if (this.isDownloading) { + throw new Error("The current tensor is being downloaded."); } - - const text_inputs = this.tokenizer(text, { - add_special_tokens: false, - ...kwargs, - }); - - return { - ...text_inputs, - ...audio_inputs, + try { + this.isDownloading = true; + const data = await this.downloader(); + this.downloader = void 0; + this.dataLocation = "cpu"; + this.cpuData = data; + if (releaseData && this.disposer) { + this.disposer(); + this.disposer = void 0; + } + return data; + } finally { + this.isDownloading = false; } + } + default: + throw new Error(`cannot get data from location: ${this.dataLocation}`); } -} - - -/***/ }), - -/***/ "./src/models/wav2vec2/feature_extraction_wav2vec2.js": -/*!************************************************************!*\ - !*** ./src/models/wav2vec2/feature_extraction_wav2vec2.js ***! - \************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Wav2Vec2FeatureExtractor: () => (/* binding */ Wav2Vec2FeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); - - - -class Wav2Vec2FeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { + } + dispose() { + if (this.isDownloading) { + throw new Error("The current tensor is being downloaded."); + } + if (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"; + } + // #endregion + // #region tensor utilities + ensureValid() { + if (this.dataLocation === "none") { + throw new Error("The tensor is disposed."); + } + } + reshape(dims) { + this.ensureValid(); + if (this.downloader || this.disposer) { + throw new Error("Cannot reshape a tensor that owns GPU resource."); + } + return tensorReshape(this, dims); + } +}; - /** - * @param {Float32Array} input_values - * @returns {Float32Array} - */ - _zero_mean_unit_var_norm(input_values) { - // TODO support batch? - const sum = input_values.reduce((a, b) => a + b, 0); - const mean = sum / input_values.length; - const variance = input_values.reduce((a, b) => a + (b - mean) ** 2, 0) / input_values.length; - return input_values.map(x => (x - mean) / Math.sqrt(variance + 1e-7)); +// ../../node_modules/.pnpm/onnxruntime-common@1.30.0/node_modules/onnxruntime-common/dist/esm/tensor.js +var Tensor2 = Tensor; + +// src/backends/onnx.js +var DEVICE_TO_EXECUTION_PROVIDER_MAPPING = Object.freeze({ + auto: null, + // Auto-detect based on device and environment + gpu: null, + // Auto-detect GPU + cpu: "cpu", + // CPU + wasm: "wasm", + // WebAssembly + webgpu: "webgpu", + // WebGPU + cuda: "cuda", + // CUDA + dml: "dml", + // DirectML + coreml: "coreml", + // CoreML + webnn: { name: "webnn", deviceType: "cpu" }, + // WebNN (default) + "webnn-npu": { name: "webnn", deviceType: "npu" }, + // WebNN NPU + "webnn-gpu": { name: "webnn", deviceType: "gpu" }, + // WebNN GPU + "webnn-cpu": { name: "webnn", deviceType: "cpu" } + // WebNN CPU +}); +function getOnnxLogSeverityLevel(logLevel2) { + if (logLevel2 <= LogLevel.DEBUG) { + return 0; + } else if (logLevel2 <= LogLevel.INFO) { + return 2; + } else if (logLevel2 <= LogLevel.WARNING) { + return 3; + } else if (logLevel2 <= LogLevel.ERROR) { + return 3; + } else { + return 4; + } +} +var ONNX_LOG_LEVEL_NAMES = { + 0: "verbose", + 1: "info", + 2: "warning", + 3: "error", + 4: "fatal" +}; +var supportedDevices = []; +var defaultDevices; +var ONNX; +var ORT_SYMBOL = /* @__PURE__ */ Symbol.for("onnxruntime"); +if (ORT_SYMBOL in globalThis) { + ONNX = globalThis[ORT_SYMBOL]; +} else if (apis.IS_NODE_ENV) { + ONNX = onnx_node_default; + switch (process.platform) { + case "win32": + supportedDevices.push("dml"); + break; + case "linux": + if (process.arch === "x64") { + supportedDevices.push("cuda"); + } + break; + case "darwin": + supportedDevices.push("coreml"); + break; + } + supportedDevices.push("webgpu"); + supportedDevices.push("cpu"); + defaultDevices = ["cpu"]; +} else { + ONNX = ort_webgpu_bundle_min_exports; + if (apis.IS_WEBNN_AVAILABLE) { + supportedDevices.push("webnn-npu", "webnn-gpu", "webnn-cpu", "webnn"); + } + if (apis.IS_WEBGPU_AVAILABLE) { + supportedDevices.push("webgpu"); + } + supportedDevices.push("wasm"); + defaultDevices = ["wasm"]; +} +function getSupportedDevices() { + return [...supportedDevices]; +} +var InferenceSession2 = ONNX.InferenceSession; +function deviceToExecutionProviders(device = null) { + if (!device) return defaultDevices; + switch (device) { + case "auto": + return supportedDevices; + case "gpu": + return supportedDevices.filter((x) => ["webgpu", "cuda", "dml", "webnn-gpu"].includes(x)); + } + if (supportedDevices.includes(device)) { + return [DEVICE_TO_EXECUTION_PROVIDER_MAPPING[device] ?? device]; + } + throw new Error(`Unsupported device: "${device}". Should be one of: ${supportedDevices.join(", ")}.`); +} +var webInitChain = Promise.resolve(); +var wasmLoadPromise = null; +async function ensureWasmLoaded() { + if (wasmLoadPromise) { + return wasmLoadPromise; + } + const shouldUseWasmCache = env.useWasmCache && typeof ONNX_ENV?.wasm?.wasmPaths === "object" && ONNX_ENV?.wasm?.wasmPaths?.wasm && ONNX_ENV?.wasm?.wasmPaths?.mjs; + if (!shouldUseWasmCache) { + if (apis.IS_DENO_WEB_RUNTIME) { + throw new Error( + "env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override." + ); } - - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. - */ - async _call(audio) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'Wav2Vec2FeatureExtractor'); - - if (audio instanceof Float64Array) { - audio = new Float32Array(audio); + wasmLoadPromise = Promise.resolve(); + return wasmLoadPromise; + } + wasmLoadPromise = (async () => { + const urls = ( + /** @type {{ wasm: string, mjs: string }} */ + ONNX_ENV.wasm.wasmPaths + ); + let wasmBinaryLoaded = false; + await Promise.all([ + // Load and cache the WASM binary + urls.wasm && !isBlobURL(urls.wasm) ? (async () => { + try { + const wasmBinary = await loadWasmBinary(toAbsoluteURL(urls.wasm)); + if (wasmBinary) { + ONNX_ENV.wasm.wasmBinary = wasmBinary; + wasmBinaryLoaded = true; + } + } catch (err) { + logger.warn("Failed to pre-load WASM binary:", err); } - - let input_values = audio; - - // zero-mean and unit-variance normalization - if (this.config.do_normalize) { - input_values = this._zero_mean_unit_var_norm(input_values); + })() : Promise.resolve(), + // Load and cache the WASM factory as a blob URL + urls.mjs && !isBlobURL(urls.mjs) ? (async () => { + try { + const wasmFactoryBlob = await loadWasmFactory(toAbsoluteURL(urls.mjs)); + if (wasmFactoryBlob) { + ONNX_ENV.wasm.wasmPaths.mjs = wasmFactoryBlob; + } + } catch (err) { + logger.warn("Failed to pre-load WASM factory:", err); } - - // TODO: allow user to pass in attention mask - const shape = [1, input_values.length]; - return { - input_values: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('float32', input_values, shape), - attention_mask: new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor('int64', new BigInt64Array(input_values.length).fill(1n), shape) - }; + })() : Promise.resolve() + ]); + if (!wasmBinaryLoaded) { + ONNX_ENV.wasm.wasmPaths.mjs = urls.mjs; } + })(); + return wasmLoadPromise; } - - -/***/ }), - -/***/ "./src/models/wav2vec2/processing_wav2vec2.js": -/*!****************************************************!*\ - !*** ./src/models/wav2vec2/processing_wav2vec2.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Wav2Vec2Processor: () => (/* binding */ Wav2Vec2Processor) -/* harmony export */ }); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); - - - - -class Wav2Vec2Processor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoFeatureExtractor - - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio) - } +async function createInferenceSession(buffer_or_path, session_options, session_config) { + await ensureWasmLoaded(); + const logSeverityLevel = getOnnxLogSeverityLevel(env.logLevel ?? LogLevel.WARNING); + const load = () => InferenceSession2.create(buffer_or_path, { + // Set default log severity level, but allow overriding through session options + logSeverityLevel, + ...session_options + }); + const session = await (apis.IS_WEB_ENV ? webInitChain = webInitChain.then(load) : load()); + session.config = session_config; + return session; } - - -/***/ }), - -/***/ "./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js": -/*!********************************************************************!*\ - !*** ./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js ***! - \********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Wav2Vec2ProcessorWithLM: () => (/* binding */ Wav2Vec2ProcessorWithLM) -/* harmony export */ }); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); - - - - -class Wav2Vec2ProcessorWithLM extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_1__.AutoFeatureExtractor - - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio) +var webInferenceChain = Promise.resolve(); +async function runInferenceSession(session, ortFeed) { + const run = () => session.run(ortFeed); + return apis.IS_WEB_ENV ? webInferenceChain = webInferenceChain.then(run) : run(); +} +function isONNXTensor(x) { + return x instanceof ONNX.Tensor; +} +var ONNX_ENV = ONNX?.env; +function isONNXProxy() { + return ONNX_ENV?.wasm?.proxy; +} +if (ONNX_ENV) { + let setLogLevel = function(logLevel2) { + const severityLevel = getOnnxLogSeverityLevel(logLevel2); + ONNX_ENV.logLevel = ONNX_LOG_LEVEL_NAMES[severityLevel]; + }; + if (ONNX_ENV.wasm) { + if ( + // @ts-ignore Cannot find name 'ServiceWorkerGlobalScope'.ts(2304) + !(typeof ServiceWorkerGlobalScope !== "undefined" && self instanceof ServiceWorkerGlobalScope) && ONNX_ENV.versions?.web && !ONNX_ENV.wasm.wasmPaths + ) { + const wasmPathPrefix = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ONNX_ENV.versions.web}/dist/`; + let wasmPathSuffix = ".asyncify"; + if (apis.IS_SAFARI_BELOW_26 && !apis.IS_WEBGPU_AVAILABLE) { + wasmPathSuffix = ""; + } + ONNX_ENV.wasm.wasmPaths = { + mjs: `${wasmPathPrefix}ort-wasm-simd-threaded${wasmPathSuffix}.mjs`, + wasm: `${wasmPathPrefix}ort-wasm-simd-threaded${wasmPathSuffix}.wasm` + }; } + ONNX_ENV.wasm.proxy = false; + } + if (ONNX_ENV.webgpu) { + ONNX_ENV.webgpu.powerPreference = "high-performance"; + } + setLogLevel(env.logLevel ?? LogLevel.WARNING); + env.backends.onnx = { + ...ONNX_ENV, + setLogLevel, + getSupportedDevices + }; } - -/***/ }), - -/***/ "./src/models/wespeaker/feature_extraction_wespeaker.js": -/*!**************************************************************!*\ - !*** ./src/models/wespeaker/feature_extraction_wespeaker.js ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ WeSpeakerFeatureExtractor: () => (/* binding */ WeSpeakerFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); - - - - - -class WeSpeakerFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - - constructor(config) { - super(config); - - const sampling_rate = this.config.sampling_rate; - const mel_filters = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - 257, // num_frequency_bins - this.config.num_mel_bins, // num_mel_filters - 20, // min_frequency - Math.floor(sampling_rate / 2), // max_frequency - sampling_rate, // sampling_rate - null, // norm - "kaldi", // mel_scale - true, // triangularize_in_mel_space - ); - this.mel_filters = mel_filters; - - this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(400, 'hamming', { - periodic: false, - }) - this.min_num_frames = this.config.min_num_frames; +// src/ops/registry.js +var wrap = async (session_bytes, session_options, names) => { + const session = await createInferenceSession(new Uint8Array(session_bytes), session_options); + return ( + /** @type {any} */ + (async (inputs) => { + const proxied = isONNXProxy(); + const ortFeed = Object.fromEntries( + Object.entries(inputs).map(([k, v]) => [k, (proxied ? v.clone() : v).ort_tensor]) + ); + const outputs = await runInferenceSession(session, ortFeed); + if (Array.isArray(names)) { + return names.map((n) => new Tensor3(outputs[n])); + } else { + return new Tensor3(outputs[ + /** @type {string} */ + names + ]); + } + }) + ); +}; +var TensorOpRegistry = class { + static session_options = { + // TODO: Allow for multiple execution providers + // executionProviders: ['webgpu'], + }; + static get nearest_interpolate_4d() { + if (!this._nearest_interpolate_4d) { + this._nearest_interpolate_4d = wrap( + [ + 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" + ); } - - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - async _extract_fbank_features(waveform) { - // Kaldi compliance: 16-bit signed integers - // 32768 == 2 ** 15 - waveform = waveform.map((/** @type {number} */ x) => x * 32768) - - return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( - waveform, - this.window, // window - 400, // frame_length - 160, // hop_length - { - fft_length: 512, - power: 2.0, - center: false, - preemphasis: 0.97, - mel_filters: this.mel_filters, - log_mel: 'log', - mel_floor: 1.192092955078125e-07, - remove_dc_offset: true, - - // Custom - transpose: true, - min_num_frames: this.min_num_frames, - } - ) + return this._nearest_interpolate_4d; + } + static get bilinear_interpolate_4d() { + if (!this._bilinear_interpolate_4d) { + this._bilinear_interpolate_4d = wrap( + [ + 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" + ); + } + return this._bilinear_interpolate_4d; + } + static get bicubic_interpolate_4d() { + if (!this._bicubic_interpolate_4d) { + this._bicubic_interpolate_4d = wrap( + [ + 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" + ); + } + return this._bicubic_interpolate_4d; + } + static get matmul() { + if (!this._matmul) { + this._matmul = wrap( + [ + 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" + ); + } + return this._matmul; + } + static get stft() { + if (!this._stft) { + this._stft = wrap( + [ + 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" + ); + } + return this._stft; + } + static get rfft() { + if (!this._rfft) { + this._rfft = wrap( + [ + 8, + 9, + 58, + 93, + 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, + 19, + 10, + 1, + 120, + 18, + 14, + 10, + 12, + 8, + 1, + 18, + 8, + 10, + 0, + 10, + 0, + 10, + 2, + 8, + 1, + 90, + 11, + 10, + 1, + 97, + 18, + 6, + 10, + 4, + 8, + 7, + 18, + 0, + 98, + 19, + 10, + 1, + 121, + 18, + 14, + 10, + 12, + 8, + 1, + 18, + 8, + 10, + 0, + 10, + 0, + 10, + 2, + 8, + 2, + 66, + 2, + 16, + 20 + ], + this.session_options, + "y" + ); + } + return this._rfft; + } + static get top_k() { + if (!this._top_k) { + this._top_k = wrap( + [ + 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, + [ + /* Values */ + "v", + /* Indices */ + "i" + ] + ); } + return this._top_k; + } + static get slice() { + if (!this._slice) { + this._slice = wrap( + [ + 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" + ); + } + return this._slice; + } +}; +// src/utils/devices.js +var DEVICE_TYPES = Object.freeze({ + auto: "auto", + // Auto-detect based on device and environment + gpu: "gpu", + // Auto-detect GPU + cpu: "cpu", + // CPU + wasm: "wasm", + // WebAssembly + webgpu: "webgpu", + // WebGPU + cuda: "cuda", + // CUDA + dml: "dml", + // DirectML + coreml: "coreml", + // CoreML + webnn: "webnn", + // WebNN (default) + "webnn-npu": "webnn-npu", + // WebNN NPU + "webnn-gpu": "webnn-gpu", + // WebNN GPU + "webnn-cpu": "webnn-cpu" + // WebNN CPU +}); +var DEFAULT_DEVICE = apis.IS_NODE_ENV ? "cpu" : "wasm"; +function selectDevice(deviceConfig, fileName, { warn } = {}) { + if (!deviceConfig) return DEFAULT_DEVICE; + if (typeof deviceConfig === "string") return deviceConfig; + if (deviceConfig.hasOwnProperty(fileName)) return deviceConfig[fileName]; + if (warn) { + warn(`device not specified for "${fileName}". Using the default device (${DEFAULT_DEVICE}).`); + } + return DEFAULT_DEVICE; +} - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'WeSpeakerFeatureExtractor'); - - const features = (await this._extract_fbank_features(audio)).unsqueeze_(0); - - if (this.config.fbank_centering_span === null) { - // center features with global average - const meanData = /** @type {Float32Array} */ (features.mean(1).data); - const featuresData = /** @type {Float32Array} */(features.data); - const [batch_size, num_frames, feature_size] = features.dims; - - for (let i = 0; i < batch_size; ++i) { - const offset1 = i * num_frames * feature_size; - const offset2 = i * feature_size; - for (let j = 0; j < num_frames; ++j) { - const offset3 = offset1 + j * feature_size; - for (let k = 0; k < feature_size; ++k) { - featuresData[offset3 + k] -= meanData[offset2 + k]; - } - } - } +// src/utils/dtypes.js +var isWebGpuFp16Supported = /* @__PURE__ */ (function() { + let cachedResult; + return async function() { + if (cachedResult === void 0) { + if (!apis.IS_WEBGPU_AVAILABLE) { + cachedResult = false; + } else { + try { + const adapter = await navigator.gpu.requestAdapter(); + cachedResult = adapter.features.has("shader-f16"); + } catch (e) { + cachedResult = false; } - - return { - input_features: features - }; + } + } + return cachedResult; + }; +})(); +var DATA_TYPES = Object.freeze({ + auto: "auto", + // Auto-detect based on environment + fp32: "fp32", + fp16: "fp16", + q8: "q8", + int8: "int8", + uint8: "uint8", + q4: "q4", + bnb4: "bnb4", + q4f16: "q4f16", + // fp16 model with 4-bit block weight quantization + q2: "q2", + q2f16: "q2f16", + // fp16 model with 2-bit block weight quantization + q1: "q1", + q1f16: "q1f16" + // fp16 model with 1-bit block weight quantization +}); +var DEFAULT_DEVICE_DTYPE = DATA_TYPES.fp32; +var DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({ + // NOTE: If not specified, will default to fp32 + [DEVICE_TYPES.wasm]: DATA_TYPES.q8 +}); +var DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({ + [DATA_TYPES.fp32]: "", + [DATA_TYPES.fp16]: "_fp16", + [DATA_TYPES.int8]: "_int8", + [DATA_TYPES.uint8]: "_uint8", + [DATA_TYPES.q8]: "_quantized", + [DATA_TYPES.q4]: "_q4", + [DATA_TYPES.q2]: "_q2", + [DATA_TYPES.q1]: "_q1", + [DATA_TYPES.q4f16]: "_q4f16", + [DATA_TYPES.q2f16]: "_q2f16", + [DATA_TYPES.q1f16]: "_q1f16", + [DATA_TYPES.bnb4]: "_bnb4" +}); +function selectDtype(dtype, fileName, selectedDevice, { configDtype = null, warn } = {}) { + let resolved; + let needsWarn = false; + if (dtype && typeof dtype !== "string") { + if (dtype.hasOwnProperty(fileName)) { + resolved = dtype[fileName]; + } else { + resolved = null; + needsWarn = true; + } + } else { + resolved = /** @type {string|null|undefined} */ + dtype; + } + let result; + if (resolved === DATA_TYPES.auto) { + if (configDtype) { + const fallback = typeof configDtype === "string" ? configDtype : configDtype?.[fileName]; + if (fallback && fallback !== DATA_TYPES.auto && DATA_TYPES.hasOwnProperty(fallback)) { + return ( + /** @type {DataType} */ + fallback + ); + } } + result = DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? DEFAULT_DEVICE_DTYPE; + } else if (resolved && DATA_TYPES.hasOwnProperty(resolved)) { + result = /** @type {DataType} */ + resolved; + } else { + result = DEFAULT_DEVICE_DTYPE_MAPPING[selectedDevice] ?? DEFAULT_DEVICE_DTYPE; + } + if (needsWarn && warn) { + warn( + `dtype not specified for "${fileName}". Using the default dtype (${result}) for this device (${selectedDevice}).` + ); + } + return result; } +var DataTypeMap = Object.freeze({ + float32: Float32Array, + // @ts-ignore ts(2552) Limited availability of Float16Array across browsers: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array + float16: typeof Float16Array !== "undefined" ? Float16Array : Uint16Array, + float64: Float64Array, + string: Array, + // string[] + int8: Int8Array, + uint8: Uint8Array, + int16: Int16Array, + uint16: Uint16Array, + int32: Int32Array, + uint32: Uint32Array, + int64: BigInt64Array, + uint64: BigUint64Array, + bool: Uint8Array, + uint4: Uint8Array, + int4: Int8Array +}); - -/***/ }), - -/***/ "./src/models/whisper/common_whisper.js": -/*!**********************************************!*\ - !*** ./src/models/whisper/common_whisper.js ***! - \**********************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ WHISPER_LANGUAGE_MAPPING: () => (/* binding */ WHISPER_LANGUAGE_MAPPING), -/* harmony export */ WHISPER_TO_LANGUAGE_CODE_MAPPING: () => (/* binding */ WHISPER_TO_LANGUAGE_CODE_MAPPING), -/* harmony export */ whisper_language_to_code: () => (/* binding */ whisper_language_to_code) -/* harmony export */ }); - - -const WHISPER_LANGUAGES = [ - ["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"], -] - -// @ts-ignore -const WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES); -// @ts-ignore -const WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([ - ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]), - ...[ - ["burmese", "my"], - ["valencian", "ca"], - ["flemish", "nl"], - ["haitian", "ht"], - ["letzeburgesch", "lb"], - ["pushto", "ps"], - ["panjabi", "pa"], - ["moldavian", "ro"], - ["moldovan", "ro"], - ["sinhalese", "si"], - ["castilian", "es"], - ] -]); - -/** - * @param {string} language The language name or code - * @returns {string} The language code - */ -function whisper_language_to_code(language) { - language = language.toLowerCase(); - - // Map to code from user-friendly name (e.g., "english" -> "en") - let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language); - - if (language_code === undefined) { - // User provided something that is not a language name - - // Perhaps the user passed the special token itself - const language_special_token = language.match(/^<\|([a-z]{2})\|>$/); - if (language_special_token) { - language = language_special_token[1]; - } - - if (WHISPER_LANGUAGE_MAPPING.has(language)) { - // User provided the language code directly (e.g., "en") - language_code = language; - - } else { - // User provided something that is not a language code or name - const is_language_code = language.length === 2; - const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values(); - - throw new Error(`Language "${language}" is not supported. Must be one of: ${JSON.stringify(Array.from(langs))}`); +// src/utils/tensor.js +var Tensor3 = class _Tensor { + /** + * Dimensions of the tensor. + * @type {number[]} + */ + get dims() { + return this.ort_tensor.dims; + } + set dims(value) { + this.ort_tensor.dims = value; + } + /** + * Type of the tensor. + * @type {DataType} + */ + get type() { + return this.ort_tensor.type; + } + /** + * The data stored in the tensor. + * @type {DataArray} + */ + get data() { + return this.ort_tensor.data; + } + /** + * The number of elements in the tensor. + * @type {number} + */ + get size() { + return this.ort_tensor.size; + } + /** + * The location of the tensor data. + * @type {string} + */ + get location() { + return this.ort_tensor.location; + } + ort_tensor; + /** + * Create a new Tensor, either from raw data or by wrapping an `onnxruntime` tensor: + * - `new Tensor(dataType, data, dims)`, e.g. `new Tensor('float32', new Float32Array([1, 2, 3]), [3])`. + * - `new Tensor(ortTensor)`. + * + * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args + */ + constructor(...args) { + if (isONNXTensor(args[0])) { + this.ort_tensor = /** @type {ONNXTensor} */ + args[0]; + } else { + this.ort_tensor = new Tensor2( + /** @type {DataType} */ + args[0], + // @ts-expect-error ts(2769) Type 'number' is not assignable to type 'bigint'. + /** @type {Exclude} */ + args[1], + args[2] + ); + } + return new Proxy(this, { + get: (obj, key) => { + if (typeof key === "string") { + let index = Number(key); + if (Number.isInteger(index)) { + return obj._getitem(index); + } } + return obj[key]; + }, + set: (obj, key, value) => { + return obj[key] = value; + } + }); + } + /** + * Releases the underlying ONNX Runtime tensor (e.g., GPU buffers). Do not use the tensor afterwards. + */ + dispose() { + this.ort_tensor.dispose(); + } + /** + * Returns an iterator object for iterating over the tensor data in row-major order. + * If the tensor has more than one dimension, the iterator will yield subarrays. + * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. + */ + *[Symbol.iterator]() { + const [iterLength, ...iterDims] = this.dims; + if (iterDims.length > 0) { + const iterSize = iterDims.reduce((a, b) => a * b); + for (let i = 0; i < iterLength; ++i) { + yield this._subarray(i, iterSize, iterDims); + } + } else { + yield* this.data; } - return language_code; -} - - -/***/ }), - -/***/ "./src/models/whisper/feature_extraction_whisper.js": -/*!**********************************************************!*\ - !*** ./src/models/whisper/feature_extraction_whisper.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ WhisperFeatureExtractor: () => (/* binding */ WhisperFeatureExtractor) -/* harmony export */ }); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils/audio.js */ "./src/utils/audio.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils/maths.js */ "./src/utils/maths.js"); - - - - - -class WhisperFeatureExtractor extends _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.FeatureExtractor { - - constructor(config) { - super(config); - - // Prefer given `mel_filters` from preprocessor_config.json, or calculate them if they don't exist. - this.config.mel_filters ??= (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.mel_filter_bank)( - Math.floor(1 + this.config.n_fft / 2), // num_frequency_bins - this.config.feature_size, // num_mel_filters - 0.0, // min_frequency - 8000.0, // max_frequency - this.config.sampling_rate, // sampling_rate - "slaney", // norm - "slaney", // mel_scale - ); - - this.window = (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.window_function)(this.config.n_fft, 'hann'); + } + /** + * Index into a Tensor object. + * @param {number} index The index to access. + * @returns {Tensor} The data at the specified index. + * @private + */ + _getitem(index) { + const [iterLength, ...iterDims] = this.dims; + index = safeIndex(index, iterLength); + if (iterDims.length > 0) { + const iterSize = iterDims.reduce((a, b) => a * b); + return this._subarray(index, iterSize, iterDims); + } else { + return new _Tensor(this.type, [this.data[index]], iterDims); + } + } + /** + * @param {number} index + * @param {number} iterSize + * @param {any} iterDims + * @returns {Tensor} + */ + _subarray(index, iterSize, iterDims) { + const o1 = index * iterSize; + const o2 = (index + 1) * iterSize; + const data = "subarray" in this.data ? this.data.subarray(o1, o2) : this.data.slice(o1, o2); + return new _Tensor(this.type, data, iterDims); + } + /** + * Returns the value of this tensor as a standard JavaScript Number. This only works + * for tensors with one element. For other cases, see `Tensor.tolist()`. + * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. + * @throws {Error} If the tensor has more than one element. + */ + item() { + const this_data = this.data; + if (this_data.length !== 1) { + throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`); + } + return this_data[0]; + } + /** + * Convert tensor data to a n-dimensional JS list + * @returns {any[]} + */ + tolist() { + return reshape(this.data, this.dims); + } + /** + * Return a new Tensor with the sigmoid function applied to each element. + * @returns {Tensor} The tensor with the sigmoid function applied. + */ + sigmoid() { + return this.clone().sigmoid_(); + } + /** + * Applies the sigmoid function to the tensor in place. + * @returns {Tensor} Returns `this`. + */ + sigmoid_() { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = 1 / (1 + Math.exp(-this_data[i])); + } + return this; + } + /** + * Return a new Tensor with a callback function applied to each element. + * @param {Function} callback - The function to apply to each element. It should take three arguments: + * the current element, its index, and the tensor's data array. + * @returns {Tensor} A new Tensor with the callback function applied to each element. + */ + map(callback) { + return this.clone().map_(callback); + } + /** + * Apply a callback function to each element of the tensor in place. + * @param {Function} callback - The function to apply to each element. It should take three arguments: + * the current element, its index, and the tensor's data array. + * @returns {Tensor} Returns `this`. + */ + map_(callback) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = callback(this_data[i], i, this_data); + } + return this; + } + /** + * Return a new Tensor with every element multiplied by a constant. + * @param {number} val The value to multiply by. + * @returns {Tensor} The new tensor. + */ + mul(val) { + return this.clone().mul_(val); + } + /** + * Multiply the tensor by a constant in place. + * @param {number} val The value to multiply by. + * @returns {Tensor} Returns `this`. + */ + mul_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] *= val; + } + return this; + } + /** + * Return a new Tensor with every element divided by a constant. + * @param {number} val The value to divide by. + * @returns {Tensor} The new tensor. + */ + div(val) { + return this.clone().div_(val); + } + /** + * Divide the tensor by a constant in place. + * @param {number} val The value to divide by. + * @returns {Tensor} Returns `this`. + */ + div_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] /= val; + } + return this; + } + /** + * Return a new Tensor with every element added by a constant. + * @param {number} val The value to add by. + * @returns {Tensor} The new tensor. + */ + add(val) { + return this.clone().add_(val); + } + /** + * Add the tensor by a constant in place. + * @param {number} val The value to add by. + * @returns {Tensor} Returns `this`. + */ + add_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] += val; + } + return this; + } + /** + * Return a new Tensor with every element subtracted by a constant. + * @param {number} val The value to subtract by. + * @returns {Tensor} The new tensor. + */ + sub(val) { + return this.clone().sub_(val); + } + /** + * Subtract the tensor by a constant in place. + * @param {number} val The value to subtract by. + * @returns {Tensor} Returns `this`. + */ + sub_(val) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] -= val; } - - /** - * Computes the log-Mel spectrogram of the provided audio waveform. - * @param {Float32Array|Float64Array} waveform The audio waveform to process. - * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. - */ - async _extract_fbank_features(waveform) { - const features = await (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_2__.spectrogram)( - waveform, - this.window, // window - this.config.n_fft, // frame_length - this.config.hop_length, // hop_length - { - power: 2.0, - mel_filters: this.config.mel_filters, - log_mel: 'log10', - - // Custom - max_num_frames: Math.min( - Math.floor(waveform.length / this.config.hop_length), - this.config.nb_max_frames, // 3000 - ) - } - ) - - const data = features.data; - const maxValue = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)(/** @type {Float32Array} */(data))[0]; - - for (let i = 0; i < data.length; ++i) { - data[i] = (Math.max(data[i], maxValue - 8.0) + 4.0) / 4.0; - } - - return features; + return this; + } + /** + * Return a new Tensor with the element-wise remainder of division by a constant. + * Uses Python-style modulo signs (e.g. `-1 mod 2 = 1`) while preserving the tensor's dtype. + * Negative divisors are unsupported for unsigned and boolean tensors. + * This operation does not implement PyTorch's dtype promotion or scalar casting rules. + * @param {number|bigint} val The divisor. + * @returns {Tensor} The new tensor. + */ + remainder(val) { + return this.clone().remainder_(val); + } + /** + * In-place version of @see {@link Tensor.remainder} + * @param {number|bigint} val The divisor. + * @returns {Tensor} Returns `this`. + */ + remainder_(val) { + const this_data = this.data; + const is_bigint = this_data instanceof BigInt64Array || this_data instanceof BigUint64Array; + const divisor = ( + /** @type {any} */ + is_bigint ? BigInt(val) : Number(val) + ); + if ((divisor === 0 || divisor === 0n) && (this.type.includes("int") || this.type === "bool")) { + throw new RangeError("Division by zero"); } - - /** - * Asynchronously extracts features from a given audio using the provided configuration. - * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. - * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. - */ - async _call(audio, { - max_length = null, - } = {}) { - (0,_base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_0__.validate_audio_inputs)(audio, 'WhisperFeatureExtractor'); - - let waveform; - const length = max_length ?? this.config.n_samples; - if (audio.length > length) { - if (audio.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`." - ); - } - waveform = audio.slice(0, length); - } else { - // pad with zeros - waveform = new Float32Array(length); - waveform.set(audio); - } - - const features = await this._extract_fbank_features(waveform); - - return { - input_features: features.unsqueeze_(0) - }; + if (divisor < 0 && (this.type.startsWith("uint") || this.type === "bool")) { + throw new RangeError("Negative divisors are not supported for unsigned or boolean tensors"); } -} - - -/***/ }), - -/***/ "./src/models/whisper/generation_whisper.js": -/*!**************************************************!*\ - !*** ./src/models/whisper/generation_whisper.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ WhisperGenerationConfig: () => (/* binding */ WhisperGenerationConfig) -/* harmony export */ }); -/* harmony import */ var _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../generation/configuration_utils.js */ "./src/generation/configuration_utils.js"); - - -class WhisperGenerationConfig extends _generation_configuration_utils_js__WEBPACK_IMPORTED_MODULE_0__.GenerationConfig { - - /** - * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. - * @type {boolean} - */ - return_timestamps = null; - - /** - * Whether to return token-level timestamps - * with the text. This can be used with or without the `return_timestamps` option. To get word-level - * timestamps, use the tokenizer to group the tokens into words. - * @type {boolean} - */ - return_token_timestamps = null; - - /** - * The number of audio frames available in this chunk. This is only used generating word-level timestamps. - * @type {number} - */ - num_frames = null; - - /** - * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that - * select the cross-attention heads that are highly correlated to word-level timing. - * @type {[number, number][]} - */ - alignment_heads = null; - - /** - * Task to use for generation, either "translate" or "transcribe". - * @type {string} - */ - task = null; - - /** - * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. - * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary. - * @type {string} - */ - language = null; - - /** - * The id of the `"<|notimestamps|>"` token. - * @type {number} - */ - no_timestamps_token_id = null; - - /** - * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is - * provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for - * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words - * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value. - * @type {number[]} - */ - prompt_ids = null; - - /** - * Whether the model is multilingual or not. - * @type {boolean} - */ - is_multilingual = null; - - /** - * (Optional) A mapping from language tokens to their corresponding IDs. - * Only required if the model is multilingual. - * @type {Record|null} - */ - lang_to_id = null; - - /** - * (Optional) A mapping from task tokens to their corresponding IDs. - * @type {Record|null} - */ - task_to_id = null; - - /** - * Used to set the maximum value of the initial timestamp. This is used to prevent the model from - * predicting timestamps that are too far in the future. - * @type {number} - */ - max_initial_timestamp_index = 1; -} - -/** - * @typedef {import('../../generation/parameters.js').GenerationFunctionParameters & {generation_config: WhisperGenerationConfig} & WhisperGenerationConfig} WhisperGenerationFunctionParameters - */ - - -/***/ }), - -/***/ "./src/models/whisper/processing_whisper.js": -/*!**************************************************!*\ - !*** ./src/models/whisper/processing_whisper.js ***! - \**************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ WhisperProcessor: () => (/* binding */ WhisperProcessor) -/* harmony export */ }); -/* harmony import */ var _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../base/processing_utils.js */ "./src/base/processing_utils.js"); - - - - -/** - * Represents a WhisperProcessor that extracts features from an audio input. - */ -class WhisperProcessor extends _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_2__.Processor { - static tokenizer_class = _tokenizers_js__WEBPACK_IMPORTED_MODULE_1__.AutoTokenizer - static feature_extractor_class = _auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_0__.AutoFeatureExtractor - - /** - * Calls the feature_extractor function with the given audio input. - * @param {any} audio The audio input to extract features from. - * @returns {Promise} A Promise that resolves with the extracted features. - */ - async _call(audio) { - return await this.feature_extractor(audio); + for (let i = 0; i < this_data.length; ++i) { + const remainder = this_data[i] % divisor; + const needs_shift = remainder < 0 && divisor > 0 || remainder > 0 && divisor < 0; + this_data[i] = needs_shift ? remainder + divisor : remainder; } -} - - - -/***/ }), - -/***/ "./src/models/yolos/image_processing_yolos.js": -/*!****************************************************!*\ - !*** ./src/models/yolos/image_processing_yolos.js ***! - \****************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ YolosFeatureExtractor: () => (/* binding */ YolosFeatureExtractor), -/* harmony export */ YolosImageProcessor: () => (/* binding */ YolosImageProcessor) -/* harmony export */ }); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); - - -class YolosImageProcessor extends _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.ImageProcessor { - /** @type {typeof post_process_object_detection} */ - post_process_object_detection(...args) { - return (0,_base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_0__.post_process_object_detection)(...args); + return this; + } + /** + * Creates a deep copy of the current Tensor. + * @returns {Tensor} A new Tensor with the same type, data, and dimensions as the original. + */ + clone() { + return new _Tensor(this.type, this.data.slice(), this.dims.slice()); + } + /** + * Performs a slice operation on the Tensor along specified dimensions. + * + * Consider a Tensor that has a dimension of [4, 7]: + * ``` + * [ 1, 2, 3, 4, 5, 6, 7] + * [ 8, 9, 10, 11, 12, 13, 14] + * [15, 16, 17, 18, 19, 20, 21] + * [22, 23, 24, 25, 26, 27, 28] + * ``` + * We can slice against the two dims of row and column, for instance in this + * case we can start at the second element, and return to the second last, + * like this: + * ``` + * tensor.slice([1, -1], [1, -1]); + * ``` + * which would return: + * ``` + * [ 9, 10, 11, 12, 13 ] + * [ 16, 17, 18, 19, 20 ] + * ``` + * + * @param {...(number|number[]|null)} slices The slice specifications for each dimension. + * - If a number is given, then a single element is selected. + * - If an array of two numbers is given, then a range of elements [start, end (exclusive)] is selected. + * - If null is given, then the entire dimension is selected. + * @returns {Tensor} A new Tensor containing the selected elements. + * @throws {Error} If the slice input is invalid. + */ + slice(...slices) { + const newTensorDims = []; + const newOffsets = []; + for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) { + let slice3 = slices[sliceIndex]; + if (slice3 === null || slice3 === void 0) { + newOffsets.push([0, this.dims[sliceIndex]]); + newTensorDims.push(this.dims[sliceIndex]); + } else if (typeof slice3 === "number") { + slice3 = safeIndex(slice3, this.dims[sliceIndex], sliceIndex); + newOffsets.push([slice3, slice3 + 1]); + } else if (Array.isArray(slice3) && slice3.length === 2) { + let [start, end] = slice3; + start = start === null ? 0 : safeIndex(start, this.dims[sliceIndex], sliceIndex, false); + end = end === null ? this.dims[sliceIndex] : safeIndex(end, this.dims[sliceIndex], sliceIndex, false); + if (start > end) { + throw new Error(`Invalid slice: ${slice3}`); + } + const offsets = [Math.max(start, 0), Math.min(end, this.dims[sliceIndex])]; + newOffsets.push(offsets); + newTensorDims.push(offsets[1] - offsets[0]); + } else { + throw new Error(`Invalid slice: ${slice3}`); + } } -} -class YolosFeatureExtractor extends YolosImageProcessor { } - - -/***/ }), - -/***/ "./src/ops/registry.js": -/*!*****************************!*\ - !*** ./src/ops/registry.js ***! - \*****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ TensorOpRegistry: () => (/* binding */ TensorOpRegistry) -/* harmony export */ }); -/* harmony import */ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../backends/onnx.js */ "./src/backends/onnx.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); - - - - -const IS_WEB_ENV = _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_BROWSER_ENV || _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV; -/** - * Asynchronously creates a wrapper function for running an ONNX inference session. - * - * @param {number[]} session_bytes The session data in bytes. - * @param {import('onnxruntime-common').InferenceSession.SessionOptions} session_options The options for the ONNX session. - * @template {string | [string] | string[]} T - * @param {T} names The name(s) of the output tensor(s). - * - * @returns {Promise): Promise>} - * The wrapper function for running the ONNX inference session. - */ -const wrap = async (session_bytes, session_options, names) => { - const session = await (0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__.createInferenceSession)( - new Uint8Array(session_bytes), session_options, - ); - - /** @type {Promise} */ - let chain = Promise.resolve(); - - return /** @type {any} */(async (/** @type {Record} */ inputs) => { - const proxied = (0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_0__.isONNXProxy)(); - const ortFeed = Object.fromEntries(Object.entries(inputs).map(([k, v]) => [k, (proxied ? v.clone() : v).ort_tensor])); - - // When running in-browser via WASM, we need to chain calls to session.run to avoid "Error: Session already started" - const outputs = await (chain = IS_WEB_ENV ? chain.then(() => session.run(ortFeed)) : session.run(ortFeed)); - - if (Array.isArray(names)) { - return names.map((n) => new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(outputs[n])); - } else { - return new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_1__.Tensor(outputs[/** @type {string} */(names)]); - } - }) -} - -// In-memory registry of initialized ONNX operators -class TensorOpRegistry { - static session_options = { - // TODO: Allow for multiple execution providers - // executionProviders: ['webgpu'], - }; - - static get nearest_interpolate_4d() { - if (!this._nearest_interpolate_4d) { - this._nearest_interpolate_4d = wrap( - [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', - ); - } - return this._nearest_interpolate_4d; + const newDims = newOffsets.map(([start, end]) => end - start); + const newBufferSize = newDims.reduce((a, b) => a * b); + const this_data = this.data; + const data = new this_data.constructor(newBufferSize); + const stride = this.stride(); + let isContiguous = true; + for (let i = 1; i < newDims.length; ++i) { + if (newOffsets[i][0] !== 0 || newOffsets[i][1] !== this.dims[i]) { + isContiguous = false; + break; + } } - static get bilinear_interpolate_4d() { - if (!this._bilinear_interpolate_4d) { - this._bilinear_interpolate_4d = wrap( - [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', - ); + if (isContiguous) { + const start = newOffsets[0][0] * stride[0]; + const end = newOffsets[0][1] * stride[0]; + if (ArrayBuffer.isView(this_data)) { + data.set(this_data.subarray(start, end)); + } else if (Array.isArray(this_data)) { + const slicedData = this_data.slice(start, end); + for (let i = 0; i < slicedData.length; ++i) { + data[i] = slicedData[i]; } - return this._bilinear_interpolate_4d; + } else { + throw new Error("Unsupported data type for slicing"); + } + } else { + for (let i = 0; i < newBufferSize; ++i) { + let originalIndex = 0; + for (let j2 = newDims.length - 1, num = i; j2 >= 0; --j2) { + const size = newDims[j2]; + originalIndex += (num % size + newOffsets[j2][0]) * stride[j2]; + num = Math.floor(num / size); + } + data[i] = this_data[originalIndex]; + } } - - static get bicubic_interpolate_4d() { - if (!this._bicubic_interpolate_4d) { - this._bicubic_interpolate_4d = wrap( - [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', - ); - } - return this._bicubic_interpolate_4d; + return new _Tensor(this.type, data, newTensorDims); + } + /** + * Return a permuted version of this Tensor, according to the provided dimensions. + * @param {...number} dims Dimensions to permute. + * @returns {Tensor} The permuted tensor. + */ + permute(...dims) { + return permute(this, dims); + } + // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute() + /** @type {Tensor['permute']} */ + transpose(...dims) { + return this.permute(...dims); + } + /** + * Returns the sum of each row of the input tensor in the given dimension dim. + * + * @param {number|null} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. + * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. + * @returns The summed tensor + */ + sum(dim = null, keepdim = false) { + return this.norm(1, dim, keepdim); + } + /** + * Returns the matrix norm or vector norm of a given tensor. + * @param {number|string} [p='fro'] The order of norm + * @param {number|null} [dim=null] Specifies which dimension of the tensor to calculate the norm across. + * If dim is None, the norm will be calculated across all dimensions of input. + * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. + * @returns {Tensor} The norm of the tensor. + */ + norm(p = "fro", dim = null, keepdim = false) { + if (p === "fro") { + p = 2; + } else if (typeof p === "string") { + throw Error(`Unsupported norm: ${p}`); + } + const this_data = this.data; + const is_bigint = this_data instanceof BigInt64Array || this_data instanceof BigUint64Array; + if (is_bigint && p !== 1) { + throw Error(`Expected a floating point tensor as input. Got ${this.type}`); + } + let fn2, zero; + if (is_bigint) { + fn2 = (a, b) => a + b; + zero = 0n; + } else { + fn2 = (a, b) => a + b ** p; + zero = 0; } - - static get matmul() { - if (!this._matmul) { - this._matmul = wrap( - [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', - ); - } - return this._matmul; + if (dim === null) { + let val = this_data.reduce(fn2, zero); + if (p !== 1) { + val = val ** (1 / p); + } + return new _Tensor(this.type, [val], []); } - - static get stft() { - if (!this._stft) { - this._stft = wrap( - [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', - ) - } - return this._stft; + const [type, result, resultDims] = reduce_helper(fn2, this, dim, keepdim); + if (p !== 1) { + for (let i = 0; i < result.length; ++i) { + result[i] = result[i] ** (1 / p); + } } - - static get rfft() { - if (!this._rfft) { - this._rfft = wrap( - [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', - ) - } - return this._rfft; + return new _Tensor(type, result, resultDims); + } + /** + * Performs `L_p` normalization of inputs over specified dimension. Operates in place. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} `this` for operation chaining. + */ + normalize_(p = 2, dim = 1) { + dim = safeIndex(dim, this.dims.length); + const norm = this.norm(p, dim, true); + const this_data = this.data; + const norm_data = norm.data; + for (let i = 0; i < this_data.length; ++i) { + let resultIndex = 0; + for (let j2 = this.dims.length - 1, num = i, resultMultiplier = 1; j2 >= 0; --j2) { + const size = this.dims[j2]; + if (j2 !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= this.dims[j2]; + } + num = Math.floor(num / size); + } + this_data[i] /= norm_data[resultIndex]; } - - static get top_k() { - if (!this._top_k) { - this._top_k = wrap( - [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, - [ /* Values */ 'v', /* Indices */ 'i'] - ) + return this; + } + /** + * Performs `L_p` normalization of inputs over specified dimension. + * @param {number} [p=2] The exponent value in the norm formulation + * @param {number} [dim=1] The dimension to reduce + * @returns {Tensor} The normalized tensor. + */ + normalize(p = 2, dim = 1) { + return this.clone().normalize_(p, dim); + } + /** + * Compute and return the stride of this tensor. + * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. + * @returns {number[]} The stride of this tensor. + */ + stride() { + return dimsToStride(this.dims); + } + /** + * Returns a tensor with all specified dimensions of input of size 1 removed. + * + * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. + * If you would like a copy, use `tensor.clone()` before squeezing. + * + * @param {number|number[]|null} [dim=null] If given, the input will be squeezed only in the specified dimensions. + * @returns {Tensor} The squeezed tensor + */ + squeeze(dim = null) { + return new _Tensor(this.type, this.data, calc_squeeze_dims(this.dims, dim)); + } + /** + * In-place version of @see {@link Tensor.squeeze} + * @param {number|number[]|null} [dim=null] If given, the input will be squeezed only in the specified dimensions. + * @returns {Tensor} `this`, with the specified dimensions of size 1 removed. + */ + squeeze_(dim = null) { + this.dims = calc_squeeze_dims(this.dims, dim); + return this; + } + /** + * Returns a new tensor with a dimension of size one inserted at the specified position. + * + * NOTE: The returned tensor shares the same underlying data with this tensor. + * + * @param {number} dim The index at which to insert the singleton dimension + * @returns {Tensor} The unsqueezed tensor + */ + unsqueeze(dim) { + return new _Tensor(this.type, this.data, calc_unsqueeze_dims(this.dims, dim)); + } + /** + * In-place version of @see {@link Tensor.unsqueeze} + * @type {Tensor['unsqueeze']} + */ + unsqueeze_(dim) { + this.dims = calc_unsqueeze_dims(this.dims, dim); + return this; + } + /** + * In-place version of @see {@link Tensor.flatten} + * @param {number} [start_dim=0] the first dim to flatten + * @param {number} [end_dim=-1] the last dim to flatten + * @returns {Tensor} `this`, flattened along the specified dimensions. + */ + flatten_(start_dim = 0, end_dim = -1) { + end_dim = (end_dim + this.dims.length) % this.dims.length; + let dimsToKeepBefore = this.dims.slice(0, start_dim); + let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1); + let dimsToKeepAfter = this.dims.slice(end_dim + 1); + this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter]; + return this; + } + /** + * Flattens input by reshaping it into a one-dimensional tensor. + * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` + * and ending with `end_dim` are flattened. The order of elements in input is unchanged. + * @param {number} start_dim the first dim to flatten + * @param {number} end_dim the last dim to flatten + * @returns {Tensor} The flattened tensor. + */ + flatten(start_dim = 0, end_dim = -1) { + return this.clone().flatten_(start_dim, end_dim); + } + /** + * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. + * @param {...number} dims the desired size + * @returns {Tensor} The tensor with the same data but different shape + */ + view(...dims) { + let inferredIndex = -1; + for (let i = 0; i < dims.length; ++i) { + if (dims[i] === -1) { + if (inferredIndex !== -1) { + throw new Error("Only one dimension can be inferred"); } - return this._top_k; + inferredIndex = i; + } } - - static get slice() { - if (!this._slice) { - this._slice = wrap( - [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', - ) - } - return this._slice; + const this_data = this.data; + if (inferredIndex !== -1) { + const productOther = dims.reduce((product2, curr, index) => { + return index !== inferredIndex ? product2 * curr : product2; + }, 1); + dims[inferredIndex] = this_data.length / productOther; } -} - - -/***/ }), - -/***/ "./src/pipelines.js": -/*!**************************!*\ - !*** ./src/pipelines.js ***! - \**************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AudioClassificationPipeline: () => (/* binding */ AudioClassificationPipeline), -/* harmony export */ AutomaticSpeechRecognitionPipeline: () => (/* binding */ AutomaticSpeechRecognitionPipeline), -/* harmony export */ BackgroundRemovalPipeline: () => (/* binding */ BackgroundRemovalPipeline), -/* harmony export */ DepthEstimationPipeline: () => (/* binding */ DepthEstimationPipeline), -/* harmony export */ DocumentQuestionAnsweringPipeline: () => (/* binding */ DocumentQuestionAnsweringPipeline), -/* harmony export */ FeatureExtractionPipeline: () => (/* binding */ FeatureExtractionPipeline), -/* harmony export */ FillMaskPipeline: () => (/* binding */ FillMaskPipeline), -/* harmony export */ ImageClassificationPipeline: () => (/* binding */ ImageClassificationPipeline), -/* harmony export */ ImageFeatureExtractionPipeline: () => (/* binding */ ImageFeatureExtractionPipeline), -/* harmony export */ ImageSegmentationPipeline: () => (/* binding */ ImageSegmentationPipeline), -/* harmony export */ ImageToImagePipeline: () => (/* binding */ ImageToImagePipeline), -/* harmony export */ ImageToTextPipeline: () => (/* binding */ ImageToTextPipeline), -/* harmony export */ ObjectDetectionPipeline: () => (/* binding */ ObjectDetectionPipeline), -/* harmony export */ Pipeline: () => (/* binding */ Pipeline), -/* harmony export */ QuestionAnsweringPipeline: () => (/* binding */ QuestionAnsweringPipeline), -/* harmony export */ SummarizationPipeline: () => (/* binding */ SummarizationPipeline), -/* harmony export */ Text2TextGenerationPipeline: () => (/* binding */ Text2TextGenerationPipeline), -/* harmony export */ TextClassificationPipeline: () => (/* binding */ TextClassificationPipeline), -/* harmony export */ TextGenerationPipeline: () => (/* binding */ TextGenerationPipeline), -/* harmony export */ TextToAudioPipeline: () => (/* binding */ TextToAudioPipeline), -/* harmony export */ TokenClassificationPipeline: () => (/* binding */ TokenClassificationPipeline), -/* harmony export */ TranslationPipeline: () => (/* binding */ TranslationPipeline), -/* harmony export */ ZeroShotAudioClassificationPipeline: () => (/* binding */ ZeroShotAudioClassificationPipeline), -/* harmony export */ ZeroShotClassificationPipeline: () => (/* binding */ ZeroShotClassificationPipeline), -/* harmony export */ ZeroShotImageClassificationPipeline: () => (/* binding */ ZeroShotImageClassificationPipeline), -/* harmony export */ ZeroShotObjectDetectionPipeline: () => (/* binding */ ZeroShotObjectDetectionPipeline), -/* harmony export */ pipeline: () => (/* binding */ pipeline) -/* harmony export */ }); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./models.js */ "./src/models.js"); -/* harmony import */ var _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./models/auto/processing_auto.js */ "./src/models/auto/processing_auto.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/audio.js */ "./src/utils/audio.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/image.js */ "./src/utils/image.js"); -/** - * @file Pipelines provide a high-level, easy to use, API for running machine learning models. - * - * **Example:** Instantiate pipeline using the `pipeline` function. - * ```javascript - * import { pipeline } from '@huggingface/transformers'; - * - * const classifier = await pipeline('sentiment-analysis'); - * const output = await classifier('I love transformers!'); - * // [{'label': 'POSITIVE', 'score': 0.999817686}] - * ``` - * - * @module pipelines - */ - - - - - - - - - - - - - - - -/** - * @typedef {string | RawImage | URL | Blob | HTMLCanvasElement | OffscreenCanvas} ImageInput - * @typedef {ImageInput|ImageInput[]} ImagePipelineInputs - */ - -/** - * Prepare images for further tasks. - * @param {ImagePipelineInputs} images images to prepare. - * @returns {Promise} returns processed images. - * @private - */ -async function prepareImages(images) { - if (!Array.isArray(images)) { - images = [images]; + return new _Tensor(this.type, this_data, dims); + } + /** + * In-place version of @see {@link Tensor.neg} + * @returns {Tensor} `this`, with every element negated. + */ + neg_() { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = -this_data[i]; } - - // Possibly convert any non-images to images - return await Promise.all(images.map(x => _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.read(x))); -} - -/** - * @typedef {string | URL | Float32Array | Float64Array} AudioInput - * @typedef {AudioInput|AudioInput[]} AudioPipelineInputs - */ - -/** - * Prepare audios for further tasks. - * @param {AudioPipelineInputs} audios audios to prepare. - * @param {number} sampling_rate sampling rate of the audios. - * @returns {Promise} The preprocessed audio data. - * @private - */ -async function prepareAudios(audios, sampling_rate) { - if (!Array.isArray(audios)) { - audios = [audios]; + return this; + } + /** + * Returns a new tensor with the negative of the elements of this tensor. + * @returns {Tensor} the output tensor. + */ + neg() { + return this.clone().neg_(); + } + /** + * Computes input > val element-wise. + * @param {number} val The value to compare with. + * @returns {Tensor} A boolean tensor that is `true` where input is greater than other and `false` elsewhere. + */ + gt(val) { + const mask = new Uint8Array(this.data.length); + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + mask[i] = this_data[i] > val ? 1 : 0; } - - return await Promise.all(audios.map(x => { - if (typeof x === 'string' || x instanceof URL) { - return (0,_utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.read_audio)(x, sampling_rate); - } else if (x instanceof Float64Array) { - return new Float32Array(x); - } - return x; - })); -} - -/** - * @typedef {Object} BoundingBox - * @property {number} xmin The minimum x coordinate of the bounding box. - * @property {number} ymin The minimum y coordinate of the bounding box. - * @property {number} xmax The maximum x coordinate of the bounding box. - * @property {number} ymax The maximum y coordinate of the bounding box. - */ - -/** - * Helper function to convert list [xmin, xmax, ymin, ymax] into object { "xmin": xmin, ... } - * @param {number[]} box The bounding box as a list. - * @param {boolean} asInteger Whether to cast to integers. - * @returns {BoundingBox} The bounding box as an object. - * @private - */ -function get_bounding_box(box, asInteger) { - if (asInteger) { - box = box.map(x => x | 0); + return new _Tensor("bool", mask, this.dims); + } + /** + * Computes input < val element-wise. + * @param {number} val The value to compare with. + * @returns {Tensor} A boolean tensor that is `true` where input is less than other and `false` elsewhere. + */ + lt(val) { + const mask = new Uint8Array(this.data.length); + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + mask[i] = this_data[i] < val ? 1 : 0; + } + return new _Tensor("bool", mask, this.dims); + } + /** + * In-place version of @see {@link Tensor.clamp} + * @type {Tensor['clamp']} + */ + clamp_(min3, max2) { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = Math.min(Math.max(this_data[i], min3), max2); + } + return this; + } + /** + * Clamps all elements in input into the range [ min, max ] + * @param {number} min lower-bound of the range to be clamped to + * @param {number} max upper-bound of the range to be clamped to + * @returns {Tensor} the output tensor. + */ + clamp(min3, max2) { + return this.clone().clamp_(min3, max2); + } + /** + * In-place version of @see {@link Tensor.round} + */ + round_() { + const this_data = this.data; + for (let i = 0; i < this_data.length; ++i) { + this_data[i] = Math.round(this_data[i]); } - const [xmin, ymin, xmax, ymax] = box; - - return { xmin, ymin, xmax, ymax }; -} - - -/** - * @callback DisposeType Disposes the item. - * @returns {Promise} A promise that resolves when the item has been disposed. - * - * @typedef {Object} Disposable - * @property {DisposeType} dispose A promise that resolves when the pipeline has been disposed. - */ - -/** - * The Pipeline class is the class from which all pipelines inherit. - * Refer to this class for methods shared across different pipelines. - */ -class Pipeline extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_4__.Callable { - /** - * Create a new Pipeline. - * @param {Object} options An object containing the following properties: - * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. - * @param {PreTrainedModel} [options.model] The model used by the pipeline. - * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). - * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). - */ - constructor({ task, model, tokenizer = null, processor = null }) { - super(); - this.task = task; - this.model = model; - this.tokenizer = tokenizer; - this.processor = processor; + return this; + } + /** + * Rounds elements of input to the nearest integer. + * @returns {Tensor} the output tensor. + */ + round() { + return this.clone().round_(); + } + /** + * Returns the mean value of each row of this tensor in the given dimension `dim`. + * @param {number|null} [dim=null] the dimension to reduce. If `null`, the mean of all elements is computed. + * @param {boolean} [keepdim=false] whether the output tensor has `dim` retained or not. + * @returns {Tensor} A new tensor with means taken along the specified dimension. + */ + mean(dim = null, keepdim = false) { + return mean(this, dim, keepdim); + } + /** + * Returns the minimum value of each row of this tensor in the given dimension `dim`. + * @param {number|null} [dim=null] the dimension to reduce. If `null`, the minimum of all elements is computed. + * @param {boolean} [keepdim=false] whether the output tensor has `dim` retained or not. + * @returns {Tensor} A new tensor with minimum values taken along the specified dimension. + */ + min(dim = null, keepdim = false) { + if (dim === null) { + const val = min2(this.data)[0]; + return new _Tensor( + this.type, + [val], + [ + /* scalar */ + ] + ); } - - /** @type {DisposeType} */ - async dispose() { - await this.model.dispose(); - } -} - -/** - * @typedef {Object} ModelTokenizerConstructorArgs - * @property {string} task The task of the pipeline. Useful for specifying subtasks. - * @property {PreTrainedModel} model The model used by the pipeline. - * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline. - * - * @typedef {ModelTokenizerConstructorArgs} TextPipelineConstructorArgs An object used to instantiate a text-based pipeline. - */ - -/** - * @typedef {Object} ModelProcessorConstructorArgs - * @property {string} task The task of the pipeline. Useful for specifying subtasks. - * @property {PreTrainedModel} model The model used by the pipeline. - * @property {Processor} processor The processor used by the pipeline. - * - * @typedef {ModelProcessorConstructorArgs} AudioPipelineConstructorArgs An object used to instantiate an audio-based pipeline. - * @typedef {ModelProcessorConstructorArgs} ImagePipelineConstructorArgs An object used to instantiate an image-based pipeline. - */ - - -/** - * @typedef {Object} ModelTokenizerProcessorConstructorArgs - * @property {string} task The task of the pipeline. Useful for specifying subtasks. - * @property {PreTrainedModel} model The model used by the pipeline. - * @property {PreTrainedTokenizer} tokenizer The tokenizer used by the pipeline. - * @property {Processor} processor The processor used by the pipeline. - * - * @typedef {ModelTokenizerProcessorConstructorArgs} TextAudioPipelineConstructorArgs An object used to instantiate a text- and audio-based pipeline. - * @typedef {ModelTokenizerProcessorConstructorArgs} TextImagePipelineConstructorArgs An object used to instantiate a text- and image-based pipeline. - */ - -/** - * @typedef {Object} TextClassificationSingle - * @property {string} label The label predicted. - * @property {number} score The corresponding probability. - * @typedef {TextClassificationSingle[]} TextClassificationOutput - * - * @typedef {Object} TextClassificationPipelineOptions Parameters specific to text classification pipelines. - * @property {number} [top_k=1] The number of top predictions to be returned. - * - * @callback TextClassificationPipelineCallback Classify the text(s) given as inputs. - * @param {string|string[]} texts The input text(s) to be classified. - * @param {TextClassificationPipelineOptions} [options] The options to use for text classification. - * @returns {Promise} An array or object containing the predicted labels and scores. - * - * @typedef {TextPipelineConstructorArgs & TextClassificationPipelineCallback & Disposable} TextClassificationPipelineType - */ - -/** - * Text classification pipeline using any `ModelForSequenceClassification`. - * - * **Example:** Sentiment-analysis w/ `Xenova/distilbert-base-uncased-finetuned-sst-2-english`. - * ```javascript - * const classifier = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english'); - * const output = await classifier('I love transformers!'); - * // [{ label: 'POSITIVE', score: 0.999788761138916 }] - * ``` - * - * **Example:** Multilingual sentiment-analysis w/ `Xenova/bert-base-multilingual-uncased-sentiment` (and return top 5 classes). - * ```javascript - * const classifier = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment'); - * const output = await classifier('Le meilleur film de tous les temps.', { top_k: 5 }); - * // [ - * // { label: '5 stars', score: 0.9610759615898132 }, - * // { label: '4 stars', score: 0.03323351591825485 }, - * // { label: '3 stars', score: 0.0036155181005597115 }, - * // { label: '1 star', score: 0.0011325967498123646 }, - * // { label: '2 stars', score: 0.0009423971059732139 } - * // ] - * ``` - * - * **Example:** Toxic comment classification w/ `Xenova/toxic-bert` (and return all classes). - * ```javascript - * const classifier = await pipeline('text-classification', 'Xenova/toxic-bert'); - * const output = await classifier('I hate you!', { top_k: null }); - * // [ - * // { label: 'toxic', score: 0.9593140482902527 }, - * // { label: 'insult', score: 0.16187334060668945 }, - * // { label: 'obscene', score: 0.03452680632472038 }, - * // { label: 'identity_hate', score: 0.0223250575363636 }, - * // { label: 'threat', score: 0.019197041168808937 }, - * // { label: 'severe_toxic', score: 0.005651099607348442 } - * // ] - * ``` - */ -class TextClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ (Pipeline)) { - - /** - * Create a new TextClassificationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + const [type, result, resultDims] = reduce_helper((a, b) => Math.min(a, b), this, dim, keepdim, Infinity); + return new _Tensor(type, result, resultDims); + } + /** + * Returns the maximum value of each row of this tensor in the given dimension `dim`. + * @param {number|null} [dim=null] the dimension to reduce. If `null`, the maximum of all elements is computed. + * @param {boolean} [keepdim=false] whether the output tensor has `dim` retained or not. + * @returns {Tensor} A new tensor with maximum values taken along the specified dimension. + */ + max(dim = null, keepdim = false) { + if (dim === null) { + const val = max(this.data)[0]; + return new _Tensor( + this.type, + [val], + [ + /* scalar */ + ] + ); } - - /** @type {TextClassificationPipelineCallback} */ - async _call(texts, { - top_k = 1 - } = {}) { - - // Run tokenization - const model_inputs = this.tokenizer(texts, { - padding: true, - truncation: true, - }); - - // Run model - const outputs = await this.model(model_inputs) - - // TODO: Use softmax tensor function - const function_to_apply = - // @ts-expect-error TS2339 - this.model.config.problem_type === 'multi_label_classification' - ? batch => batch.sigmoid() - : batch => new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( - 'float32', - (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(batch.data), - batch.dims, - ); // single_label_classification (default) - - // @ts-expect-error TS2339 - const id2label = this.model.config.id2label; - - const toReturn = []; - for (const batch of outputs.logits) { - const output = function_to_apply(batch); - - const scores = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(output, top_k); - - const values = scores[0].tolist(); - const indices = scores[1].tolist(); - const vals = indices.map((x, i) => ({ - label: id2label ? id2label[x] : `LABEL_${x}`, - score: values[i], - })); - if (top_k === 1) { - toReturn.push(...vals); - } else { - toReturn.push(vals); - } - } - - return Array.isArray(texts) || top_k === 1 ? /** @type {TextClassificationOutput} */ (toReturn) : /** @type {TextClassificationOutput[]} */ (toReturn)[0]; - } -} - -/** - * @typedef {Object} TokenClassificationSingle - * @property {string} word The token/word classified. This is obtained by decoding the selected tokens. - * @property {number} score The corresponding probability for `entity`. - * @property {string} entity The entity predicted for that token/word. - * @property {number} index The index of the corresponding token in the sentence. - * @property {number} [start] The index of the start of the corresponding entity in the sentence. - * @property {number} [end] The index of the end of the corresponding entity in the sentence. - * @typedef {TokenClassificationSingle[]} TokenClassificationOutput - * - * @typedef {Object} TokenClassificationPipelineOptions Parameters specific to token classification pipelines. - * @property {string[]} [ignore_labels] A list of labels to ignore. - * - * @callback TokenClassificationPipelineCallback Classify each token of the text(s) given as inputs. - * @param {string|string[]} texts One or several texts (or one list of texts) for token classification. - * @param {TokenClassificationPipelineOptions} [options] The options to use for token classification. - * @returns {Promise} The result. - * - * @typedef {TextPipelineConstructorArgs & TokenClassificationPipelineCallback & Disposable} TokenClassificationPipelineType - */ - -/** - * Named Entity Recognition pipeline using any `ModelForTokenClassification`. - * - * **Example:** Perform named entity recognition with `Xenova/bert-base-NER`. - * ```javascript - * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER'); - * const output = await classifier('My name is Sarah and I live in London'); - * // [ - * // { entity: 'B-PER', score: 0.9980202913284302, index: 4, word: 'Sarah' }, - * // { entity: 'B-LOC', score: 0.9994474053382874, index: 9, word: 'London' } - * // ] - * ``` - * - * **Example:** Perform named entity recognition with `Xenova/bert-base-NER` (and return all labels). - * ```javascript - * const classifier = await pipeline('token-classification', 'Xenova/bert-base-NER'); - * const output = await classifier('Sarah lives in the United States of America', { ignore_labels: [] }); - * // [ - * // { entity: 'B-PER', score: 0.9966587424278259, index: 1, word: 'Sarah' }, - * // { entity: 'O', score: 0.9987385869026184, index: 2, word: 'lives' }, - * // { entity: 'O', score: 0.9990072846412659, index: 3, word: 'in' }, - * // { entity: 'O', score: 0.9988298416137695, index: 4, word: 'the' }, - * // { entity: 'B-LOC', score: 0.9995510578155518, index: 5, word: 'United' }, - * // { entity: 'I-LOC', score: 0.9990395307540894, index: 6, word: 'States' }, - * // { entity: 'I-LOC', score: 0.9986724853515625, index: 7, word: 'of' }, - * // { entity: 'I-LOC', score: 0.9975294470787048, index: 8, word: 'America' } - * // ] - * ``` - */ -class TokenClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ (Pipeline)) { - - /** - * Create a new TokenClassificationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + const [type, result, resultDims] = reduce_helper((a, b) => Math.max(a, b), this, dim, keepdim, -Infinity); + return new _Tensor(type, result, resultDims); + } + /** + * Returns the index of the minimum value of all elements in this tensor. + * @param {number|null} [dim=null] the dimension to reduce. Only `null` (reduce over all elements) is currently supported. + * @param {boolean} [keepdim=false] whether the output tensor has `dim` retained or not. + * @returns {Tensor} An `int64` scalar tensor containing the index of the minimum value. + * @throws {Error} If `dim` is not `null`. + */ + argmin(dim = null, keepdim = false) { + if (dim !== null) { + throw new Error("`dim !== null` not yet implemented."); } - - /** @type {TokenClassificationPipelineCallback} */ - async _call(texts, { - ignore_labels = ['O'], - } = {}) { - - const isBatched = Array.isArray(texts); - - // Run tokenization - const model_inputs = this.tokenizer(isBatched ? texts : [texts], { - padding: true, - truncation: true, - }); - - // Run model - const outputs = await this.model(model_inputs) - - const logits = outputs.logits; - // @ts-expect-error TS2339 - const id2label = this.model.config.id2label; - - const toReturn = []; - for (let i = 0; i < logits.dims[0]; ++i) { - const ids = model_inputs.input_ids[i]; - const batch = logits[i]; - - // List of tokens that aren't ignored - const tokens = []; - for (let j = 0; j < batch.dims[0]; ++j) { - const tokenData = batch[j]; - const topScoreIndex = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.max)(tokenData.data)[1]; - - const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`; - if (ignore_labels.includes(entity)) { - // We predicted a token that should be ignored. So, we skip it. - continue; - } - - // TODO add option to keep special tokens? - const word = this.tokenizer.decode([ids[j].item()], { skip_special_tokens: true }); - if (word === '') { - // Was a special token. So, we skip it. - continue; - } - - const scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(tokenData.data); - - tokens.push({ - entity: entity, - score: scores[topScoreIndex], - index: j, - word: word, - - // TODO: Add support for start and end - // start: null, - // end: null, - }); - } - toReturn.push(tokens); - } - return isBatched ? toReturn : toReturn[0]; - } -} - -/** - * @typedef {Object} QuestionAnsweringOutput - * @property {number} score The probability associated to the answer. - * @property {number} [start] The character start index of the answer (in the tokenized version of the input). - * @property {number} [end] The character end index of the answer (in the tokenized version of the input). - * @property {string} answer The answer to the question. - * - * @typedef {Object} QuestionAnsweringPipelineOptions Parameters specific to question answering pipelines. - * @property {number} [top_k=1] The number of top answer predictions to be returned. - * - * @callback QuestionAnsweringPipelineCallback Answer the question(s) given as inputs by using the context(s). - * @param {string|string[]} question One or several question(s) (must be used in conjunction with the `context` argument). - * @param {string|string[]} context One or several context(s) associated with the question(s) (must be used in conjunction with the `question` argument). - * @param {QuestionAnsweringPipelineOptions} [options] The options to use for question answering. - * @returns {Promise} An array or object containing the predicted answers and scores. - * - * @typedef {TextPipelineConstructorArgs & QuestionAnsweringPipelineCallback & Disposable} QuestionAnsweringPipelineType - */ - -/** - * Question Answering pipeline using any `ModelForQuestionAnswering`. - * - * **Example:** Run question answering with `Xenova/distilbert-base-uncased-distilled-squad`. - * ```javascript - * const answerer = await pipeline('question-answering', 'Xenova/distilbert-base-uncased-distilled-squad'); - * const question = 'Who was Jim Henson?'; - * const context = 'Jim Henson was a nice puppet.'; - * const output = await answerer(question, context); - * // { - * // answer: "a nice puppet", - * // score: 0.5768911502526741 - * // } - * ``` - */ -class QuestionAnsweringPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ (Pipeline)) { - - /** - * Create a new QuestionAnsweringPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + const index = min2(this.data)[1]; + return new _Tensor("int64", [BigInt(index)], []); + } + /** + * Returns the index of the maximum value of all elements in this tensor. + * @param {number|null} [dim=null] the dimension to reduce. Only `null` (reduce over all elements) is currently supported. + * @param {boolean} [keepdim=false] whether the output tensor has `dim` retained or not. + * @returns {Tensor} An `int64` scalar tensor containing the index of the maximum value. + * @throws {Error} If `dim` is not `null`. + */ + argmax(dim = null, keepdim = false) { + if (dim !== null) { + throw new Error("`dim !== null` not yet implemented."); } - - /** @type {QuestionAnsweringPipelineCallback} */ - async _call(question, context, { - top_k = 1 - } = {}) { - - // Run tokenization - const inputs = this.tokenizer(question, { - text_pair: context, - padding: true, - truncation: true, - }); - - const { start_logits, end_logits } = await this.model(inputs); - const input_ids = inputs.input_ids.tolist(); - const attention_mask = inputs.attention_mask.tolist(); - - // TODO: add support for `return_special_tokens_mask` - const special_tokens = this.tokenizer.all_special_ids; - - /** @type {QuestionAnsweringOutput[]} */ - const toReturn = []; - for (let j = 0; j < start_logits.dims[0]; ++j) { - const ids = input_ids[j]; - const sepIndex = ids.findIndex(x => - // We use == to match bigint with number - // @ts-ignore - x == this.tokenizer.sep_token_id - ); - - - const valid_mask = attention_mask[j].map((y, ix) => ( - y == 1 - && ( - ix === 0 // is cls_token - || ( - ix > sepIndex - && special_tokens.findIndex(x => x == ids[ix]) === -1 // token is not a special token (special_tokens_mask == 0) - ) - ) - )); - - const start = start_logits[j].tolist(); - const end = end_logits[j].tolist(); - - // Now, we mask out values that can't be in the answer - // NOTE: We keep the cls_token unmasked (some models use it to indicate unanswerable questions) - for (let i = 1; i < start.length; ++i) { - if ( - attention_mask[j] == 0 // is part of padding - || i <= sepIndex // is before the sep_token - || special_tokens.findIndex(x => x == ids[i]) !== -1 // Is a special token - ) { - // Make sure non-context indexes in the tensor cannot contribute to the softmax - start[i] = -Infinity; - end[i] = -Infinity; - } - } - - // Normalize logits and spans to retrieve the answer - const start_scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(start).map((x, i) => [x, i]); - const end_scores = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(end).map((x, i) => [x, i]); - - // Mask CLS - start_scores[0][0] = 0; - end_scores[0][0] = 0; - - // Generate all valid spans and select best ones - const options = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_5__.product)(start_scores, end_scores) - .filter(x => x[0][1] <= x[1][1]) - .map(x => [x[0][1], x[1][1], x[0][0] * x[1][0]]) - .sort((a, b) => b[2] - a[2]); - - for (let k = 0; k < Math.min(options.length, top_k); ++k) { - const [start, end, score] = options[k]; - - const answer_tokens = ids.slice(start, end + 1) - - const answer = this.tokenizer.decode(answer_tokens, { - skip_special_tokens: true, - }); - - // TODO add start and end? - // NOTE: HF returns character index - toReturn.push({ - answer, score - }); - } - } - - // Mimic HF's return type based on top_k - return (top_k === 1) ? toReturn[0] : toReturn; - } -} - - -/** - * @typedef {Object} FillMaskSingle - * @property {string} sequence The corresponding input with the mask token prediction. - * @property {number} score The corresponding probability. - * @property {number} token The predicted token id (to replace the masked one). - * @property {string} token_str The predicted token (to replace the masked one). - * @typedef {FillMaskSingle[]} FillMaskOutput - * - * @typedef {Object} FillMaskPipelineOptions Parameters specific to fill mask pipelines. - * @property {number} [top_k=5] When passed, overrides the number of predictions to return. - * - * @callback FillMaskPipelineCallback Fill the masked token in the text(s) given as inputs. - * @param {string|string[]} texts One or several texts (or one list of prompts) with masked tokens. - * @param {FillMaskPipelineOptions} [options] The options to use for masked language modelling. - * @returns {Promise} An array of objects containing the score, predicted token, predicted token string, - * and the sequence with the predicted token filled in, or an array of such arrays (one for each input text). - * If only one input text is given, the output will be an array of objects. - * @throws {Error} When the mask token is not found in the input text. - * - * @typedef {TextPipelineConstructorArgs & FillMaskPipelineCallback & Disposable} FillMaskPipelineType - */ - -/** - * Masked language modeling prediction pipeline using any `ModelWithLMHead`. - * - * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-uncased`. - * ```javascript - * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased'); - * const output = await unmasker('The goal of life is [MASK].'); - * // [ - * // { token_str: 'survival', score: 0.06137419492006302, token: 8115, sequence: 'The goal of life is survival.' }, - * // { token_str: 'love', score: 0.03902450203895569, token: 1567, sequence: 'The goal of life is love.' }, - * // { token_str: 'happiness', score: 0.03253183513879776, token: 9266, sequence: 'The goal of life is happiness.' }, - * // { token_str: 'freedom', score: 0.018736306577920914, token: 4438, sequence: 'The goal of life is freedom.' }, - * // { token_str: 'life', score: 0.01859794743359089, token: 1297, sequence: 'The goal of life is life.' } - * // ] - * ``` - * - * **Example:** Perform masked language modelling (a.k.a. "fill-mask") with `Xenova/bert-base-cased` (and return top result). - * ```javascript - * const unmasker = await pipeline('fill-mask', 'Xenova/bert-base-cased'); - * const output = await unmasker('The Milky Way is a [MASK] galaxy.', { top_k: 1 }); - * // [{ token_str: 'spiral', score: 0.6299987435340881, token: 14061, sequence: 'The Milky Way is a spiral galaxy.' }] - * ``` - */ -class FillMaskPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ (Pipeline)) { - - /** - * Create a new FillMaskPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + const index = max(this.data)[1]; + return new _Tensor("int64", [BigInt(index)], []); + } + /** + * Repeats this tensor along the specified dimensions. + * @param {...number} repeats The number of times to repeat this tensor along each dimension. + * @returns {Tensor} The repeated tensor. + * @throws {Error} If the number of repeats is less than the number of dimensions. + */ + repeat(...repeats) { + if (repeats.length < this.dims.length) { + throw new Error( + `Number of dimensions of repeat dims (${repeats.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})` + ); } - - /** @type {FillMaskPipelineCallback} */ - async _call(texts, { - top_k = 5 - } = {}) { - - // Run tokenization - const model_inputs = this.tokenizer(texts, { - padding: true, - truncation: true, - }); - - // Run model - const { logits } = await this.model(model_inputs) - - const toReturn = []; - - /** @type {bigint[][]} */ - const input_ids = model_inputs.input_ids.tolist(); - for (let i = 0; i < input_ids.length; ++i) { - const ids = input_ids[i]; - const mask_token_index = ids.findIndex(x => - // We use == to match bigint with number - // @ts-ignore - x == this.tokenizer.mask_token_id - ); - if (mask_token_index === -1) { - throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`) - } - const itemLogits = logits[i][mask_token_index]; - - const scores = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( - 'float32', - (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(itemLogits.data), - itemLogits.dims, - ), top_k); - const values = scores[0].tolist(); - const indices = scores[1].tolist(); - - toReturn.push(indices.map((x, i) => { - const sequence = ids.slice(); - sequence[mask_token_index] = x; - - return { - score: values[i], - token: Number(x), - token_str: this.tokenizer.decode([x]), - sequence: this.tokenizer.decode(sequence, { skip_special_tokens: true }), - } - })); - } - return Array.isArray(texts) ? toReturn : toReturn[0]; - } -} - - -/** - * @typedef {Object} Text2TextGenerationSingle - * @property {string} generated_text The generated text. - * @typedef {Text2TextGenerationSingle[]} Text2TextGenerationOutput - * - * @callback Text2TextGenerationPipelineCallback Generate the output text(s) using text(s) given as inputs. - * @param {string|string[]} texts Input text for the encoder. - * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} - * - * @typedef {TextPipelineConstructorArgs & Text2TextGenerationPipelineCallback & Disposable} Text2TextGenerationPipelineType - */ - -/** - * Text2TextGenerationPipeline class for generating text using a model that performs text-to-text generation tasks. - * - * **Example:** Text-to-text generation w/ `Xenova/LaMini-Flan-T5-783M`. - * ```javascript - * const generator = await pipeline('text2text-generation', 'Xenova/LaMini-Flan-T5-783M'); - * const output = await generator('how can I become more healthy?', { - * max_new_tokens: 100, - * }); - * // [{ generated_text: "To become more healthy, you can: 1. Eat a balanced diet with plenty of fruits, vegetables, whole grains, lean proteins, and healthy fats. 2. Stay hydrated by drinking plenty of water. 3. Get enough sleep and manage stress levels. 4. Avoid smoking and excessive alcohol consumption. 5. Regularly exercise and maintain a healthy weight. 6. Practice good hygiene and sanitation. 7. Seek medical attention if you experience any health issues." }] - * ``` - */ -class Text2TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ (Pipeline)) { - /** @type {'generated_text'} */ - _key = 'generated_text'; - - /** - * Create a new Text2TextGenerationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + if (repeats.every((r) => r === 1)) { + if (repeats.length === this.dims.length) { + return this.clone(); + } + const numPrependedDims2 = repeats.length - this.dims.length; + const newDims = Array(numPrependedDims2).fill(1).concat(this.dims); + return new _Tensor(this.type, this.data.slice(), newDims); + } + const numPrependedDims = repeats.length - this.dims.length; + const expandedDims = Array(numPrependedDims).fill(1).concat(this.dims); + const outputDims = expandedDims.map((dim, i) => dim * repeats[i]); + const outputSize = outputDims.reduce((a, b) => a * b, 1); + const this_data = this.data; + const data = new this_data.constructor(outputSize); + const inputStrides = dimsToStride(expandedDims); + const outputStrides = dimsToStride(outputDims); + for (let i = 0; i < outputSize; ++i) { + let remaining = i; + let inputIndex = 0; + for (let d = 0; d < outputDims.length; ++d) { + const outputCoord = Math.floor(remaining / outputStrides[d]); + remaining = remaining % outputStrides[d]; + const inputCoord = outputCoord % expandedDims[d]; + inputIndex += inputCoord * inputStrides[d]; + } + data[i] = this_data[inputIndex]; } - - /** @type {Text2TextGenerationPipelineCallback} */ - async _call(texts, generate_kwargs = {}) { - if (!Array.isArray(texts)) { - texts = [texts]; - } - - - // Add global prefix, if present - // @ts-expect-error TS2339 - if (this.model.config.prefix) { - // @ts-expect-error TS2339 - texts = texts.map(x => this.model.config.prefix + x) - } - - // Handle task specific params: - // @ts-expect-error TS2339 - const task_specific_params = this.model.config.task_specific_params - if (task_specific_params && task_specific_params[this.task]) { - // Add prefixes, if present - if (task_specific_params[this.task].prefix) { - texts = texts.map(x => task_specific_params[this.task].prefix + x) - } - - // TODO update generation config - } - - const tokenizer = this.tokenizer; - const tokenizer_options = { - padding: true, - truncation: true, - } - let inputs; - if (this instanceof TranslationPipeline && '_build_translation_inputs' in tokenizer) { - // TODO: move to Translation pipeline? - // Currently put here to avoid code duplication - // @ts-ignore - inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs); - - } else { - inputs = tokenizer(texts, tokenizer_options); - } - - const outputTokenIds = await this.model.generate({ ...inputs, ...generate_kwargs }); - return tokenizer.batch_decode(/** @type {Tensor} */(outputTokenIds), { - skip_special_tokens: true, - }).map(text => ({ [this._key]: text })); - } -} - - -/** - * @typedef {Object} SummarizationSingle - * @property {string} summary_text The summary text. - * @typedef {SummarizationSingle[]} SummarizationOutput - * - * @callback SummarizationPipelineCallback Summarize the text(s) given as inputs. - * @param {string|string[]} texts One or several articles (or one list of articles) to summarize. - * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} - * - * @typedef {TextPipelineConstructorArgs & SummarizationPipelineCallback & Disposable} SummarizationPipelineType - */ - -/** - * A pipeline for summarization tasks, inheriting from Text2TextGenerationPipeline. - * - * **Example:** Summarization w/ `Xenova/distilbart-cnn-6-6`. - * ```javascript - * const generator = await pipeline('summarization', 'Xenova/distilbart-cnn-6-6'); - * const text = 'The tower is 324 metres (1,063 ft) tall, about the same height as an 81-storey building, ' + - * 'and the tallest structure in Paris. Its base is square, measuring 125 metres (410 ft) on each side. ' + - * 'During its construction, the Eiffel Tower surpassed the Washington Monument to become the tallest ' + - * 'man-made structure in the world, a title it held for 41 years until the Chrysler Building in New ' + - * 'York City was finished in 1930. It was the first structure to reach a height of 300 metres. Due to ' + - * 'the addition of a broadcasting aerial at the top of the tower in 1957, it is now taller than the ' + - * 'Chrysler Building by 5.2 metres (17 ft). Excluding transmitters, the Eiffel Tower is the second ' + - * 'tallest free-standing structure in France after the Millau Viaduct.'; - * const output = await generator(text, { - * max_new_tokens: 100, - * }); - * // [{ summary_text: ' The Eiffel Tower is about the same height as an 81-storey building and the tallest structure in Paris. It is the second tallest free-standing structure in France after the Millau Viaduct.' }] - * ``` - */ -class SummarizationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) { - /** @type {'summary_text'} */ - _key = 'summary_text'; - - /** - * Create a new SummarizationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } -} - - -/** - * @typedef {Object} TranslationSingle - * @property {string} translation_text The translated text. - * @typedef {TranslationSingle[]} TranslationOutput - * - * @callback TranslationPipelineCallback Translate the text(s) given as inputs. - * @param {string|string[]} texts Texts to be translated. - * @param {import('./generation/configuration_utils.js').GenerationConfig} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} - * - * @typedef {TextPipelineConstructorArgs & TranslationPipelineCallback & Disposable} TranslationPipelineType - */ - -/** - * Translates text from one language to another. - * - * **Example:** Multilingual translation w/ `Xenova/nllb-200-distilled-600M`. - * - * See [here](https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200) - * for the full list of languages and their corresponding codes. - * - * ```javascript - * const translator = await pipeline('translation', 'Xenova/nllb-200-distilled-600M'); - * const output = await translator('जीवन एक चॉकलेट बॉक्स की तरह है।', { - * src_lang: 'hin_Deva', // Hindi - * tgt_lang: 'fra_Latn', // French - * }); - * // [{ translation_text: 'La vie est comme une boîte à chocolat.' }] - * ``` - * - * **Example:** Multilingual translation w/ `Xenova/m2m100_418M`. - * - * See [here](https://huggingface.co/facebook/m2m100_418M#languages-covered) - * for the full list of languages and their corresponding codes. - * - * ```javascript - * const translator = await pipeline('translation', 'Xenova/m2m100_418M'); - * const output = await translator('生活就像一盒巧克力。', { - * src_lang: 'zh', // Chinese - * tgt_lang: 'en', // English - * }); - * // [{ translation_text: 'Life is like a box of chocolate.' }] - * ``` - * - * **Example:** Multilingual translation w/ `Xenova/mbart-large-50-many-to-many-mmt`. - * - * See [here](https://huggingface.co/facebook/mbart-large-50-many-to-many-mmt#languages-covered) - * for the full list of languages and their corresponding codes. - * - * ```javascript - * const translator = await pipeline('translation', 'Xenova/mbart-large-50-many-to-many-mmt'); - * const output = await translator('संयुक्त राष्ट्र के प्रमुख का कहना है कि सीरिया में कोई सैन्य समाधान नहीं है', { - * src_lang: 'hi_IN', // Hindi - * tgt_lang: 'fr_XX', // French - * }); - * // [{ translation_text: 'Le chef des Nations affirme qu 'il n 'y a military solution in Syria.' }] - * ``` - */ -class TranslationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ (/** @type {any} */ (Text2TextGenerationPipeline))) { - /** @type {'translation_text'} */ - _key = 'translation_text'; - - /** - * Create a new TranslationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + return new _Tensor(this.type, data, outputDims); + } + /** + * Constructs a tensor by repeating the elements of input. The dims argument specifies the number of repetitions in each dimension. + * @param {...number} dims The number of repetitions per dimension. + * @returns {Tensor} The tiled tensor. + */ + tile(...dims) { + if (dims.length < this.dims.length) { + const numPrependedRepeats = this.dims.length - dims.length; + dims = Array(numPrependedRepeats).fill(1).concat(dims); } -} - -function isChat(x) { - return Array.isArray(x) && x.every(x => 'role' in x && 'content' in x); -} - -/** - * @typedef {import('./tokenizers.js').Message[]} Chat - * - * @typedef {Object} TextGenerationSingle - * @property {string|Chat} generated_text The generated text. - * @typedef {TextGenerationSingle[]} TextGenerationOutput - * - * @typedef {Object} TextGenerationSpecificParams Parameters specific to text-generation pipelines. - * @property {boolean} [add_special_tokens] Whether or not to add special tokens when tokenizing the sequences. - * @property {boolean} [return_full_text=true] If set to `false` only added text is returned, otherwise the full text is returned. - * @typedef {import('./generation/configuration_utils.js').GenerationConfig & TextGenerationSpecificParams} TextGenerationConfig - * - * @callback TextGenerationPipelineCallback Complete the prompt(s) given as inputs. - * @param {string|string[]|Chat|Chat[]} texts One or several prompts (or one list of prompts) to complete. - * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} An array or object containing the generated texts. - * - * @typedef {TextPipelineConstructorArgs & TextGenerationPipelineCallback & Disposable} TextGenerationPipelineType - */ - -/** - * Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. - * This pipeline predicts the words that will follow a specified text prompt. - * NOTE: For the full list of generation parameters, see [`GenerationConfig`](./utils/generation#module_utils/generation.GenerationConfig). - * - * **Example:** Text generation with `Xenova/distilgpt2` (default settings). - * ```javascript - * const generator = await pipeline('text-generation', 'Xenova/distilgpt2'); - * const text = 'I enjoy walking with my cute dog,'; - * const output = await generator(text); - * // [{ generated_text: "I enjoy walking with my cute dog, and I love to play with the other dogs." }] - * ``` - * - * **Example:** Text generation with `Xenova/distilgpt2` (custom settings). - * ```javascript - * const generator = await pipeline('text-generation', 'Xenova/distilgpt2'); - * const text = 'Once upon a time, there was'; - * const output = await generator(text, { - * temperature: 2, - * max_new_tokens: 10, - * repetition_penalty: 1.5, - * no_repeat_ngram_size: 2, - * num_beams: 2, - * num_return_sequences: 2, - * }); - * // [{ - * // "generated_text": "Once upon a time, there was an abundance of information about the history and activities that" - * // }, { - * // "generated_text": "Once upon a time, there was an abundance of information about the most important and influential" - * // }] - * ``` - * - * **Example:** Run code generation with `Xenova/codegen-350M-mono`. - * ```javascript - * const generator = await pipeline('text-generation', 'Xenova/codegen-350M-mono'); - * const text = 'def fib(n):'; - * const output = await generator(text, { - * max_new_tokens: 44, - * }); - * // [{ - * // generated_text: 'def fib(n):\n' + - * // ' if n == 0:\n' + - * // ' return 0\n' + - * // ' elif n == 1:\n' + - * // ' return 1\n' + - * // ' else:\n' + - * // ' return fib(n-1) + fib(n-2)\n' - * // }] - * ``` - */ -class TextGenerationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ (Pipeline)) { - - /** - * Create a new TextGenerationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - - /** @type {TextGenerationPipelineCallback} */ - async _call(texts, generate_kwargs = {}) { - let isBatched = false; - let isChatInput = false; - - // By default, do not add special tokens, unless the tokenizer specifies otherwise - let add_special_tokens = generate_kwargs.add_special_tokens - ?? (this.tokenizer.add_bos_token || this.tokenizer.add_eos_token) - ?? false; - - // Normalize inputs - /** @type {string[]} */ - let inputs; - if (typeof texts === 'string') { - inputs = texts = [texts]; - } else if (Array.isArray(texts) && texts.every(x => typeof x === 'string')) { - isBatched = true; - inputs = /** @type {string[]} */(texts); + return this.repeat(...dims); + } + /** + * Performs Tensor dtype conversion. + * @param {DataType} type The desired data type. + * @returns {Tensor} The converted tensor. + */ + to(type) { + if (this.type === type) return this; + if (!DataTypeMap.hasOwnProperty(type)) { + throw new Error(`Unsupported type: ${type}`); + } + let map_fn; + const is_source_bigint = ["int64", "uint64"].includes(this.type); + const is_dest_bigint = ["int64", "uint64"].includes(type); + if (is_source_bigint && !is_dest_bigint) { + map_fn = Number; + } else if (!is_source_bigint && is_dest_bigint) { + if (["float16", "float32", "float64"].includes(this.type)) { + map_fn = (x) => BigInt(Math.floor(x)); + } else { + map_fn = BigInt; + } + } else if (this.type === "float16" && type == "float32" && this.data instanceof Uint16Array) { + return new _Tensor(type, uint16_to_float32(this.data), this.dims); + } + return new _Tensor( + type, + // @ts-ignore - TypeScript can't verify .from() across union of TypedArray constructors + DataTypeMap[type].from(this.data, map_fn), + this.dims + ); + } +}; +function reshape(data, dimensions) { + const totalElements = data.length; + const dimensionSize = dimensions.length === 0 ? 1 : dimensions.reduce((a, b) => a * b); + if (totalElements !== dimensionSize) { + throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); + } + let reshapedArray = data; + for (let i = dimensions.length - 1; i >= 0; i--) { + reshapedArray = reshapedArray.reduce( + (acc, val) => { + let lastArray = acc[acc.length - 1]; + if (lastArray.length < dimensions[i]) { + lastArray.push(val); } else { - if (isChat(texts)) { - texts = [/** @type {Chat} */(texts)]; - } else if (Array.isArray(texts) && texts.every(isChat)) { - isBatched = true; - } else { - throw new Error('Input must be a string, an array of strings, a Chat, or an array of Chats'); - } - isChatInput = true; - - // If the input is a chat, we need to apply the chat template - inputs = /** @type {string[]} */(/** @type {Chat[]} */ (texts).map( - x => this.tokenizer.apply_chat_template(x, { - tokenize: false, - add_generation_prompt: true, - }) - )); - add_special_tokens = false; // Chat template handles this already - } - - // By default, return full text - const return_full_text = isChatInput - ? false - : generate_kwargs.return_full_text ?? true; - - this.tokenizer.padding_side = 'left'; - const text_inputs = this.tokenizer(inputs, { - add_special_tokens, - padding: true, - truncation: true, - }); - - const outputTokenIds = /** @type {Tensor} */(await this.model.generate({ - ...text_inputs, - ...generate_kwargs - })); - - const decoded = this.tokenizer.batch_decode(outputTokenIds, { - skip_special_tokens: true, - }); - - let promptLengths; - if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) { - promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, { - skip_special_tokens: true, - }).map(x => x.length); - } - - /** @type {TextGenerationOutput[]} */ - const toReturn = Array.from({ length: texts.length }, _ => []); - for (let i = 0; i < decoded.length; ++i) { - const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length); - - if (promptLengths) { - // Trim the decoded text to only include the generated part - decoded[i] = decoded[i].slice(promptLengths[textIndex]); - } - toReturn[textIndex].push({ - generated_text: isChatInput - ? [ - ...((/** @type {Chat[]} */(texts)[textIndex])), - { role: 'assistant', content: decoded[i] }, - ] - : decoded[i] - }); - } - return (!isBatched && toReturn.length === 1) ? toReturn[0] : toReturn; - } -} - -/** - * @typedef {Object} ZeroShotClassificationOutput - * @property {string} sequence The sequence for which this is the output. - * @property {string[]} labels The labels sorted by order of likelihood. - * @property {number[]} scores The probabilities for each of the labels. - * - * @typedef {Object} ZeroShotClassificationPipelineOptions Parameters specific to zero-shot classification pipelines. - * @property {string} [hypothesis_template="This example is {}."] The template used to turn each - * candidate label into an NLI-style hypothesis. The candidate label will replace the {} placeholder. - * @property {boolean} [multi_label=false] Whether or not multiple candidate labels can be true. - * If `false`, the scores are normalized such that the sum of the label likelihoods for each sequence - * is 1. If `true`, the labels are considered independent and probabilities are normalized for each - * candidate by doing a softmax of the entailment score vs. the contradiction score. - * - * @callback ZeroShotClassificationPipelineCallback Classify the sequence(s) given as inputs. - * @param {string|string[]} texts The sequence(s) to classify, will be truncated if the model input is too large. - * @param {string|string[]} candidate_labels The set of possible class labels to classify each sequence into. - * Can be a single label, a string of comma-separated labels, or a list of labels. - * @param {ZeroShotClassificationPipelineOptions} [options] The options to use for zero-shot classification. - * @returns {Promise} An array or object containing the predicted labels and scores. - * - * @typedef {TextPipelineConstructorArgs & ZeroShotClassificationPipelineCallback & Disposable} ZeroShotClassificationPipelineType - */ - -/** - * NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` - * trained on NLI (natural language inference) tasks. Equivalent of `text-classification` - * pipelines, but these models don't require a hardcoded number of potential classes, they - * can be chosen at runtime. It usually means it's slower but it is **much** more flexible. - * - * **Example:** Zero shot classification with `Xenova/mobilebert-uncased-mnli`. - * ```javascript - * const classifier = await pipeline('zero-shot-classification', 'Xenova/mobilebert-uncased-mnli'); - * const text = 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.'; - * const labels = [ 'mobile', 'billing', 'website', 'account access' ]; - * const output = await classifier(text, labels); - * // { - * // sequence: 'Last week I upgraded my iOS version and ever since then my phone has been overheating whenever I use your app.', - * // labels: [ 'mobile', 'website', 'billing', 'account access' ], - * // scores: [ 0.5562091040482018, 0.1843621307860853, 0.13942646639336376, 0.12000229877234923 ] - * // } - * ``` - * - * **Example:** Zero shot classification with `Xenova/nli-deberta-v3-xsmall` (multi-label). - * ```javascript - * const classifier = await pipeline('zero-shot-classification', 'Xenova/nli-deberta-v3-xsmall'); - * const text = 'I have a problem with my iphone that needs to be resolved asap!'; - * const labels = [ 'urgent', 'not urgent', 'phone', 'tablet', 'computer' ]; - * const output = await classifier(text, labels, { multi_label: true }); - * // { - * // sequence: 'I have a problem with my iphone that needs to be resolved asap!', - * // labels: [ 'urgent', 'phone', 'computer', 'tablet', 'not urgent' ], - * // scores: [ 0.9958870956360275, 0.9923963400697035, 0.002333537946160235, 0.0015134138567598765, 0.0010699384208377163 ] - * // } - * ``` - */ -class ZeroShotClassificationPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ (Pipeline)) { - /** - * Create a new ZeroShotClassificationPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - - // Use model config to get label2id mapping - this.label2id = Object.fromEntries( - Object.entries((/** @type {any} */(this).model).config.label2id).map( - ([k, v]) => [k.toLowerCase(), v] - ) - ); - - this.entailment_id = this.label2id['entailment']; - if (this.entailment_id === undefined) { - 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']; - if (this.contradiction_id === undefined) { - console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."); - this.contradiction_id = 0; + acc.push([val]); } + return acc; + }, + [[]] + ); + } + return reshapedArray[0]; +} +function permute(tensor, axes) { + const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes); + return new Tensor3(tensor.type, permutedData, shape); +} +function interpolate(input, [out_height, out_width], mode = "bilinear", align_corners = false) { + const in_channels = input.dims.at(-3) ?? 1; + const in_height = input.dims.at(-2); + const in_width = input.dims.at(-1); + const output = interpolate_data( + /** @type {import('./maths.js').TypedArray}*/ + input.data, + [in_channels, in_height, in_width], + [out_height, out_width], + mode, + align_corners + ); + return new Tensor3(input.type, output, [in_channels, out_height, out_width]); +} +async function interpolate_4d(input, { size = null, mode = "bilinear" } = {}) { + if (input.dims.length !== 4) { + throw new Error("`interpolate_4d` currently only supports 4D input."); + } + if (!size) { + throw new Error("`interpolate_4d` requires a `size` argument."); + } + let targetDims; + if (size.length === 2) { + targetDims = [...input.dims.slice(0, 2), ...size]; + } else if (size.length === 3) { + targetDims = [input.dims[0], ...size]; + } else if (size.length === 4) { + targetDims = size; + } else { + throw new Error("`size` must be of length 2, 3, or 4."); + } + let op; + if (mode === "nearest") { + op = await TensorOpRegistry.nearest_interpolate_4d; + } else if (mode === "bilinear") { + op = await TensorOpRegistry.bilinear_interpolate_4d; + } else if (mode === "bicubic") { + op = await TensorOpRegistry.bicubic_interpolate_4d; + } else { + throw new Error(`Unsupported mode: ${mode}`); + } + const sizeTensor = new Tensor3("int64", new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]); + return await op({ x: input, s: sizeTensor }); +} +async function matmul(a, b) { + const op = await TensorOpRegistry.matmul; + return await op({ a, b }); +} +async function rfft(x, a) { + const axis = safeIndex(Number(a.item()), x.dims.length); + const op = await TensorOpRegistry.rfft; + return await op({ x: x.unsqueeze(-1), a: new Tensor3("int64", [BigInt(axis)], []) }); +} +async function topk(x, k) { + const op = await TensorOpRegistry.top_k; + if (k == null) { + k = x.dims.at(-1); + } else { + k = Math.min(k, x.dims.at(-1)); + } + return await op({ + x, + k: new Tensor3("int64", [BigInt(k)], [1]) + }); +} +var arrayToIndexTensor = (array) => new Tensor3("int64", array, [array.length]); +async function slice2(data, starts, ends, axes, steps) { + const op = await TensorOpRegistry.slice; + return await op({ + x: data, + s: arrayToIndexTensor(starts), + e: arrayToIndexTensor(ends), + a: arrayToIndexTensor(axes), + t: arrayToIndexTensor(steps ?? new Array(axes.length).fill(1)) + }); +} +function mean_pooling(last_hidden_state, attention_mask) { + const lastHiddenStateData = last_hidden_state.data; + const attentionMaskData = attention_mask.data; + const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]]; + const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]); + const [batchSize, seqLength, embedDim] = last_hidden_state.dims; + let outIndex = 0; + for (let i = 0; i < batchSize; ++i) { + const offset = i * embedDim * seqLength; + for (let k = 0; k < embedDim; ++k) { + let sum = 0; + let count2 = 0; + const attnMaskOffset = i * seqLength; + const offset2 = offset + k; + for (let j2 = 0; j2 < seqLength; ++j2) { + const attn = Number(attentionMaskData[attnMaskOffset + j2]); + count2 += attn; + sum += lastHiddenStateData[offset2 + j2 * embedDim] * attn; + } + const avg = sum / count2; + returnedData[outIndex++] = avg; } - - /** @type {ZeroShotClassificationPipelineCallback} */ - async _call(texts, candidate_labels, { - hypothesis_template = "This example is {}.", - multi_label = false, - } = {}) { - - const isBatched = Array.isArray(texts); - if (!isBatched) { - texts = [/** @type {string} */ (texts)]; - } - if (!Array.isArray(candidate_labels)) { - candidate_labels = [candidate_labels]; - } - - // Insert labels into hypothesis template - const hypotheses = candidate_labels.map( - x => hypothesis_template.replace('{}', x) - ); - - // How to perform the softmax over the logits: - // - true: softmax over the entailment vs. contradiction dim for each label independently - // - false: softmax the "entailment" logits over all candidate labels - const softmaxEach = multi_label || candidate_labels.length === 1; - - /** @type {ZeroShotClassificationOutput[]} */ - const toReturn = []; - for (const premise of texts) { - const entails_logits = []; - - for (const hypothesis of hypotheses) { - const inputs = this.tokenizer(premise, { - text_pair: hypothesis, - padding: true, - truncation: true, - }) - const outputs = await this.model(inputs) - - if (softmaxEach) { - entails_logits.push([ - outputs.logits.data[this.contradiction_id], - outputs.logits.data[this.entailment_id] - ]) - } else { - entails_logits.push(outputs.logits.data[this.entailment_id]) - } - } - - /** @type {number[]} */ - const scores = softmaxEach - ? entails_logits.map(x => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(x)[1]) - : (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(entails_logits); - - // Sort by scores (desc) and return scores with indices - const scores_sorted = scores - .map((x, i) => [x, i]) - .sort((a, b) => (b[0] - a[0])); - - toReturn.push({ - sequence: premise, - labels: scores_sorted.map(x => candidate_labels[x[1]]), - scores: scores_sorted.map(x => x[0]), - }); - } - return isBatched ? toReturn : toReturn[0]; - } -} - -/** - * @typedef {Object} FeatureExtractionPipelineOptions Parameters specific to feature extraction pipelines. - * @property {'none'|'mean'|'cls'|'first_token'|'eos'|'last_token'} [pooling="none"] The pooling method to use. - * @property {boolean} [normalize=false] Whether or not to normalize the embeddings in the last dimension. - * @property {boolean} [quantize=false] Whether or not to quantize the embeddings. - * @property {'binary'|'ubinary'} [precision='binary'] The precision to use for quantization. - * - * @callback FeatureExtractionPipelineCallback Extract the features of the input(s). - * @param {string|string[]} texts One or several texts (or one list of texts) to get the features of. - * @param {FeatureExtractionPipelineOptions} [options] The options to use for feature extraction. - * @returns {Promise} The features computed by the model. - * - * @typedef {TextPipelineConstructorArgs & FeatureExtractionPipelineCallback & Disposable} FeatureExtractionPipelineType - */ - -/** - * Feature extraction pipeline using no model head. This pipeline extracts the hidden - * states from the base transformer, which can be used as features in downstream tasks. - * - * **Example:** Run feature extraction with `bert-base-uncased` (without pooling/normalization). - * ```javascript - * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' }); - * const output = await extractor('This is a simple test.'); - * // Tensor { - * // type: 'float32', - * // data: Float32Array [0.05939924716949463, 0.021655935794115067, ...], - * // dims: [1, 8, 768] - * // } - * ``` - * - * **Example:** Run feature extraction with `bert-base-uncased` (with pooling/normalization). - * ```javascript - * const extractor = await pipeline('feature-extraction', 'Xenova/bert-base-uncased', { revision: 'default' }); - * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true }); - * // Tensor { - * // type: 'float32', - * // data: Float32Array [0.03373778983950615, -0.010106077417731285, ...], - * // dims: [1, 768] - * // } - * ``` - * - * **Example:** Calculating embeddings with `sentence-transformers` models. - * ```javascript - * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2'); - * const output = await extractor('This is a simple test.', { pooling: 'mean', normalize: true }); - * // Tensor { - * // type: 'float32', - * // data: Float32Array [0.09094982594251633, -0.014774246141314507, ...], - * // dims: [1, 384] - * // } - * ``` - * **Example:** Calculating binary embeddings with `sentence-transformers` models. - * ```javascript - * const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2'); - * const output = await extractor('This is a simple test.', { pooling: 'mean', quantize: true, precision: 'binary' }); - * // Tensor { - * // type: 'int8', - * // data: Int8Array [49, 108, 24, ...], - * // dims: [1, 48] - * // } - * ``` - */ -class FeatureExtractionPipeline extends (/** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ (Pipeline)) { - /** - * Create a new FeatureExtractionPipeline. - * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - - /** @type {FeatureExtractionPipelineCallback} */ - async _call(texts, { - pooling = /** @type {'none'} */('none'), - normalize = false, - quantize = false, - precision = /** @type {'binary'} */('binary'), - } = {}) { - - // Run tokenization - const model_inputs = this.tokenizer(texts, { - padding: true, - truncation: true, - }); - - // Run model - const outputs = await this.model(model_inputs) - - // TODO: Provide warning to the user that they might be using model which was not exported - // specifically for feature extraction - // console.log(this.model.config) - // console.log(outputs) - - /** @type {Tensor} */ - let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings; - - switch (pooling) { - case 'none': - // Skip pooling - break; - case 'mean': - result = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean_pooling)(result, model_inputs.attention_mask); - break; - case 'first_token': - case 'cls': - result = result.slice(null, 0); - break; - case 'last_token': - case 'eos': - result = result.slice(null, -1); - break; - default: - throw Error(`Pooling method '${pooling}' not supported.`); - } - - if (normalize) { - result = result.normalize(2, -1); - } - - if (quantize) { - result = (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.quantize_embeddings)(result, precision); - } - - return result; + } + return new Tensor3(last_hidden_state.type, returnedData, shape); +} +function layer_norm(input, normalized_shape, { eps = 1e-5 } = {}) { + if (input.dims.length !== 2) { + throw new Error("`layer_norm` currently only supports 2D input."); + } + const [batchSize, featureDim] = input.dims; + if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) { + throw new Error("`normalized_shape` must be a 1D array with shape `[input.dims[1]]`."); + } + const [std, mean2] = std_mean(input, 1, 0, true); + const stdData = ( + /** @type {Float32Array} */ + std.data + ); + const meanData = ( + /** @type {Float32Array} */ + mean2.data + ); + const inputData = ( + /** @type {Float32Array} */ + input.data + ); + const returnedData = new inputData.constructor(inputData.length); + for (let i = 0; i < batchSize; ++i) { + const offset = i * featureDim; + for (let j2 = 0; j2 < featureDim; ++j2) { + const offset2 = offset + j2; + returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps); } + } + return new Tensor3(input.type, returnedData, input.dims); } - - -/** - * @typedef {Object} ImageFeatureExtractionPipelineOptions Parameters specific to image feature extraction pipelines. - * @property {boolean} [pool=null] Whether or not to return the pooled output. If set to `false`, the model will return the raw hidden states. - * - * @callback ImageFeatureExtractionPipelineCallback Extract the features of the input(s). - * @param {ImagePipelineInputs} images One or several images (or one list of images) to get the features of. - * @param {ImageFeatureExtractionPipelineOptions} [options] The options to use for image feature extraction. - * @returns {Promise} The image features computed by the model. - * - * @typedef {ImagePipelineConstructorArgs & ImageFeatureExtractionPipelineCallback & Disposable} ImageFeatureExtractionPipelineType - */ - -/** - * Image feature extraction pipeline using no model head. This pipeline extracts the hidden - * states from the base transformer, which can be used as features in downstream tasks. - * - * **Example:** Perform image feature extraction with `Xenova/vit-base-patch16-224-in21k`. - * ```javascript - * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/vit-base-patch16-224-in21k'); - * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png'; - * const features = await image_feature_extractor(url); - * // Tensor { - * // dims: [ 1, 197, 768 ], - * // type: 'float32', - * // data: Float32Array(151296) [ ... ], - * // size: 151296 - * // } - * ``` - * - * **Example:** Compute image embeddings with `Xenova/clip-vit-base-patch32`. - * ```javascript - * const image_feature_extractor = await pipeline('image-feature-extraction', 'Xenova/clip-vit-base-patch32'); - * const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png'; - * const features = await image_feature_extractor(url); - * // Tensor { - * // dims: [ 1, 512 ], - * // type: 'float32', - * // data: Float32Array(512) [ ... ], - * // size: 512 - * // } - * ``` - */ -class ImageFeatureExtractionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ (Pipeline)) { - /** - * Create a new ImageFeatureExtractionPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); +function calc_squeeze_dims(dims, dim) { + dims = dims.slice(); + if (dim === null) { + dims = dims.filter((d) => d !== 1); + } else if (typeof dim === "number") { + if (dims[dim] === 1) { + dims.splice(dim, 1); + } + } else if (Array.isArray(dim)) { + dims = dims.filter((x, i) => { + return x !== 1 || !dim.includes(i); + }); + } + return dims; +} +function calc_unsqueeze_dims(dims, dim) { + dim = safeIndex(dim, dims.length + 1); + dims = dims.slice(); + dims.splice(dim, 0, 1); + return dims; +} +function safeIndex(index, size, dimension = null, boundsCheck = true) { + if (index < -size || index >= size) { + if (boundsCheck) { + throw new Error( + `IndexError: index ${index} is out of bounds for dimension${dimension === null ? "" : " " + dimension} with size ${size}` + ); + } else { + return index < -size ? 0 : size; + } + } + if (index < 0) { + index = (index % size + size) % size; + } + return index; +} +function cat(tensors, dim = 0) { + dim = safeIndex(dim, tensors[0].dims.length); + const resultDims = tensors[0].dims.slice(); + resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0); + const resultSize = resultDims.reduce((a, b) => a * b, 1); + const result = new tensors[0].data.constructor(resultSize); + const resultType = tensors[0].type; + if (dim === 0) { + let offset = 0; + for (const tensor of tensors) { + const tensorData = tensor.data; + result.set(tensorData, offset); + offset += tensorData.length; } - - /** @type {ImageFeatureExtractionPipelineCallback} */ - async _call(images, { - pool = null, - } = {}) { - - const preparedImages = await prepareImages(images); - const { pixel_values } = await this.processor(preparedImages); - const outputs = await this.model({ pixel_values }); - - /** @type {Tensor} */ - let result; - if (pool) { - if (!('pooler_output' in outputs)) { - throw Error(`No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.`); - } - result = outputs.pooler_output; - - } else { - result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds; + } else { + let currentDim = 0; + for (let t = 0; t < tensors.length; ++t) { + const { data, dims } = tensors[t]; + for (let i = 0; i < data.length; ++i) { + let resultIndex = 0; + for (let j2 = dims.length - 1, num = i, resultMultiplier = 1; j2 >= 0; --j2) { + const size = dims[j2]; + let index = num % size; + if (j2 === dim) { + index += currentDim; + } + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j2]; + num = Math.floor(num / size); } - return result; + result[resultIndex] = data[i]; + } + currentDim += dims[dim]; } + } + return new Tensor3(resultType, result, resultDims); } - -// TODO -// export class SentenceSimilarityPipeline extends Pipeline { -// } - -/** - * @typedef {Object} AudioClassificationSingle - * @property {string} label The label predicted. - * @property {number} score The corresponding probability. - * @typedef {AudioClassificationSingle[]} AudioClassificationOutput - * - * @typedef {Object} AudioClassificationPipelineOptions Parameters specific to audio classification pipelines. - * @property {number} [top_k=5] The number of top labels that will be returned by the pipeline. - * If the provided number is `null` or higher than the number of labels available in the model configuration, - * it will default to the number of labels. - * - * @callback AudioClassificationPipelineCallback Classify the sequence(s) given as inputs. - * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either: - * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate - * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. - * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. - * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). - * @param {AudioClassificationPipelineOptions} [options] The options to use for audio classification. - * @returns {Promise} An array or object containing the predicted labels and scores. - * - * @typedef {AudioPipelineConstructorArgs & AudioClassificationPipelineCallback & Disposable} AudioClassificationPipelineType - */ - -/** - * Audio classification pipeline using any `AutoModelForAudioClassification`. - * This pipeline predicts the class of a raw waveform or an audio file. - * - * **Example:** Perform audio classification with `Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech`. - * ```javascript - * const classifier = await pipeline('audio-classification', 'Xenova/wav2vec2-large-xlsr-53-gender-recognition-librispeech'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; - * const output = await classifier(url); - * // [ - * // { label: 'male', score: 0.9981542229652405 }, - * // { label: 'female', score: 0.001845747814513743 } - * // ] - * ``` - * - * **Example:** Perform audio classification with `Xenova/ast-finetuned-audioset-10-10-0.4593` and return top 4 results. - * ```javascript - * const classifier = await pipeline('audio-classification', 'Xenova/ast-finetuned-audioset-10-10-0.4593'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cat_meow.wav'; - * const output = await classifier(url, { top_k: 4 }); - * // [ - * // { label: 'Meow', score: 0.5617874264717102 }, - * // { label: 'Cat', score: 0.22365376353263855 }, - * // { label: 'Domestic animals, pets', score: 0.1141069084405899 }, - * // { label: 'Animal', score: 0.08985692262649536 }, - * // ] - * ``` - */ -class AudioClassificationPipeline extends (/** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ (Pipeline)) { - - /** - * Create a new AudioClassificationPipeline. - * @param {AudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); +function stack(tensors, dim = 0) { + return cat( + tensors.map((t) => t.unsqueeze(dim)), + dim + ); +} +function reduce_helper(callbackfn, input, dim, keepdim = false, initialValue = null) { + const inputData = input.data; + const inputDims = input.dims; + dim = safeIndex(dim, inputDims.length); + const resultDims = inputDims.slice(); + resultDims[dim] = 1; + const result = new inputData.constructor(inputData.length / inputDims[dim]); + if (initialValue !== null) { + result.fill(initialValue); + } + for (let i = 0; i < inputData.length; ++i) { + let resultIndex = 0; + for (let j2 = inputDims.length - 1, num = i, resultMultiplier = 1; j2 >= 0; --j2) { + const size = inputDims[j2]; + if (j2 !== dim) { + const index = num % size; + resultIndex += index * resultMultiplier; + resultMultiplier *= resultDims[j2]; + } + num = Math.floor(num / size); } - - /** @type {AudioClassificationPipelineCallback} */ - async _call(audio, { - top_k = 5 - } = {}) { - - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - - // @ts-expect-error TS2339 - const id2label = this.model.config.id2label; - - const toReturn = []; - for (const aud of preparedAudios) { - const inputs = await this.processor(aud); - const output = await this.model(inputs); - const logits = output.logits[0]; - - const scores = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( - 'float32', - (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(logits.data), - logits.dims, - ), top_k); - - const values = scores[0].tolist(); - const indices = scores[1].tolist(); - - const vals = indices.map((x, i) => ({ - label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`), - score: /** @type {number} */ (values[i]), - })); - - toReturn.push(vals); - }; - return Array.isArray(audio) ? toReturn : toReturn[0]; - } -} - -/** - * @typedef {Object} ZeroShotAudioClassificationOutput - * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`. - * @property {number} score The score attributed by the model for that label (between 0 and 1). - * - * @typedef {Object} ZeroShotAudioClassificationPipelineOptions Parameters specific to zero-shot audio classification pipelines. - * @property {string} [hypothesis_template="This is a sound of {}."] The sentence used in conjunction with `candidate_labels` - * to attempt the audio classification by replacing the placeholder with the candidate_labels. - * Then likelihood is estimated by using `logits_per_audio`. - * - * @callback ZeroShotAudioClassificationPipelineCallback Classify the sequence(s) given as inputs. - * @param {AudioPipelineInputs} audio The input audio file(s) to be classified. The input is either: - * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate - * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. - * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. - * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). - * @param {string[]} candidate_labels The candidate labels for this audio. - * @param {ZeroShotAudioClassificationPipelineOptions} [options] The options to use for zero-shot audio classification. - * @returns {Promise} An array of objects containing the predicted labels and scores. - * - * @typedef {TextAudioPipelineConstructorArgs & ZeroShotAudioClassificationPipelineCallback & Disposable} ZeroShotAudioClassificationPipelineType - */ - -/** - * Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you - * provide an audio and a set of `candidate_labels`. - * - * **Example**: Perform zero-shot audio classification with `Xenova/clap-htsat-unfused`. - * ```javascript - * const classifier = await pipeline('zero-shot-audio-classification', 'Xenova/clap-htsat-unfused'); - * const audio = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/dog_barking.wav'; - * const candidate_labels = ['dog', 'vaccum cleaner']; - * const scores = await classifier(audio, candidate_labels); - * // [ - * // { score: 0.9993992447853088, label: 'dog' }, - * // { score: 0.0006007603369653225, label: 'vaccum cleaner' } - * // ] - * ``` - */ -class ZeroShotAudioClassificationPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ (Pipeline)) { - - /** - * Create a new ZeroShotAudioClassificationPipeline. - * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + result[resultIndex] = callbackfn(result[resultIndex], inputData[i], i, resultIndex); + } + if (!keepdim) resultDims.splice(dim, 1); + return [input.type, result, resultDims]; +} +function std_mean(input, dim = null, correction = 1, keepdim = false) { + const inputData = ( + /** @type {Float32Array} */ + input.data + ); + const inputDims = input.dims; + if (dim === null) { + const sum = inputData.reduce((a, b) => a + b, 0); + const mean2 = sum / inputData.length; + const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean2) ** 2, 0) / (inputData.length - correction)); + const meanTensor2 = new Tensor3( + input.type, + [mean2], + [ + /* scalar */ + ] + ); + const stdTensor2 = new Tensor3( + input.type, + [std], + [ + /* scalar */ + ] + ); + return [stdTensor2, meanTensor2]; + } + dim = safeIndex(dim, inputDims.length); + const meanTensor = mean(input, dim, keepdim); + const meanTensorData = meanTensor.data; + const [type, result, resultDims] = reduce_helper( + (a, b, i, j2) => a + (b - meanTensorData[j2]) ** 2, + input, + dim, + keepdim + ); + for (let i = 0; i < result.length; ++i) { + result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction)); + } + const stdTensor = new Tensor3(type, result, resultDims); + return [stdTensor, meanTensor]; +} +function mean(input, dim = null, keepdim = false) { + const inputDims = input.dims; + const inputData = ( + /** @type {Float32Array} */ + input.data + ); + if (dim === null) { + const val = inputData.reduce((a, b) => a + b, 0); + return new Tensor3( + input.type, + [val / inputData.length], + [ + /* scalar */ + ] + ); + } + dim = safeIndex(dim, inputDims.length); + const [type, result, resultDims] = reduce_helper((a, b) => a + b, input, dim, keepdim); + if (inputDims[dim] !== 1) { + for (let i = 0; i < result.length; ++i) { + result[i] /= inputDims[dim]; } + } + return new Tensor3(type, result, resultDims); +} +function dimsToStride(dims) { + const stride = new Array(dims.length); + for (let i = dims.length - 1, s2 = 1; i >= 0; --i) { + stride[i] = s2; + s2 *= dims[i]; + } + return stride; +} +function fullHelper(size, fill_value, dtype, cls) { + const numElements = size.reduce((a, b) => a * b, 1); + return new Tensor3(dtype, new cls(numElements).fill(fill_value), size); +} +function full(size, fill_value) { + let dtype; + let typedArrayCls; + if (typeof fill_value === "number") { + dtype = "float32"; + typedArrayCls = Float32Array; + } else if (typeof fill_value === "bigint") { + dtype = "int64"; + typedArrayCls = BigInt64Array; + } else if (typeof fill_value === "boolean") { + dtype = "bool"; + typedArrayCls = Uint8Array; + } else { + throw new Error(`Unsupported data type: ${typeof fill_value}`); + } + return fullHelper(size, fill_value, dtype, typedArrayCls); +} +function full_like(tensor, fill_value) { + return full(tensor.dims, fill_value); +} +function ones(size) { + return fullHelper(size, 1n, "int64", BigInt64Array); +} +function ones_like(tensor) { + return ones(tensor.dims); +} +function zeros(size) { + return fullHelper(size, 0n, "int64", BigInt64Array); +} +function zeros_like(tensor) { + return zeros(tensor.dims); +} +function rand(size) { + const length = size.reduce((a, b) => a * b, 1); + return new Tensor3( + "float32", + Float32Array.from({ length }, () => random.random()), + size + ); +} +function randn(size) { + const length = size.reduce((a, b) => a * b, 1); + return new Tensor3( + "float32", + Float32Array.from({ length }, () => random.gauss()), + size + ); +} +function quantize_embeddings(tensor, precision) { + if (tensor.dims.length !== 2) { + throw new Error("The tensor must have 2 dimensions"); + } + if (tensor.dims.at(-1) % 8 !== 0) { + throw new Error("The last dimension of the tensor must be a multiple of 8"); + } + if (!["binary", "ubinary"].includes(precision)) { + throw new Error("The precision must be either 'binary' or 'ubinary'"); + } + const signed = precision === "binary"; + const dtype = signed ? "int8" : "uint8"; + const cls = signed ? Int8Array : Uint8Array; + const inputData = tensor.data; + const outputData = new cls(inputData.length / 8); + for (let i = 0; i < inputData.length; ++i) { + const bit = inputData[i] > 0 ? 1 : 0; + const arrayIndex = Math.floor(i / 8); + const bitPosition = i % 8; + outputData[arrayIndex] |= bit << 7 - bitPosition; + if (signed && bitPosition === 0) { + outputData[arrayIndex] -= 128; + } + } + return new Tensor3(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]); +} - /** @type {ZeroShotAudioClassificationPipelineCallback} */ - async _call(audio, candidate_labels, { - hypothesis_template = "This is a sound of {}." - } = {}) { - - const single = !Array.isArray(audio); - if (single) { - audio = [/** @type {AudioInput} */ (audio)]; - } +// src/utils/model_registry/get_tokenizer_files.js +async function get_tokenizer_files(modelId) { + if (!modelId) { + throw new Error("modelId is required for get_tokenizer_files"); + } + const metadata = await get_file_metadata(modelId, "tokenizer_config.json", {}); + if (metadata.exists) { + return ["tokenizer.json", "tokenizer_config.json"]; + } + return []; +} - // Insert label into hypothesis template - const texts = candidate_labels.map( - x => hypothesis_template.replace('{}', x) +// src/tokenization_utils.js +async function loadTokenizer(pretrained_model_name_or_path, options) { + const tokenizerFiles = await get_tokenizer_files(pretrained_model_name_or_path); + return await Promise.all( + tokenizerFiles.map((file) => getModelJSON(pretrained_model_name_or_path, file, true, options)) + ); +} +function prepareTensorForDecode(tensor) { + const dims = tensor.dims; + switch (dims.length) { + case 1: + return tensor.tolist(); + case 2: + if (dims[0] !== 1) { + throw new Error( + "Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs." ); - - // Run tokenization - const text_inputs = this.tokenizer(texts, { - padding: true, - truncation: true, - }); - - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - - const toReturn = []; - for (const aud of preparedAudios) { - const audio_inputs = await this.processor(aud); - - // Run model with both text and audio inputs - const output = await this.model({ ...text_inputs, ...audio_inputs }); - - // Compute softmax per audio - const probs = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(output.logits_per_audio.data); - - toReturn.push([...probs].map((x, i) => ({ - score: x, - label: candidate_labels[i] - }))); - } - return single ? toReturn[0] : toReturn; - } -} - -/** - * @typedef {Object} Chunk - * @property {[number, number]} timestamp The start and end timestamp of the chunk in seconds. - * @property {string} text The recognized text. - */ - -/** - * @typedef {Object} AutomaticSpeechRecognitionOutput - * @property {string} text The recognized text. - * @property {Chunk[]} [chunks] When using `return_timestamps`, the `chunks` will become a list - * containing all the various text chunks identified by the model. - * - * @typedef {Object} AutomaticSpeechRecognitionSpecificParams Parameters specific to automatic-speech-recognition pipelines. - * @property {boolean|'word'} [return_timestamps] Whether to return timestamps or not. Default is `false`. - * @property {number} [chunk_length_s] The length of audio chunks to process in seconds. Default is 0 (no chunking). - * @property {number} [stride_length_s] The length of overlap between consecutive audio chunks in seconds. If not provided, defaults to `chunk_length_s / 6`. - * @property {boolean} [force_full_sequences] Whether to force outputting full sequences or not. Default is `false`. - * @property {string} [language] The source language. Default is `null`, meaning it should be auto-detected. Use this to potentially improve performance if the source language is known. - * @property {string} [task] The task to perform. Default is `null`, meaning it should be auto-detected. - * @property {number} [num_frames] The number of frames in the input audio. - * @typedef {import('./generation/configuration_utils.js').GenerationConfig & AutomaticSpeechRecognitionSpecificParams} AutomaticSpeechRecognitionConfig - * - * @callback AutomaticSpeechRecognitionPipelineCallback Transcribe the audio sequence(s) given as inputs to text. - * @param {AudioPipelineInputs} audio The input audio file(s) to be transcribed. The input is either: - * - `string` or `URL` that is the filename/URL of the audio file, the file will be read at the processor's sampling rate - * to get the waveform using the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) API. - * If `AudioContext` is not available, you should pass the raw waveform in as a Float32Array of shape `(n, )`. - * - `Float32Array` or `Float64Array` of shape `(n, )`, representing the raw audio at the correct sampling rate (no further check will be done). - * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} An object containing the transcription text and optionally timestamps if `return_timestamps` is `true`. - * - * @typedef {TextAudioPipelineConstructorArgs & AutomaticSpeechRecognitionPipelineCallback & Disposable} AutomaticSpeechRecognitionPipelineType - */ - -/** - * Pipeline that aims at extracting spoken text contained within some audio. - * - * **Example:** Transcribe English. - * ```javascript - * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; - * const output = await transcriber(url); - * // { text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." } - * ``` - * - * **Example:** Transcribe English w/ timestamps. - * ```javascript - * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; - * const output = await transcriber(url, { return_timestamps: true }); - * // { - * // text: " And so my fellow Americans ask not what your country can do for you, ask what you can do for your country." - * // chunks: [ - * // { timestamp: [0, 8], text: " And so my fellow Americans ask not what your country can do for you" } - * // { timestamp: [8, 11], text: " ask what you can do for your country." } - * // ] - * // } - * ``` - * - * **Example:** Transcribe English w/ word-level timestamps. - * ```javascript - * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/jfk.wav'; - * const output = await transcriber(url, { return_timestamps: 'word' }); - * // { - * // "text": " And so my fellow Americans ask not what your country can do for you ask what you can do for your country.", - * // "chunks": [ - * // { "text": " And", "timestamp": [0, 0.78] }, - * // { "text": " so", "timestamp": [0.78, 1.06] }, - * // { "text": " my", "timestamp": [1.06, 1.46] }, - * // ... - * // { "text": " for", "timestamp": [9.72, 9.92] }, - * // { "text": " your", "timestamp": [9.92, 10.22] }, - * // { "text": " country.", "timestamp": [10.22, 13.5] } - * // ] - * // } - * ``` - * - * **Example:** Transcribe French. - * ```javascript - * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3'; - * const output = await transcriber(url, { language: 'french', task: 'transcribe' }); - * // { text: " J'adore, j'aime, je n'aime pas, je déteste." } - * ``` - * - * **Example:** Translate French to English. - * ```javascript - * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-small'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/french-audio.mp3'; - * const output = await transcriber(url, { language: 'french', task: 'translate' }); - * // { text: " I love, I like, I don't like, I hate." } - * ``` - * - * **Example:** Transcribe/translate audio longer than 30 seconds. - * ```javascript - * const transcriber = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny.en'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/ted_60.wav'; - * const output = await transcriber(url, { chunk_length_s: 30, stride_length_s: 5 }); - * // { text: " So in college, I was a government major, which means [...] So I'd start off light and I'd bump it up" } - * ``` - */ -class AutomaticSpeechRecognitionPipeline extends (/** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ (Pipeline)) { - - /** - * Create a new AutomaticSpeechRecognitionPipeline. - * @param {TextAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + } + return tensor.tolist()[0]; + default: + throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`); + } +} +var SPECIAL_TOKEN_ATTRIBUTES = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token" + // additional_special_tokens (TODO) +]; +function padHelper(item, length, value_fn, side) { + for (const key of Object.keys(item)) { + const diff = length - item[key].length; + const value = value_fn(key); + const padData = new Array(diff).fill(value); + item[key] = side === "right" ? mergeArrays(item[key], padData) : mergeArrays(padData, item[key]); + } +} +function truncateHelper(item, length) { + for (const key of Object.keys(item)) { + item[key].length = length; + } +} +function getTokenFromConfig(config, ...keys) { + for (const key of keys) { + if (!Object.hasOwn(config, key)) continue; + const item = config[key]; + if (!item) continue; + if (typeof item === "object") { + if (item.__type === "AddedToken") { + return item.content; + } else { + throw Error(`Unknown token: ${item}`); + } + } else { + return item; } - - /** @type {AutomaticSpeechRecognitionPipelineCallback} */ - async _call(audio, kwargs = {}) { - switch (this.model.config.model_type) { - case 'whisper': - case 'lite-whisper': - return this._call_whisper(audio, kwargs) - case 'wav2vec2': - case 'wav2vec2-bert': - case 'unispeech': - case 'unispeech-sat': - case 'hubert': - return this._call_wav2vec2(audio, kwargs) - case 'moonshine': - return this._call_moonshine(audio, kwargs) - default: - throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`) - } + } + return null; +} +function getSpecialTokens(tokenizer) { + const special = []; + for (const value of tokenizer.get_added_tokens_decoder().values()) { + if (value.special) special.push(value); + } + return special; +} +var PreTrainedTokenizer = class extends /** @type {new (tokenizerJSON: Object, tokenizerConfig: Object) => PreTrainedTokenizerCallback} */ +Callable { + return_token_type_ids = false; + padding_side = "right"; + /** + * Create a new PreTrainedTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON, tokenizerConfig) { + super(); + this._tokenizerJSON = tokenizerJSON; + this._tokenizerConfig = tokenizerConfig; + this._tokenizer = new Tokenizer_default(tokenizerJSON, tokenizerConfig); + this.config = tokenizerConfig; + this.padding_side = tokenizerConfig.padding_side ?? this.padding_side; + this.mask_token = getTokenFromConfig(tokenizerConfig, "mask_token"); + this.mask_token_id = this._tokenizer.token_to_id(this.mask_token); + this.pad_token = getTokenFromConfig(tokenizerConfig, "pad_token", "eos_token"); + this.pad_token_id = this._tokenizer.token_to_id(this.pad_token); + this.sep_token = getTokenFromConfig(tokenizerConfig, "sep_token"); + this.sep_token_id = this._tokenizer.token_to_id(this.sep_token); + this.unk_token = getTokenFromConfig(tokenizerConfig, "unk_token"); + this.unk_token_id = this._tokenizer.token_to_id(this.unk_token); + this.bos_token = getTokenFromConfig(tokenizerConfig, "bos_token"); + this.bos_token_id = this._tokenizer.token_to_id(this.bos_token); + this.eos_token = getTokenFromConfig(tokenizerConfig, "eos_token"); + this.eos_token_id = this._tokenizer.token_to_id(this.eos_token); + this.chat_template = tokenizerConfig.chat_template ?? null; + if (Array.isArray(this.chat_template)) { + const chat_template = /* @__PURE__ */ Object.create(null); + for (const { name, template } of this.chat_template) { + if (typeof name !== "string" || typeof template !== "string") { + throw new Error('Chat template must be a list of objects with "name" and "template" properties'); + } + chat_template[name] = template; + } + this.chat_template = chat_template; } - - /** - * @type {AutomaticSpeechRecognitionPipelineCallback} - * @private - */ - async _call_wav2vec2(audio, kwargs) { - // TODO use kwargs - - if (kwargs.language) { - console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'); - } - if (kwargs.task) { - console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); - } - - const single = !Array.isArray(audio); - if (single) { - audio = [/** @type {AudioInput} */ (audio)]; - } - - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - - const toReturn = []; - for (const aud of preparedAudios) { - const inputs = await this.processor(aud); - const output = await this.model(inputs); - const logits = output.logits[0]; - - const predicted_ids = []; - for (const item of logits) { - predicted_ids.push((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.max)(item.data)[1]) - } - const predicted_sentences = this.tokenizer.decode(predicted_ids) - toReturn.push({ text: predicted_sentences }) - } - return single ? toReturn[0] : toReturn; + this._compiled_template_cache = /* @__PURE__ */ new Map(); + const special_tokens = getSpecialTokens(this._tokenizer); + this.all_special_ids = special_tokens.map((t) => t.id); + this.all_special_tokens = special_tokens.map((t) => t.content); + } + /** + * Loads a pretrained tokenizer from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pretrained tokenizer. + * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. + * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main" } = {}) { + const info = await loadTokenizer(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision + }); + return new this(...info); + } + get_vocab() { + return this._tokenizer.get_vocab(); + } + get model_max_length() { + return this._tokenizerConfig.model_max_length ?? Infinity; + } + get add_eos_token() { + return this._tokenizerConfig.add_eos_token; + } + get add_bos_token() { + return this._tokenizerConfig.add_bos_token; + } + /** + * Converts a token string (or a sequence of tokens) into a single integer id (or a sequence of ids), using the vocabulary. + * + * @template {string|string[]} T + * @param {T} tokens One or several token(s) to convert to token id(s). + * @returns {T extends string ? number : number[]} The token id or list of token ids. + */ + convert_tokens_to_ids(tokens) { + if (typeof tokens === "string") { + return ( + /** @type {any} */ + this._tokenizer.token_to_id(tokens) + ); + } else { + return ( + /** @type {any} */ + tokens.map((token) => this._tokenizer.token_to_id(token)) + ); } - - /** - * @type {AutomaticSpeechRecognitionPipelineCallback} - * @private - */ - async _call_whisper(audio, kwargs) { - const return_timestamps = kwargs.return_timestamps ?? false; - const chunk_length_s = kwargs.chunk_length_s ?? 0; - const force_full_sequences = kwargs.force_full_sequences ?? false; - let stride_length_s = kwargs.stride_length_s ?? null; - - const generation_config = { ...kwargs } - - if (return_timestamps === 'word') { - generation_config['return_token_timestamps'] = true; - generation_config['return_timestamps'] = false; // Do not predict timestamp tokens - } - - const single = !Array.isArray(audio); - if (single) { - audio = [/** @type {AudioInput} */ (audio)]; - } - - // @ts-expect-error TS2339 - const time_precision = this.processor.feature_extractor.config.chunk_length / this.model.config.max_source_positions; - const hop_length = this.processor.feature_extractor.config.hop_length; - - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - - const toReturn = []; - for (const aud of preparedAudios) { - /** @type {{stride: number[], input_features: Tensor, is_last: boolean, tokens?: bigint[], token_timestamps?: number[]}[]} */ - let chunks = []; - if (chunk_length_s > 0) { - if (stride_length_s === null) { - stride_length_s = chunk_length_s / 6; - } else if (chunk_length_s <= stride_length_s) { - throw Error("`chunk_length_s` must be larger than `stride_length_s`.") - } - - // TODO support different stride_length_s (for left and right) - - const window = sampling_rate * chunk_length_s; - const stride = sampling_rate * stride_length_s; - const jump = window - 2 * stride; - let offset = 0; - - // Create subarrays of audio with overlaps - while (true) { - const offset_end = offset + window; - const subarr = aud.subarray(offset, offset_end); - const feature = await this.processor(subarr); - - const is_first = offset === 0; - const is_last = offset_end >= aud.length; - chunks.push({ - stride: [ - subarr.length, - is_first ? 0 : stride, - is_last ? 0 : stride - ], - input_features: feature.input_features, - is_last, - }) - if (is_last) break; - offset += jump; - } - - } else { - chunks = [{ - stride: [aud.length, 0, 0], - input_features: (await this.processor(aud)).input_features, - is_last: true - }] - } - - // Generate for each set of input features - for (const chunk of chunks) { - generation_config.num_frames = Math.floor(chunk.stride[0] / hop_length); - - // NOTE: doing sequentially for now - const data = await this.model.generate({ - inputs: chunk.input_features, - ...generation_config - }); - - // TODO: Right now we only get top beam - if (return_timestamps === 'word') { - // @ts-expect-error TS2339 - chunk.tokens = data.sequences.tolist()[0]; - // @ts-expect-error TS2339 - chunk.token_timestamps = data.token_timestamps.tolist()[0].map( - (/** @type {number} */ x) => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.round)(x, 2) - ); - - } else { - chunk.tokens = (/** @type {Tensor} */(data))[0].tolist(); - } - - // convert stride to seconds - chunk.stride = chunk.stride.map(x => x / sampling_rate); - } - - // Merge text chunks - // @ts-ignore - const [full_text, optional] = this.tokenizer._decode_asr(chunks, { - time_precision, return_timestamps, force_full_sequences - }); - - toReturn.push({ text: full_text, ...optional }) - } - return single ? toReturn[0] : toReturn; + } + /** + * Encode/tokenize the given text(s). + * @template {string|string[]} TText + * @template {boolean} [TReturnTensor=true] + * @param {TText} text The text to tokenize. + * @param {TokenizerCallOptions} [options] Additional tokenization options. + * @returns {BatchEncoding>} Object to be passed to the model. + */ + _call(text, options = {}) { + const { text_pair = null, add_special_tokens = true, padding = false, return_token_type_ids = null } = options; + let { truncation = null, max_length = null } = options; + const return_tensor = ( + /** @type {TReturnTensor} */ + options.return_tensor ?? true + ); + const isBatched = Array.isArray(text); + let encodedTokens; + if (isBatched) { + if (text.length === 0) { + throw Error("text array must be non-empty"); + } + if (text_pair !== null) { + if (!Array.isArray(text_pair)) { + throw Error("text_pair must also be an array"); + } else if (text.length !== text_pair.length) { + throw Error("text and text_pair must have the same length"); + } + encodedTokens = text.map( + (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids }) + ); + } else { + encodedTokens = text.map((x) => this._encode_plus(x, { add_special_tokens, return_token_type_ids })); + } + } else { + if (text === null || text === void 0) { + throw Error("text may not be null or undefined"); + } + if (Array.isArray(text_pair)) { + throw Error( + "When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array)." + ); + } + encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })]; + } + if (max_length === null) { + max_length = this.model_max_length; + } else if (truncation === null) { + if (padding === true) { + logger.warn( + "`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`." + ); + max_length = this.model_max_length; + } else if (padding === false) { + logger.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." + ); + truncation = true; + } } - - /** - * @type {AutomaticSpeechRecognitionPipelineCallback} - * @private - */ - async _call_moonshine(audio, kwargs) { - const single = !Array.isArray(audio); - if (single) { - audio = [/** @type {AudioInput} */ (audio)]; - } - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - const preparedAudios = await prepareAudios(audio, sampling_rate); - const toReturn = []; - for (const aud of preparedAudios) { - const inputs = await this.processor(aud); - - // According to the [paper](https://huggingface.co/papers/2410.15608): - // "We use greedy decoding, with a heuristic limit of 6 output tokens - // per second of audio to avoid repeated output sequences." - const max_new_tokens = Math.floor(aud.length / sampling_rate) * 6; - const outputs = await this.model.generate({ max_new_tokens, ...kwargs, ...inputs }); - - const text = this.processor.batch_decode(/** @type {Tensor} */(outputs), { skip_special_tokens: true })[0]; - toReturn.push({ text }); - } - return single ? toReturn[0] : toReturn; - } - -} - -/** - * @typedef {Object} ImageToTextSingle - * @property {string} generated_text The generated text. - * @typedef {ImageToTextSingle[]} ImageToTextOutput - * - * @callback ImageToTextPipelineCallback Assign labels to the image(s) passed as inputs. - * @param {ImagePipelineInputs} texts The images to be captioned. - * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} An object (or array of objects) containing the generated text(s). - * - * @typedef {TextImagePipelineConstructorArgs & ImageToTextPipelineCallback & Disposable} ImageToTextPipelineType - */ - -/** - * Image To Text pipeline using a `AutoModelForVision2Seq`. This pipeline predicts a caption for a given image. - * - * **Example:** Generate a caption for an image w/ `Xenova/vit-gpt2-image-captioning`. - * ```javascript - * const captioner = await pipeline('image-to-text', 'Xenova/vit-gpt2-image-captioning'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; - * const output = await captioner(url); - * // [{ generated_text: 'a cat laying on a couch with another cat' }] - * ``` - * - * **Example:** Optical Character Recognition (OCR) w/ `Xenova/trocr-small-handwritten`. - * ```javascript - * const captioner = await pipeline('image-to-text', 'Xenova/trocr-small-handwritten'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/handwriting.jpg'; - * const output = await captioner(url); - * // [{ generated_text: 'Mr. Brown commented icily.' }] - * ``` - */ -class ImageToTextPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ (Pipeline)) { - - /** - * Create a new ImageToTextPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - - /** @type {ImageToTextPipelineCallback} */ - async _call(images, generate_kwargs = {}) { - - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - - const { pixel_values } = await this.processor(preparedImages); - - const toReturn = []; - for (const batch of pixel_values) { - batch.dims = [1, ...batch.dims] - const output = await this.model.generate({ inputs: batch, ...generate_kwargs }); - const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output), { - skip_special_tokens: true, - }).map(x => ({ generated_text: x.trim() })) - toReturn.push(decoded); - } - - return isBatched ? toReturn : toReturn[0]; - } -} - -/** - * @typedef {Object} ImageClassificationSingle - * @property {string} label The label identified by the model. - * @property {number} score The score attributed by the model for that label. - * @typedef {ImageClassificationSingle[]} ImageClassificationOutput - * - * @typedef {Object} ImageClassificationPipelineOptions Parameters specific to image classification pipelines. - * @property {number} [top_k=1] The number of top labels that will be returned by the pipeline. - * - * @callback ImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs. - * @param {ImagePipelineInputs} images The input images(s) to be classified. - * @param {ImageClassificationPipelineOptions} [options] The options to use for image classification. - * @returns {Promise} An array or object containing the predicted labels and scores. - * - * @typedef {ImagePipelineConstructorArgs & ImageClassificationPipelineCallback & Disposable} ImageClassificationPipelineType - */ - -/** - * Image classification pipeline using any `AutoModelForImageClassification`. - * This pipeline predicts the class of an image. - * - * **Example:** Classify an image. - * ```javascript - * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; - * const output = await classifier(url); - * // [ - * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, - * // ] - * ``` - * - * **Example:** Classify an image and return top `n` classes. - * ```javascript - * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; - * const output = await classifier(url, { top_k: 3 }); - * // [ - * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, - * // { label: 'tiger cat', score: 0.3634825646877289 }, - * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 }, - * // ] - * ``` - * - * **Example:** Classify an image and return all classes. - * ```javascript - * const classifier = await pipeline('image-classification', 'Xenova/vit-base-patch16-224'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; - * const output = await classifier(url, { top_k: 0 }); - * // [ - * // { label: 'tiger, Panthera tigris', score: 0.632695734500885 }, - * // { label: 'tiger cat', score: 0.3634825646877289 }, - * // { label: 'lion, king of beasts, Panthera leo', score: 0.00045060308184474707 }, - * // { label: 'jaguar, panther, Panthera onca, Felis onca', score: 0.00035465499968267977 }, - * // ... - * // ] - * ``` - */ -class ImageClassificationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ (Pipeline)) { - - /** - * Create a new ImageClassificationPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + if (padding === true) { + max_length = Math.min(max(encodedTokens.map((x) => x.input_ids.length))[0], max_length ?? Infinity); } - - /** @type {ImageClassificationPipelineCallback} */ - async _call(images, { - top_k = 5 - } = {}) { - - const preparedImages = await prepareImages(images); - - const { pixel_values } = await this.processor(preparedImages); - const output = await this.model({ pixel_values }); - - // @ts-expect-error TS2339 - const id2label = this.model.config.id2label; - - /** @type {ImageClassificationOutput[]} */ - const toReturn = []; - for (const batch of output.logits) { - const scores = await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk)(new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( - 'float32', - (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(batch.data), - batch.dims, - ), top_k); - - const values = scores[0].tolist(); - const indices = scores[1].tolist(); - - const vals = indices.map((x, i) => ({ - label: /** @type {string} */ (id2label ? id2label[x] : `LABEL_${x}`), - score: /** @type {number} */ (values[i]), - })); - toReturn.push(vals); - } - - return Array.isArray(images) ? toReturn : toReturn[0]; - } - -} - -/** - * @typedef {Object} ImageSegmentationPipelineOutput - * @property {string|null} label The label of the segment. - * @property {number|null} score The score of the segment. - * @property {RawImage} mask The mask of the segment. - * - * @typedef {Object} ImageSegmentationPipelineOptions Parameters specific to image segmentation pipelines. - * @property {number} [threshold=0.5] Probability threshold to filter out predicted masks. - * @property {number} [mask_threshold=0.5] Threshold to use when turning the predicted masks into binary values. - * @property {number} [overlap_mask_area_threshold=0.8] Mask overlap threshold to eliminate small, disconnected segments. - * @property {null|string} [subtask=null] Segmentation task to be performed. One of [`panoptic`, `instance`, and `semantic`], - * depending on model capabilities. If not set, the pipeline will attempt to resolve (in that order). - * @property {number[]} [label_ids_to_fuse=null] List of label ids to fuse. If not set, do not fuse any labels. - * @property {number[][]} [target_sizes=null] List of target sizes for the input images. If not set, use the original image sizes. - * - * @callback ImageSegmentationPipelineCallback Segment the input images. - * @param {ImagePipelineInputs} images The input images. - * @param {ImageSegmentationPipelineOptions} [options] The options to use for image segmentation. - * @returns {Promise} The annotated segments. - * - * @typedef {ImagePipelineConstructorArgs & ImageSegmentationPipelineCallback & Disposable} ImageSegmentationPipelineType - */ - -/** - * Image segmentation pipeline using any `AutoModelForXXXSegmentation`. - * This pipeline predicts masks of objects and their classes. - * - * **Example:** Perform image segmentation with `Xenova/detr-resnet-50-panoptic`. - * ```javascript - * const segmenter = await pipeline('image-segmentation', 'Xenova/detr-resnet-50-panoptic'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; - * const output = await segmenter(url); - * // [ - * // { label: 'remote', score: 0.9984649419784546, mask: RawImage { ... } }, - * // { label: 'cat', score: 0.9994316101074219, mask: RawImage { ... } } - * // ] - * ``` - */ -class ImageSegmentationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ (Pipeline)) { - /** - * Create a new ImageSegmentationPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - - this.subtasks_mapping = { - // Mapping of subtasks to their corresponding post-processing function names. - panoptic: 'post_process_panoptic_segmentation', - instance: 'post_process_instance_segmentation', - semantic: 'post_process_semantic_segmentation' + max_length = Math.min(max_length, this.model_max_length ?? Infinity); + if (padding || truncation) { + for (let i = 0; i < encodedTokens.length; ++i) { + if (encodedTokens[i].input_ids.length === max_length) { + continue; + } else if (encodedTokens[i].input_ids.length > max_length) { + if (truncation) { + truncateHelper(encodedTokens[i], max_length); + } + } else { + if (padding) { + padHelper( + encodedTokens[i], + max_length, + (key) => key === "input_ids" ? this.pad_token_id : 0, + this.padding_side + ); + } } + } } - - /** @type {ImageSegmentationPipelineCallback} */ - async _call(images, { - threshold = 0.5, - mask_threshold = 0.5, - overlap_mask_area_threshold = 0.8, - label_ids_to_fuse = null, - target_sizes = null, - subtask = null, - } = {}) { - const isBatched = Array.isArray(images); - - if (isBatched && images.length !== 1) { - throw Error("Image segmentation pipeline currently only supports a batch size of 1."); - } - - const preparedImages = await prepareImages(images); - const imageSizes = preparedImages.map(x => [x.height, x.width]); - - const inputs = await this.processor(preparedImages); - - const { inputNames, outputNames } = this.model.sessions['model']; - if (!inputNames.includes('pixel_values')) { - if (inputNames.length !== 1) { - throw Error(`Expected a single input name, but got ${inputNames.length} inputs: ${inputNames}.`); - } - - const newName = inputNames[0]; - if (newName in inputs) { - throw Error(`Input name ${newName} already exists in the inputs.`); - } - // To ensure compatibility with certain background-removal models, - // we may need to perform a mapping of input to output names - inputs[newName] = inputs.pixel_values; - } - - const output = await this.model(inputs); - - let fn = null; - if (subtask !== null) { - fn = this.subtasks_mapping[subtask]; - } else if (this.processor.image_processor) { - for (const [task, func] of Object.entries(this.subtasks_mapping)) { - if (func in this.processor.image_processor) { - fn = this.processor.image_processor[func].bind(this.processor.image_processor); - subtask = task; - break; - } + const result = {}; + if (return_tensor) { + if (!(padding && truncation)) { + if (encodedTokens.some((x) => { + for (const key of Object.keys(x)) { + if (x[key].length !== encodedTokens[0][key]?.length) { + return true; } + } + return false; + })) { + 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." + ); } - - // @ts-expect-error TS2339 - const id2label = this.model.config.id2label; - - /** @type {ImageSegmentationPipelineOutput[]} */ - const annotation = []; - if (!subtask) { - // We define an epsilon to safeguard against numerical/precision issues when detecting - // the normalization mode of the output (i.e., sigmoid already applied, or not). - // See https://github.com/microsoft/onnxruntime/issues/23943 for more information. - const epsilon = 1e-5; - - // Perform standard image segmentation - const result = output[outputNames[0]]; - for (let i = 0; i < imageSizes.length; ++i) { - const size = imageSizes[i]; - const item = result[i]; - if (item.data.some(x => x < -epsilon || x > 1 + epsilon)) { - item.sigmoid_(); - } - const mask = await _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.fromTensor(item.mul_(255).to('uint8')).resize(size[1], size[0]); - annotation.push({ - label: null, - score: null, - mask - }); - } - } else if (subtask === 'panoptic' || subtask === 'instance') { - const processed = fn( - output, - threshold, - mask_threshold, - overlap_mask_area_threshold, - label_ids_to_fuse, - target_sizes ?? imageSizes, // TODO FIX? - )[0]; - - const segmentation = processed.segmentation; - - for (const segment of processed.segments_info) { - const maskData = new Uint8ClampedArray(segmentation.data.length); - for (let i = 0; i < segmentation.data.length; ++i) { - if (segmentation.data[i] === segment.id) { - maskData[i] = 255; - } - } - - const mask = new _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1) - - annotation.push({ - score: segment.score, - label: id2label[segment.label_id], - mask: mask - }) - } - - } else if (subtask === 'semantic') { - const { segmentation, labels } = fn(output, target_sizes ?? imageSizes)[0]; - - for (const label of labels) { - const maskData = new Uint8ClampedArray(segmentation.data.length); - for (let i = 0; i < segmentation.data.length; ++i) { - if (segmentation.data[i] === label) { - maskData[i] = 255; - } - } - - const mask = new _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); - - annotation.push({ - score: null, - label: id2label[label], - mask: mask - }); - } - } else { - throw Error(`Subtask ${subtask} not supported.`); - } - - return annotation; - } -} - - -/** - * @typedef {Object} BackgroundRemovalPipelineOptions Parameters specific to image segmentation pipelines. - * - * @callback BackgroundRemovalPipelineCallback Segment the input images. - * @param {ImagePipelineInputs} images The input images. - * @param {BackgroundRemovalPipelineOptions} [options] The options to use for image segmentation. - * @returns {Promise} The images with the background removed. - * - * @typedef {ImagePipelineConstructorArgs & BackgroundRemovalPipelineCallback & Disposable} BackgroundRemovalPipelineType - */ - -/** - * Background removal pipeline using certain `AutoModelForXXXSegmentation`. - * This pipeline removes the backgrounds of images. - * - * **Example:** Perform background removal with `Xenova/modnet`. - * ```javascript - * const segmenter = await pipeline('background-removal', 'Xenova/modnet'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/portrait-of-woman_small.jpg'; - * const output = await segmenter(url); - * // [ - * // RawImage { data: Uint8ClampedArray(648000) [ ... ], width: 360, height: 450, channels: 4 } - * // ] - * ``` - */ -class BackgroundRemovalPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => BackgroundRemovalPipelineType} */ (/** @type {any} */(ImageSegmentationPipeline))) { - /** - * Create a new BackgroundRemovalPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + } + const dims = [encodedTokens.length, encodedTokens[0].input_ids.length]; + for (const key of Object.keys(encodedTokens[0])) { + result[key] = new Tensor3( + "int64", + BigInt64Array.from(encodedTokens.flatMap((x) => x[key]).map(BigInt)), + dims + ); + } + } else { + for (const key of Object.keys(encodedTokens[0])) { + result[key] = encodedTokens.map((x) => x[key]); + } + if (!isBatched) { + for (const key of Object.keys(result)) { + result[key] = result[key][0]; + } + } + } + return ( + /** @type {BatchEncoding>} */ + result + ); + } + /** + * Encodes a single text using the preprocessor pipeline of the tokenizer. + * + * @param {string|null} text The text to encode. + * @returns {string[]|null} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + return this._tokenizer.encode(text).tokens; + } + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {string|null} [options.text_pair=null] The optional second text to encode. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean|null} [options.return_token_type_ids=null] Whether to return token_type_ids. + * @returns {{input_ids: number[], attention_mask: number[], token_type_ids?: number[]}} An object containing the encoded text. + * @private + */ + _encode_plus(text, { text_pair = null, add_special_tokens = true, return_token_type_ids = null } = {}) { + const { ids, attention_mask, token_type_ids } = this._tokenizer.encode(text, { + text_pair, + add_special_tokens, + return_token_type_ids: return_token_type_ids ?? this.return_token_type_ids + }); + return { + input_ids: ids, + attention_mask, + ...token_type_ids ? { token_type_ids } : {} + }; + } + /** + * Converts a string into a sequence of tokens. + * @param {string} text The sequence to be encoded. + * @param {Object} options An optional object containing the following properties: + * @param {string|null} [options.pair] A second sequence to be encoded with the first. + * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. + * @returns {string[]} The list of tokens. + */ + tokenize(text, { pair = null, add_special_tokens = false } = {}) { + return this._tokenizer.tokenize(text, { text_pair: pair, add_special_tokens }); + } + /** + * Encodes a single text or a pair of texts using the model's tokenizer. + * + * @param {string} text The text to encode. + * @param {Object} options An optional object containing the following properties: + * @param {string|null} [options.text_pair=null] The optional second text to encode. + * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. + * @param {boolean|null} [options.return_token_type_ids=null] Whether to return token_type_ids. + * @returns {number[]} An array of token IDs representing the encoded text(s). + */ + encode(text, { text_pair = null, add_special_tokens = true, return_token_type_ids = null } = {}) { + return this._tokenizer.encode(text, { + text_pair, + add_special_tokens, + return_token_type_ids + }).ids; + } + /** + * Decode a batch of tokenized sequences. + * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. + * @param {Object} decode_args (Optional) Object with decoding arguments. + * @returns {string[]} List of decoded sequences. + */ + batch_decode(batch, decode_args = {}) { + if (batch instanceof Tensor3) { + batch = batch.tolist(); } - - /** @type {BackgroundRemovalPipelineCallback} */ - async _call(images, options = {}) { - const isBatched = Array.isArray(images); - - if (isBatched && images.length !== 1) { - throw Error("Background removal pipeline currently only supports a batch size of 1."); - } - - const preparedImages = await prepareImages(images); - - // @ts-expect-error TS2339 - const masks = await super._call(images, options); - const result = preparedImages.map((img, i) => { - const cloned = img.clone(); - cloned.putAlpha(masks[i].mask); - return cloned; - }); - - return result; + return batch.map((x) => this.decode(x, decode_args)); + } + /** + * Decodes a sequence of token IDs back to a string. + * + * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode. + * @param {Object} [decode_args={}] + * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. + * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuation and abbreviated forms are removed. + * + * @returns {string} The decoded string. + * @throws {Error} If `token_ids` is not a non-empty array of integers. + */ + decode(token_ids, decode_args = {}) { + if (token_ids instanceof Tensor3) { + token_ids = prepareTensorForDecode(token_ids); } -} - -/** - * @typedef {Object} ZeroShotImageClassificationOutput - * @property {string} label The label identified by the model. It is one of the suggested `candidate_label`. - * @property {number} score The score attributed by the model for that label (between 0 and 1). - * - * @typedef {Object} ZeroShotImageClassificationPipelineOptions Parameters specific to zero-shot image classification pipelines. - * @property {string} [hypothesis_template="This is a photo of {}"] The sentence used in conjunction with `candidate_labels` - * to attempt the image classification by replacing the placeholder with the candidate_labels. - * Then likelihood is estimated by using `logits_per_image`. - * - * @callback ZeroShotImageClassificationPipelineCallback Assign labels to the image(s) passed as inputs. - * @param {ImagePipelineInputs} images The input images. - * @param {string[]} candidate_labels The candidate labels for this image. - * @param {ZeroShotImageClassificationPipelineOptions} [options] The options to use for zero-shot image classification. - * @returns {Promise} An array of objects containing the predicted labels and scores. - * - * @typedef {TextImagePipelineConstructorArgs & ZeroShotImageClassificationPipelineCallback & Disposable} ZeroShotImageClassificationPipelineType - */ - -/** - * Zero shot image classification pipeline. This pipeline predicts the class of - * an image when you provide an image and a set of `candidate_labels`. - * - * **Example:** Zero shot image classification w/ `Xenova/clip-vit-base-patch32`. - * ```javascript - * const classifier = await pipeline('zero-shot-image-classification', 'Xenova/clip-vit-base-patch32'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/tiger.jpg'; - * const output = await classifier(url, ['tiger', 'horse', 'dog']); - * // [ - * // { score: 0.9993917942047119, label: 'tiger' }, - * // { score: 0.0003519294841680676, label: 'horse' }, - * // { score: 0.0002562698791734874, label: 'dog' } - * // ] - * ``` - */ -class ZeroShotImageClassificationPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ (Pipeline)) { - /** - * Create a new ZeroShotImageClassificationPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + if (!Array.isArray(token_ids) || token_ids.length === 0 || !isIntegralNumber(token_ids[0])) { + throw Error("token_ids must be a non-empty array of integers."); } - - /** @type {ZeroShotImageClassificationPipelineCallback} */ - async _call(images, candidate_labels, { - hypothesis_template = "This is a photo of {}" - } = {}) { - - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - - // Insert label into hypothesis template - const texts = candidate_labels.map( - x => hypothesis_template.replace('{}', x) + return this.decode_single(token_ids, decode_args); + } + /** + * Decode a single list of token ids to a string. + * @param {number[]|bigint[]} token_ids List of token ids to decode + * @param {Object} decode_args Optional arguments for decoding + * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding + * @param {boolean|null} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. + * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. + * @returns {string} The decoded string + */ + decode_single(token_ids, { skip_special_tokens = false, clean_up_tokenization_spaces = null }) { + return this._tokenizer.decode(token_ids, { + skip_special_tokens, + clean_up_tokenization_spaces + }); + } + /** + * Retrieve the chat template string used for tokenizing chat messages. This template is used + * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat + * template for better generation tracking. + * + * @param {Object} options An optional object containing the following properties: + * @param {string|null} [options.chat_template=null] + * A Jinja template or the name of a template to use for this conversion. + * It is usually not necessary to pass anything to this argument, + * as the model's template will be used by default. + * @param {Object[]} [options.tools=null] + * A list of tools (callable functions) that will be accessible to the model. If the template does not + * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, + * giving the name, description and argument types for the tool. See our + * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) + * for more information. + * @returns {string} The chat template string. + */ + get_chat_template({ chat_template = null, tools = null } = {}) { + if (this.chat_template && typeof this.chat_template === "object") { + const template_dict = this.chat_template; + if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) { + chat_template = template_dict[chat_template]; + } else if (chat_template === null) { + if (tools !== null && "tool_use" in template_dict) { + chat_template = template_dict["tool_use"]; + } else if ("default" in template_dict) { + chat_template = template_dict["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(template_dict).sort()}.` + ); + } + } + } else if (chat_template === null) { + if (this.chat_template) { + chat_template = this.chat_template; + } else { + throw Error( + "Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating" ); - - // Run tokenization - const text_inputs = this.tokenizer(texts, { - padding: this.model.config.model_type === 'siglip' ? 'max_length' : true, - truncation: true, - }); - - // Run processor - const { pixel_values } = await this.processor(preparedImages); - - // Run model with both text and pixel inputs - const output = await this.model({ ...text_inputs, pixel_values }); - - const function_to_apply = - this.model.config.model_type === 'siglip' - ? batch => batch.sigmoid().data - : batch => (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_6__.softmax)(batch.data); - - // Compare each image with each candidate label - const toReturn = []; - for (const batch of output.logits_per_image) { - // Compute softmax per image - const probs = function_to_apply(batch); - - const result = [...probs].map((x, i) => ({ - score: x, - label: candidate_labels[i] - })); - result.sort((a, b) => b.score - a.score); // sort by score in descending order - toReturn.push(result); - } - - return isBatched ? toReturn : toReturn[0]; - } -} - - -/** - * @typedef {Object} ObjectDetectionPipelineSingle - * @property {string} label The class label identified by the model. - * @property {number} score The score attributed by the model for that label. - * @property {BoundingBox} box The bounding box of detected object in image's original size, or as a percentage if `percentage` is set to true. - * @typedef {ObjectDetectionPipelineSingle[]} ObjectDetectionPipelineOutput - * - * @typedef {Object} ObjectDetectionPipelineOptions Parameters specific to object detection pipelines. - * @property {number} [threshold=0.9] The threshold used to filter boxes by score. - * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false). - * - * @callback ObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs. - * @param {ImagePipelineInputs} images The input images. - * @param {ObjectDetectionPipelineOptions} [options] The options to use for object detection. - * @returns {Promise} A list of objects or a list of list of objects. - * - * @typedef {ImagePipelineConstructorArgs & ObjectDetectionPipelineCallback & Disposable} ObjectDetectionPipelineType - */ - -/** - * Object detection pipeline using any `AutoModelForObjectDetection`. - * This pipeline predicts bounding boxes of objects and their classes. - * - * **Example:** Run object-detection with `Xenova/detr-resnet-50`. - * ```javascript - * const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50'); - * const img = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; - * const output = await detector(img, { threshold: 0.9 }); - * // [{ - * // score: 0.9976370930671692, - * // label: "remote", - * // box: { xmin: 31, ymin: 68, xmax: 190, ymax: 118 } - * // }, - * // ... - * // { - * // score: 0.9984092116355896, - * // label: "cat", - * // box: { xmin: 331, ymin: 19, xmax: 649, ymax: 371 } - * // }] - * ``` - */ -class ObjectDetectionPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ (Pipeline)) { - - /** - * Create a new ObjectDetectionPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + } } - - /** @type {ObjectDetectionPipelineCallback} */ - async _call(images, { - threshold = 0.9, - percentage = false, - } = {}) { - - const isBatched = Array.isArray(images); - - if (isBatched && images.length !== 1) { - throw Error("Object detection pipeline currently only supports a batch size of 1."); + return chat_template; + } + /** + * Converts a list of message objects with `"role"` and `"content"` keys to a list of token + * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to + * determine the format and control tokens to use when converting. + * + * See the [chat templating guide](https://huggingface.co/docs/transformers/chat_templating) for more information. + * + * **Example:** Applying a chat template to a conversation. + * + * ```javascript + * import { AutoTokenizer } from "@huggingface/transformers"; + * + * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1"); + * + * const chat = [ + * { "role": "user", "content": "Hello, how are you?" }, + * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, + * { "role": "user", "content": "I'd like to show off how chat templating works!" }, + * ] + * + * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); + * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" + * + * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); + * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] + * ``` + * + * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys, + * representing the chat history so far. + * @template {boolean} [TTokenize=true] + * @template {boolean} [TReturnTensor=true] + * @template {boolean} [TReturnDict=true] + * @param {ApplyChatTemplateOptions} [options] Options controlling + * template rendering and tokenization. + * @returns {ApplyChatTemplateReturn} The tokenized output. + */ + apply_chat_template(conversation, options = ( + /** @type {ApplyChatTemplateOptions} */ + {} + )) { + let { + tools = null, + documents = null, + chat_template = null, + add_generation_prompt = false, + tokenize: tokenize2 = ( + /** @type {TTokenize} */ + true + ), + padding = false, + truncation = false, + max_length = null, + return_tensor = ( + /** @type {TReturnTensor} */ + true + ), + return_dict = ( + /** @type {TReturnDict} */ + true + ), + tokenizer_kwargs = {}, + ...kwargs + } = options; + chat_template = this.get_chat_template({ chat_template, tools }); + if (typeof chat_template !== "string") { + throw Error(`chat_template must be a string, but got ${typeof chat_template}`); + } + let compiledTemplate = this._compiled_template_cache.get(chat_template); + if (compiledTemplate === void 0) { + compiledTemplate = new Template(chat_template); + this._compiled_template_cache.set(chat_template, compiledTemplate); + } + const special_tokens_map = /* @__PURE__ */ Object.create(null); + for (const key of SPECIAL_TOKEN_ATTRIBUTES) { + const value = getTokenFromConfig(this.config, key); + if (value) { + special_tokens_map[key] = value; + } + } + const rendered = compiledTemplate.render({ + messages: conversation, + add_generation_prompt, + tools, + documents, + ...special_tokens_map, + ...kwargs + }); + if (tokenize2) { + const out = this._call(rendered, { + add_special_tokens: false, + padding, + truncation, + max_length, + return_tensor, + ...tokenizer_kwargs + }); + return ( + /** @type {ApplyChatTemplateReturn} */ + return_dict ? out : out.input_ids + ); + } + return ( + /** @type {ApplyChatTemplateReturn} */ + rendered + ); + } +}; +function _build_translation_inputs(self2, raw_inputs, tokenizer_options, generate_kwargs) { + if (!("language_codes" in self2) || !Array.isArray(self2.language_codes)) { + throw new Error( + "Tokenizer must have `language_codes` attribute set and it should be an array of language ids." + ); + } + if (!("languageRegex" in self2) || !(self2.languageRegex instanceof RegExp)) { + throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression."); + } + if (!("lang_to_token" in self2) || typeof self2.lang_to_token !== "function") { + throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function."); + } + const src_lang_token = generate_kwargs.src_lang; + const tgt_lang_token = generate_kwargs.tgt_lang; + if (!self2.language_codes.includes(tgt_lang_token)) { + throw new Error( + `Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}` + ); + } + if (src_lang_token !== void 0) { + if (!self2.language_codes.includes(src_lang_token)) { + throw new Error( + `Source language code "${src_lang_token}" is not valid. Must be one of: {${self2.language_codes.join(", ")}}` + ); + } + const post_processor_config = self2._tokenizer.post_processor?.config; + if (post_processor_config && "single" in post_processor_config) { + for (const item of post_processor_config.single) { + if ("SpecialToken" in item && self2.languageRegex.test(item.SpecialToken.id)) { + item.SpecialToken.id = self2.lang_to_token(src_lang_token); + break; } - const preparedImages = await prepareImages(images); - - const imageSizes = percentage ? null : preparedImages.map(x => [x.height, x.width]); - - const { pixel_values, pixel_mask } = await this.processor(preparedImages); - const output = await this.model({ pixel_values, pixel_mask }); - - // @ts-ignore - const processed = this.processor.image_processor.post_process_object_detection(output, threshold, imageSizes); - - // Add labels - // @ts-expect-error TS2339 - const id2label = this.model.config.id2label; - - // Format output - /** @type {ObjectDetectionPipelineOutput[]} */ - const result = processed.map(batch => ( - batch.boxes.map((box, i) => ({ - score: batch.scores[i], - label: id2label[batch.classes[i]], - box: get_bounding_box(box, !percentage), - })) - )) - - return isBatched ? result : result[0]; - } -} - - -/** - * @typedef {Object} ZeroShotObjectDetectionOutput - * @property {string} label Text query corresponding to the found object. - * @property {number} score Score corresponding to the object (between 0 and 1). - * @property {BoundingBox} box Bounding box of the detected object in image's original size, or as a percentage if `percentage` is set to true. - * - * @typedef {Object} ZeroShotObjectDetectionPipelineOptions Parameters specific to zero-shot object detection pipelines. - * @property {number} [threshold=0.1] The probability necessary to make a prediction. - * @property {number} [top_k=null] The number of top predictions that will be returned by the pipeline. - * If the provided number is `null` or higher than the number of predictions available, it will default - * to the number of predictions. - * @property {boolean} [percentage=false] Whether to return the boxes coordinates in percentage (true) or in pixels (false). - * - * @callback ZeroShotObjectDetectionPipelineCallback Detect objects (bounding boxes & classes) in the image(s) passed as inputs. - * @param {ImagePipelineInputs} images The input images. - * @param {string[]} candidate_labels What the model should recognize in the image. - * @param {ZeroShotObjectDetectionPipelineOptions} [options] The options to use for zero-shot object detection. - * @returns {Promise} An array of objects containing the predicted labels, scores, and bounding boxes. - * - * @typedef {TextImagePipelineConstructorArgs & ZeroShotObjectDetectionPipelineCallback & Disposable} ZeroShotObjectDetectionPipelineType - */ - -/** - * Zero-shot object detection pipeline. This pipeline predicts bounding boxes of - * objects when you provide an image and a set of `candidate_labels`. - * - * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32`. - * ```javascript - * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/astronaut.png'; - * const candidate_labels = ['human face', 'rocket', 'helmet', 'american flag']; - * const output = await detector(url, candidate_labels); - * // [ - * // { - * // score: 0.24392342567443848, - * // label: 'human face', - * // box: { xmin: 180, ymin: 67, xmax: 274, ymax: 175 } - * // }, - * // { - * // score: 0.15129457414150238, - * // label: 'american flag', - * // box: { xmin: 0, ymin: 4, xmax: 106, ymax: 513 } - * // }, - * // { - * // score: 0.13649864494800568, - * // label: 'helmet', - * // box: { xmin: 277, ymin: 337, xmax: 511, ymax: 511 } - * // }, - * // { - * // score: 0.10262022167444229, - * // label: 'rocket', - * // box: { xmin: 352, ymin: -1, xmax: 463, ymax: 287 } - * // } - * // ] - * ``` - * - * **Example:** Zero-shot object detection w/ `Xenova/owlvit-base-patch32` (returning top 4 matches and setting a threshold). - * ```javascript - * const detector = await pipeline('zero-shot-object-detection', 'Xenova/owlvit-base-patch32'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/beach.png'; - * const candidate_labels = ['hat', 'book', 'sunglasses', 'camera']; - * const output = await detector(url, candidate_labels, { top_k: 4, threshold: 0.05 }); - * // [ - * // { - * // score: 0.1606510728597641, - * // label: 'sunglasses', - * // box: { xmin: 347, ymin: 229, xmax: 429, ymax: 264 } - * // }, - * // { - * // score: 0.08935828506946564, - * // label: 'hat', - * // box: { xmin: 38, ymin: 174, xmax: 258, ymax: 364 } - * // }, - * // { - * // score: 0.08530698716640472, - * // label: 'camera', - * // box: { xmin: 187, ymin: 350, xmax: 260, ymax: 411 } - * // }, - * // { - * // score: 0.08349756896495819, - * // label: 'book', - * // box: { xmin: 261, ymin: 280, xmax: 494, ymax: 425 } - * // } - * // ] - * ``` - */ -class ZeroShotObjectDetectionPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ (Pipeline)) { - - /** - * Create a new ZeroShotObjectDetectionPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); + } } + } + generate_kwargs.forced_bos_token_id = self2._tokenizer.token_to_id(self2.lang_to_token(tgt_lang_token)); + return self2._call(raw_inputs, tokenizer_options); +} + +// src/models/tokenizers.js +var tokenizers_exports = {}; +__export(tokenizers_exports, { + AlbertTokenizer: () => AlbertTokenizer, + AutoTokenizer: () => AutoTokenizer, + BartTokenizer: () => BartTokenizer, + BertTokenizer: () => BertTokenizer, + BlenderbotSmallTokenizer: () => BlenderbotSmallTokenizer, + BlenderbotTokenizer: () => BlenderbotTokenizer, + BloomTokenizer: () => BloomTokenizer, + CLIPTokenizer: () => CLIPTokenizer, + CamembertTokenizer: () => CamembertTokenizer, + CodeGenTokenizer: () => CodeGenTokenizer, + CodeLlamaTokenizer: () => CodeLlamaTokenizer, + CohereAsrTokenizer: () => CohereAsrTokenizer, + CohereTokenizer: () => CohereTokenizer, + ConvBertTokenizer: () => ConvBertTokenizer, + DebertaTokenizer: () => DebertaTokenizer, + DebertaV2Tokenizer: () => DebertaV2Tokenizer, + DistilBertTokenizer: () => DistilBertTokenizer, + ElectraTokenizer: () => ElectraTokenizer, + EsmTokenizer: () => EsmTokenizer, + FalconTokenizer: () => FalconTokenizer, + GPT2Tokenizer: () => GPT2Tokenizer, + GPTNeoXTokenizer: () => GPTNeoXTokenizer, + GemmaTokenizer: () => GemmaTokenizer, + HerbertTokenizer: () => HerbertTokenizer, + LlamaTokenizer: () => LlamaTokenizer, + M2M100Tokenizer: () => M2M100Tokenizer, + MBart50Tokenizer: () => MBart50Tokenizer, + MBartTokenizer: () => MBartTokenizer, + MPNetTokenizer: () => MPNetTokenizer, + MarianTokenizer: () => MarianTokenizer, + MgpstrTokenizer: () => MgpstrTokenizer, + MobileBertTokenizer: () => MobileBertTokenizer, + NllbTokenizer: () => NllbTokenizer, + NougatTokenizer: () => NougatTokenizer, + PreTrainedTokenizer: () => PreTrainedTokenizer, + Qwen2Tokenizer: () => Qwen2Tokenizer, + RoFormerTokenizer: () => RoFormerTokenizer, + RobertaTokenizer: () => RobertaTokenizer, + SiglipTokenizer: () => SiglipTokenizer, + SpeechT5Tokenizer: () => SpeechT5Tokenizer, + SqueezeBertTokenizer: () => SqueezeBertTokenizer, + T5Tokenizer: () => T5Tokenizer, + TokenizersBackend: () => PreTrainedTokenizer, + VitsTokenizer: () => VitsTokenizer, + Wav2Vec2CTCTokenizer: () => Wav2Vec2CTCTokenizer, + WhisperTokenizer: () => WhisperTokenizer, + XLMRobertaTokenizer: () => XLMRobertaTokenizer, + XLMTokenizer: () => XLMTokenizer +}); - /** @type {ZeroShotObjectDetectionPipelineCallback} */ - async _call(images, candidate_labels, { - threshold = 0.1, - top_k = null, - percentage = false, - } = {}) { - - const isBatched = Array.isArray(images); - const preparedImages = await prepareImages(images); - - // Run tokenization - const text_inputs = this.tokenizer(candidate_labels, { - padding: true, - truncation: true, - }); - - // Run processor - const model_inputs = await this.processor(preparedImages); - - // Since non-maximum suppression is performed for exporting, we need to - // process each image separately. For more information, see: - // https://github.com/huggingface/optimum/blob/e3b7efb1257c011db907ef40ab340e795cc5684c/optimum/exporters/onnx/model_configs.py#L1028-L1032 - const toReturn = []; - for (let i = 0; i < preparedImages.length; ++i) { - const image = preparedImages[i]; - const imageSize = percentage ? null : [[image.height, image.width]]; - const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0); - - // Run model with both text and pixel inputs - const output = await this.model({ ...text_inputs, pixel_values }); - - let result; - if ('post_process_grounded_object_detection' in this.processor) { - // @ts-ignore - const processed = this.processor.post_process_grounded_object_detection( - output, - text_inputs.input_ids, - { - // TODO: support separate threshold values - box_threshold: threshold, - text_threshold: threshold, - target_sizes: imageSize, - }, - )[0]; - result = processed.boxes.map((box, i) => ({ - score: processed.scores[i], - label: processed.labels[i], - box: get_bounding_box(box, !percentage), - })) - } else { - // @ts-ignore - const processed = this.processor.image_processor.post_process_object_detection(output, threshold, imageSize, true)[0]; - result = processed.boxes.map((box, i) => ({ - score: processed.scores[i], - label: candidate_labels[processed.classes[i]], - box: get_bounding_box(box, !percentage), - })) - } - result.sort((a, b) => b.score - a.score); - - if (top_k !== null) { - result = result.slice(0, top_k); - } - toReturn.push(result) - } - - return isBatched ? toReturn : toReturn[0]; - } -} - -/** - * @typedef {Object} DocumentQuestionAnsweringSingle - * @property {string} answer The generated text. - * @typedef {DocumentQuestionAnsweringSingle[]} DocumentQuestionAnsweringOutput - * - * @callback DocumentQuestionAnsweringPipelineCallback Answer the question given as input by using the document. - * @param {ImageInput} image The image of the document to use. - * @param {string} question A question to ask of the document. - * @param {Partial} [options] Additional keyword arguments to pass along to the generate method of the model. - * @returns {Promise} An object (or array of objects) containing the answer(s). - * - * @typedef {TextImagePipelineConstructorArgs & DocumentQuestionAnsweringPipelineCallback & Disposable} DocumentQuestionAnsweringPipelineType - */ - -/** - * Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. - * The inputs/outputs are similar to the (extractive) question answering pipeline; however, - * the pipeline takes an image (and optional OCR'd words/boxes) as input instead of text context. - * - * **Example:** Answer questions about a document with `Xenova/donut-base-finetuned-docvqa`. - * ```javascript - * const qa_pipeline = await pipeline('document-question-answering', 'Xenova/donut-base-finetuned-docvqa'); - * const image = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/invoice.png'; - * const question = 'What is the invoice number?'; - * const output = await qa_pipeline(image, question); - * // [{ answer: 'us-001' }] - * ``` - */ -class DocumentQuestionAnsweringPipeline extends (/** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ (Pipeline)) { - - /** - * Create a new DocumentQuestionAnsweringPipeline. - * @param {TextImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } - - /** @type {DocumentQuestionAnsweringPipelineCallback} */ - async _call(image, question, generate_kwargs = {}) { - - // NOTE: For now, we only support a batch size of 1 - - // Preprocess image - const preparedImage = (await prepareImages(image))[0]; - const { pixel_values } = await this.processor(preparedImage); - - // Run tokenization - const task_prompt = `${question}`; - const decoder_input_ids = this.tokenizer(task_prompt, { - add_special_tokens: false, - padding: true, - truncation: true, - }).input_ids; - - // Run model - const output = await this.model.generate({ - inputs: pixel_values, - // @ts-expect-error TS2339 - max_length: this.model.config.decoder.max_position_embeddings, - decoder_input_ids, - ...generate_kwargs, - }); - - // Decode output - const decoded = this.tokenizer.batch_decode(/** @type {Tensor} */(output))[0]; - - // Parse answer - const match = decoded.match(/(.*?)<\/s_answer>/); - let answer = null; - if (match && match.length >= 2) { - answer = match[1].trim(); - } - return [{ answer }]; - } -} - - -/** - * @typedef {Object} VocoderOptions - * @property {PreTrainedModel} [vocoder] The vocoder used by the pipeline (if the model uses one). If not provided, use the default HifiGan vocoder. - * @typedef {TextAudioPipelineConstructorArgs & VocoderOptions} TextToAudioPipelineConstructorArgs - */ - -/** - * @typedef {Object} TextToAudioOutput - * @property {Float32Array} audio The generated audio waveform. - * @property {number} sampling_rate The sampling rate of the generated audio waveform. - * - * @typedef {Object} TextToAudioPipelineOptions Parameters specific to text-to-audio pipelines. - * @property {Tensor|Float32Array|string|URL} [speaker_embeddings=null] The speaker embeddings (if the model requires it). - * - * @callback TextToAudioPipelineCallback Generates speech/audio from the inputs. - * @param {string|string[]} texts The text(s) to generate. - * @param {TextToAudioPipelineOptions} options Parameters passed to the model generation/forward method. - * @returns {Promise} An object containing the generated audio and sampling rate. - * - * @typedef {TextToAudioPipelineConstructorArgs & TextToAudioPipelineCallback & Disposable} TextToAudioPipelineType - */ - -/** - * Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. - * This pipeline generates an audio file from an input text and optional other conditional inputs. - * - * **Example:** Generate audio from text with `Xenova/speecht5_tts`. - * ```javascript - * const synthesizer = await pipeline('text-to-speech', 'Xenova/speecht5_tts', { quantized: false }); - * const speaker_embeddings = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/speaker_embeddings.bin'; - * const out = await synthesizer('Hello, my dog is cute', { speaker_embeddings }); - * // RawAudio { - * // audio: Float32Array(26112) [-0.00005657337896991521, 0.00020583874720614403, ...], - * // sampling_rate: 16000 - * // } - * ``` - * - * You can then save the audio to a .wav file with the `wavefile` package: - * ```javascript - * import wavefile from 'wavefile'; - * import fs from 'fs'; - * - * const wav = new wavefile.WaveFile(); - * wav.fromScratch(1, out.sampling_rate, '32f', out.audio); - * fs.writeFileSync('out.wav', wav.toBuffer()); - * ``` - * - * **Example:** Multilingual speech generation with `Xenova/mms-tts-fra`. See [here](https://huggingface.co/models?pipeline_tag=text-to-speech&other=vits&sort=trending) for the full list of available languages (1107). - * ```javascript - * const synthesizer = await pipeline('text-to-speech', 'Xenova/mms-tts-fra'); - * const out = await synthesizer('Bonjour'); - * // RawAudio { - * // audio: Float32Array(23808) [-0.00037693005288019776, 0.0003325853613205254, ...], - * // sampling_rate: 16000 - * // } - * ``` - */ -class TextToAudioPipeline extends (/** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ (Pipeline)) { - DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan" - - /** - * Create a new TextToAudioPipeline. - * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - - // TODO: Find a better way for `pipeline` to set the default vocoder - this.vocoder = options.vocoder ?? null; - } +// src/models/albert/tokenization_albert.js +var AlbertTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; +// src/models/bart/tokenization_bart.js +var BartTokenizer = class extends PreTrainedTokenizer { +}; - /** @type {TextToAudioPipelineCallback} */ - async _call(text_inputs, { - speaker_embeddings = null, - } = {}) { +// src/models/bert/tokenization_bert.js +var BertTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - // If this.processor is not set, we are using a `AutoModelForTextToWaveform` model - if (this.processor) { - return this._call_text_to_spectrogram(text_inputs, { speaker_embeddings }); - } else { - return this._call_text_to_waveform(text_inputs); - } - } +// src/models/blenderbot_small/tokenization_blenderbot_small.js +var BlenderbotSmallTokenizer = class extends PreTrainedTokenizer { +}; - async _call_text_to_waveform(text_inputs) { +// src/models/blenderbot/tokenization_blenderbot.js +var BlenderbotTokenizer = class extends PreTrainedTokenizer { +}; - // Run tokenization - const inputs = this.tokenizer(text_inputs, { - padding: true, - truncation: true, - }); +// src/models/bloom/tokenization_bloom.js +var BloomTokenizer = class extends PreTrainedTokenizer { +}; - // Generate waveform - const { waveform } = await this.model(inputs); +// src/models/camembert/tokenization_camembert.js +var CamembertTokenizer = class extends PreTrainedTokenizer { +}; - // @ts-expect-error TS2339 - const sampling_rate = this.model.config.sampling_rate; - return new _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.RawAudio( - waveform.data, - sampling_rate, - ) - } +// src/models/clip/tokenization_clip.js +var CLIPTokenizer = class extends PreTrainedTokenizer { +}; - async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) { +// src/models/code_llama/tokenization_code_llama.js +var CodeLlamaTokenizer = class extends PreTrainedTokenizer { +}; - // Load vocoder, if not provided - if (!this.vocoder) { - console.log('No vocoder specified, using default HifiGan vocoder.'); - this.vocoder = await _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: 'fp32' }); - } +// src/models/codegen/tokenization_codegen.js +var CodeGenTokenizer = class extends PreTrainedTokenizer { +}; - // Load speaker embeddings as Float32Array from path/URL - if (typeof speaker_embeddings === 'string' || speaker_embeddings instanceof URL) { - // Load from URL with fetch - speaker_embeddings = new Float32Array( - await (await fetch(speaker_embeddings)).arrayBuffer() - ); - } +// src/models/cohere/tokenization_cohere.js +var CohereTokenizer = class extends PreTrainedTokenizer { +}; - if (speaker_embeddings instanceof Float32Array) { - speaker_embeddings = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor( - 'float32', - speaker_embeddings, - [1, speaker_embeddings.length] - ) - } else if (!(speaker_embeddings instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor)) { - throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.") - } +// src/models/cohere_asr/tokenization_cohere_asr.js +var CohereAsrTokenizer = class extends PreTrainedTokenizer { +}; - // Run tokenization - const { input_ids } = this.tokenizer(text_inputs, { - padding: true, - truncation: true, - }); +// src/models/convbert/tokenization_convbert.js +var ConvBertTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - // NOTE: At this point, we are guaranteed that `speaker_embeddings` is a `Tensor` - // @ts-ignore - const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder }); +// src/models/deberta_v2/tokenization_deberta_v2.js +var DebertaV2Tokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - const sampling_rate = this.processor.feature_extractor.config.sampling_rate; - return new _utils_audio_js__WEBPACK_IMPORTED_MODULE_7__.RawAudio( - waveform.data, - sampling_rate, - ) - } -} +// src/models/deberta/tokenization_deberta.js +var DebertaTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; -/** - * @callback ImageToImagePipelineCallback Transform the image(s) passed as inputs. - * @param {ImagePipelineInputs} images The images to transform. - * @returns {Promise} The transformed image or list of images. - * - * @typedef {ImagePipelineConstructorArgs & ImageToImagePipelineCallback & Disposable} ImageToImagePipelineType - */ - -/** - * Image to Image pipeline using any `AutoModelForImageToImage`. This pipeline generates an image based on a previous image input. - * - * **Example:** Super-resolution w/ `Xenova/swin2SR-classical-sr-x2-64` - * ```javascript - * const upscaler = await pipeline('image-to-image', 'Xenova/swin2SR-classical-sr-x2-64'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/butterfly.jpg'; - * const output = await upscaler(url); - * // RawImage { - * // data: Uint8Array(786432) [ 41, 31, 24, 43, ... ], - * // width: 512, - * // height: 512, - * // channels: 3 - * // } - * ``` - */ -class ImageToImagePipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ (Pipeline)) { - /** - * Create a new ImageToImagePipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } +// src/models/distilbert/tokenization_distilbert.js +var DistilBertTokenizer = class extends PreTrainedTokenizer { +}; - /** @type {ImageToImagePipelineCallback} */ - async _call(images) { +// src/models/electra/tokenization_electra.js +var ElectraTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - const preparedImages = await prepareImages(images); - const inputs = await this.processor(preparedImages); - const outputs = await this.model(inputs); +// src/models/esm/tokenization_esm.js +var EsmTokenizer = class extends PreTrainedTokenizer { +}; - /** @type {RawImage[]} */ - const toReturn = []; - for (const batch of outputs.reconstruction) { - const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to('uint8'); - toReturn.push(_utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.fromTensor(output)); - } - - return toReturn.length > 1 ? toReturn : toReturn[0]; - } -} - -/** - * @typedef {Object} DepthEstimationPipelineOutput - * @property {Tensor} predicted_depth The raw depth map predicted by the model. - * @property {RawImage} depth The processed depth map as an image (with the same size as the input image). - * - * @callback DepthEstimationPipelineCallback Predicts the depth for the image(s) passed as inputs. - * @param {ImagePipelineInputs} images The images to compute depth for. - * @returns {Promise} An image or a list of images containing result(s). - * - * @typedef {ImagePipelineConstructorArgs & DepthEstimationPipelineCallback & Disposable} DepthEstimationPipelineType - */ - -/** - * Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image. - * - * **Example:** Depth estimation w/ `Xenova/dpt-hybrid-midas` - * ```javascript - * const depth_estimator = await pipeline('depth-estimation', 'Xenova/dpt-hybrid-midas'); - * const url = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/cats.jpg'; - * const out = await depth_estimator(url); - * // { - * // predicted_depth: Tensor { - * // dims: [ 384, 384 ], - * // type: 'float32', - * // data: Float32Array(147456) [ 542.859130859375, 545.2833862304688, 546.1649169921875, ... ], - * // size: 147456 - * // }, - * // depth: RawImage { - * // data: Uint8Array(307200) [ 86, 86, 86, ... ], - * // width: 640, - * // height: 480, - * // channels: 1 - * // } - * // } - * ``` - */ -class DepthEstimationPipeline extends (/** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ (Pipeline)) { - /** - * Create a new DepthEstimationPipeline. - * @param {ImagePipelineConstructorArgs} options An object used to instantiate the pipeline. - */ - constructor(options) { - super(options); - } +// src/models/falcon/tokenization_falcon.js +var FalconTokenizer = class extends PreTrainedTokenizer { +}; - /** @type {DepthEstimationPipelineCallback} */ - async _call(images) { +// src/models/gemma/tokenization_gemma.js +var GemmaTokenizer = class extends PreTrainedTokenizer { +}; - const preparedImages = await prepareImages(images); +// src/models/gpt_neox/tokenization_gpt_neox.js +var GPTNeoXTokenizer = class extends PreTrainedTokenizer { +}; - const inputs = await this.processor(preparedImages); - const { predicted_depth } = await this.model(inputs); +// src/models/gpt2/tokenization_gpt2.js +var GPT2Tokenizer = class extends PreTrainedTokenizer { +}; - const toReturn = []; - for (let i = 0; i < preparedImages.length; ++i) { - const batch = predicted_depth[i]; - const [height, width] = batch.dims.slice(-2); - const [new_width, new_height] = preparedImages[i].size; +// src/models/herbert/tokenization_herbert.js +var HerbertTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - // Interpolate to original size - const prediction = (await (0,_utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate_4d)(batch.view(1, 1, height, width), { - size: [new_height, new_width], - mode: 'bilinear', - })).view(new_height, new_width); +// src/models/llama/tokenization_llama.js +var LlamaTokenizer = class extends PreTrainedTokenizer { + padding_side = "left"; +}; - const minval = /** @type {number} */(prediction.min().item()); - const maxval = /** @type {number} */(prediction.max().item()); - const formatted = prediction.sub(minval).div_(maxval - minval).mul_(255).to('uint8').unsqueeze(0); - const depth = _utils_image_js__WEBPACK_IMPORTED_MODULE_9__.RawImage.fromTensor(formatted); - toReturn.push({ - predicted_depth: prediction, - depth, - }); - } +// src/models/m2m_100/tokenization_m2m_100.js +var M2M100Tokenizer = class extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^__[a-z]{2,3}__$/; + this.language_codes = this.all_special_tokens.filter((x) => this.languageRegex.test(x)).map((x) => x.slice(2, -2)); + this.lang_to_token = (x) => `__${x}__`; + } + /** + * Helper function to build translation inputs for an `M2M100Tokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } +}; - return toReturn.length > 1 ? toReturn : toReturn[0]; +// src/models/marian/tokenization_marian.js +var MarianTokenizer = class extends PreTrainedTokenizer { + /** + * Create a new MarianTokenizer instance. + * @param {Object} tokenizerJSON The JSON of the tokenizer. + * @param {Object} tokenizerConfig The config of the tokenizer. + */ + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^(>>\w+<<)\s*/g; + this.supported_language_codes = Array.from(this.get_vocab().keys()).filter((x) => this.languageRegex.test(x)); + logger.warn( + 'WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.' + ); + } + /** + * Encodes a single text. Overriding this method is necessary since the language codes + * must be removed before encoding with sentencepiece model. + * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 + * + * @param {string|null} text The text to encode. + * @returns {string[]|null} The encoded tokens. + */ + _encode_text(text) { + if (text === null) return null; + const [matchInfo, ...remainder] = text.trim().split(this.languageRegex); + if (remainder.length === 0) { + return super._encode_text(matchInfo); + } else if (remainder.length === 2) { + const [language, text2] = remainder; + if (!this.supported_language_codes.includes(language)) { + logger.warn( + `Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}` + ); + } + return mergeArrays([language], super._encode_text(text2)); } -} - -const SUPPORTED_TASKS = Object.freeze({ - "text-classification": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": TextClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSequenceClassification, - "default": { - // TODO: replace with original - // "model": "distilbert-base-uncased-finetuned-sst-2-english", - "model": "Xenova/distilbert-base-uncased-finetuned-sst-2-english", - }, - "type": "text", - }, - "token-classification": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": TokenClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTokenClassification, - "default": { - // TODO: replace with original - // "model": "Davlan/bert-base-multilingual-cased-ner-hrl", - "model": "Xenova/bert-base-multilingual-cased-ner-hrl", - }, - "type": "text", - }, - "question-answering": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": QuestionAnsweringPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForQuestionAnswering, - "default": { - // TODO: replace with original - // "model": "distilbert-base-cased-distilled-squad", - "model": "Xenova/distilbert-base-cased-distilled-squad", - }, - "type": "text", - }, + } +}; - "fill-mask": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": FillMaskPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForMaskedLM, - "default": { - // TODO: replace with original - // "model": "bert-base-uncased", - "model": "Xenova/bert-base-uncased", - }, - "type": "text", - }, - "summarization": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": SummarizationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM, - "default": { - // TODO: replace with original - // "model": "sshleifer/distilbart-cnn-6-6", - "model": "Xenova/distilbart-cnn-6-6", - }, - "type": "text", - }, - "translation": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": TranslationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM, - "default": { - // TODO: replace with original - // "model": "t5-small", - "model": "Xenova/t5-small", - }, - "type": "text", - }, - "text2text-generation": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": Text2TextGenerationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSeq2SeqLM, - "default": { - // TODO: replace with original - // "model": "google/flan-t5-small", - "model": "Xenova/flan-t5-small", - }, - "type": "text", - }, - "text-generation": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": TextGenerationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForCausalLM, - "default": { - // TODO: replace with original - // "model": "gpt2", - "model": "Xenova/gpt2", - }, - "type": "text", - }, - "zero-shot-classification": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": ZeroShotClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSequenceClassification, - "default": { - // TODO: replace with original - // "model": "typeform/distilbert-base-uncased-mnli", - "model": "Xenova/distilbert-base-uncased-mnli", - }, - "type": "text", - }, - "audio-classification": { - "pipeline": AudioClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForAudioClassification, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "superb/wav2vec2-base-superb-ks", - "model": "Xenova/wav2vec2-base-superb-ks", - }, - "type": "audio", - }, - "zero-shot-audio-classification": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": ZeroShotAudioClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "laion/clap-htsat-fused", - "model": "Xenova/clap-htsat-unfused", - }, - "type": "multimodal", - }, - "automatic-speech-recognition": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": AutomaticSpeechRecognitionPipeline, - "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSpeechSeq2Seq, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForCTC], - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "openai/whisper-tiny.en", - "model": "Xenova/whisper-tiny.en", - }, - "type": "multimodal", - }, - "text-to-audio": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": TextToAudioPipeline, - "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTextToWaveform, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForTextToSpectrogram], - "processor": [_models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, /* Some don't use a processor */ null], - "default": { - // TODO: replace with original - // "model": "microsoft/speecht5_tts", - "model": "Xenova/speecht5_tts", - }, - "type": "text", - }, - "image-to-text": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": ImageToTextPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForVision2Seq, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "nlpconnect/vit-gpt2-image-captioning", - "model": "Xenova/vit-gpt2-image-captioning", - }, - "type": "multimodal", - }, +// src/models/mbart/tokenization_mbart.js +var MBartTokenizer = class extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/; + this.language_codes = this.all_special_tokens.filter((x) => this.languageRegex.test(x)).map((x) => x); + this.lang_to_token = (x) => x; + } + /** + * Helper function to build translation inputs for an `MBartTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } +}; - "image-classification": { - // no tokenizer - "pipeline": ImageClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageClassification, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "google/vit-base-patch16-224", - "model": "Xenova/vit-base-patch16-224", - }, - "type": "multimodal", - }, +// src/models/mbart50/tokenization_mbart50.js +var MBart50Tokenizer = class extends MBartTokenizer { +}; - "image-segmentation": { - // no tokenizer - "pipeline": ImageSegmentationPipeline, - "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSemanticSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForUniversalSegmentation], - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "facebook/detr-resnet-50-panoptic", - "model": "Xenova/detr-resnet-50-panoptic", - }, - "type": "multimodal", - }, - "background-removal": { - // no tokenizer - "pipeline": BackgroundRemovalPipeline, - "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForSemanticSegmentation, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForUniversalSegmentation], - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - "model": "Xenova/modnet", - }, - "type": "image", - }, +// src/models/mgp_str/tokenization_mgp_str.js +var MgpstrTokenizer = class extends PreTrainedTokenizer { +}; - "zero-shot-image-classification": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": ZeroShotImageClassificationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "openai/clip-vit-base-patch32", - "model": "Xenova/clip-vit-base-patch32", - }, - "type": "multimodal", - }, +// src/models/mobilebert/tokenization_mobilebert.js +var MobileBertTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - "object-detection": { - // no tokenizer - "pipeline": ObjectDetectionPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForObjectDetection, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "facebook/detr-resnet-50", - "model": "Xenova/detr-resnet-50", - }, - "type": "multimodal", - }, - "zero-shot-object-detection": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": ZeroShotObjectDetectionPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForZeroShotObjectDetection, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "google/owlvit-base-patch32", - "model": "Xenova/owlvit-base-patch32", - }, - "type": "multimodal", - }, - "document-question-answering": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": DocumentQuestionAnsweringPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForDocumentQuestionAnswering, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "naver-clova-ix/donut-base-finetuned-docvqa", - "model": "Xenova/donut-base-finetuned-docvqa", - }, - "type": "multimodal", - }, - "image-to-image": { - // no tokenizer - "pipeline": ImageToImagePipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageToImage, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "caidas/swin2SR-classical-sr-x2-64", - "model": "Xenova/swin2SR-classical-sr-x2-64", - }, - "type": "image", - }, - "depth-estimation": { - // no tokenizer - "pipeline": DepthEstimationPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForDepthEstimation, - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "default": { - // TODO: replace with original - // "model": "Intel/dpt-large", - "model": "Xenova/dpt-large", - }, - "type": "image", - }, +// src/models/mpnet/tokenization_mpnet.js +var MPNetTokenizer = class extends PreTrainedTokenizer { +}; - // This task serves as a useful interface for dealing with sentence-transformers (https://huggingface.co/sentence-transformers). - "feature-extraction": { - "tokenizer": _tokenizers_js__WEBPACK_IMPORTED_MODULE_0__.AutoTokenizer, - "pipeline": FeatureExtractionPipeline, - "model": _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel, - "default": { - // TODO: replace with original - // "model": "sentence-transformers/all-MiniLM-L6-v2", - "model": "Xenova/all-MiniLM-L6-v2", - }, - "type": "text", - }, - "image-feature-extraction": { - "processor": _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_2__.AutoProcessor, - "pipeline": ImageFeatureExtractionPipeline, - "model": [_models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModelForImageFeatureExtraction, _models_js__WEBPACK_IMPORTED_MODULE_1__.AutoModel], - "default": { - // TODO: replace with original - // "model": "google/vit-base-patch16-224", - "model": "Xenova/vit-base-patch16-224-in21k", - }, - "type": "image", - }, -}) +// src/models/nllb/tokenization_nllb.js +var NllbTokenizer = class extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/; + this.language_codes = this.all_special_tokens.filter((x) => this.languageRegex.test(x)); + this.lang_to_token = (x) => x; + } + /** + * Helper function to build translation inputs for an `NllbTokenizer`. + * @param {string|string[]} raw_inputs The text to tokenize. + * @param {Object} tokenizer_options Options to be sent to the tokenizer + * @param {Object} generate_kwargs Generation options. + * @returns {Object} Object to be passed to the model. + */ + _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { + return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } +}; +// src/models/nougat/tokenization_nougat.js +var NougatTokenizer = class extends PreTrainedTokenizer { +}; -// TODO: Add types for TASK_ALIASES -const TASK_ALIASES = Object.freeze({ - "sentiment-analysis": "text-classification", - "ner": "token-classification", - // "vqa": "visual-question-answering", // TODO: Add - "asr": "automatic-speech-recognition", - "text-to-speech": "text-to-audio", +// src/models/qwen2/tokenization_qwen2.js +var Qwen2Tokenizer = class extends PreTrainedTokenizer { +}; - // Add for backwards compatibility - "embeddings": "feature-extraction", -}); +// src/models/roberta/tokenization_roberta.js +var RobertaTokenizer = class extends PreTrainedTokenizer { +}; -/** - * @typedef {keyof typeof SUPPORTED_TASKS} TaskType - * @typedef {keyof typeof TASK_ALIASES} AliasType - * @typedef {TaskType | AliasType} PipelineType All possible pipeline types. - * @typedef {{[K in TaskType]: InstanceType}} SupportedTasks A mapping of pipeline names to their corresponding pipeline classes. - * @typedef {{[K in AliasType]: InstanceType}} AliasTasks A mapping from pipeline aliases to their corresponding pipeline classes. - * @typedef {SupportedTasks & AliasTasks} AllTasks A mapping from all pipeline names and aliases to their corresponding pipeline classes. - */ - -/** - * Utility factory method to build a `Pipeline` object. - * - * @template {PipelineType} T The type of pipeline to return. - * @param {T} task The task defining which pipeline will be returned. Currently accepted tasks are: - * - `"audio-classification"`: will return a `AudioClassificationPipeline`. - * - `"automatic-speech-recognition"`: will return a `AutomaticSpeechRecognitionPipeline`. - * - `"depth-estimation"`: will return a `DepthEstimationPipeline`. - * - `"document-question-answering"`: will return a `DocumentQuestionAnsweringPipeline`. - * - `"feature-extraction"`: will return a `FeatureExtractionPipeline`. - * - `"fill-mask"`: will return a `FillMaskPipeline`. - * - `"image-classification"`: will return a `ImageClassificationPipeline`. - * - `"image-segmentation"`: will return a `ImageSegmentationPipeline`. - * - `"image-to-text"`: will return a `ImageToTextPipeline`. - * - `"object-detection"`: will return a `ObjectDetectionPipeline`. - * - `"question-answering"`: will return a `QuestionAnsweringPipeline`. - * - `"summarization"`: will return a `SummarizationPipeline`. - * - `"text2text-generation"`: will return a `Text2TextGenerationPipeline`. - * - `"text-classification"` (alias "sentiment-analysis" available): will return a `TextClassificationPipeline`. - * - `"text-generation"`: will return a `TextGenerationPipeline`. - * - `"token-classification"` (alias "ner" available): will return a `TokenClassificationPipeline`. - * - `"translation"`: will return a `TranslationPipeline`. - * - `"translation_xx_to_yy"`: will return a `TranslationPipeline`. - * - `"zero-shot-classification"`: will return a `ZeroShotClassificationPipeline`. - * - `"zero-shot-audio-classification"`: will return a `ZeroShotAudioClassificationPipeline`. - * - `"zero-shot-image-classification"`: will return a `ZeroShotImageClassificationPipeline`. - * - `"zero-shot-object-detection"`: will return a `ZeroShotObjectDetectionPipeline`. - * @param {string} [model=null] The name of the pre-trained model to use. If not specified, the default model for the task will be used. - * @param {import('./utils/hub.js').PretrainedModelOptions} [options] Optional parameters for the pipeline. - * @returns {Promise} A Pipeline object for the specified task. - * @throws {Error} If an unsupported pipeline is requested. - */ -async function pipeline( - task, - model = null, - { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = 'main', - device = null, - dtype = null, - subfolder = 'onnx', - use_external_data_format = null, - model_file_name = null, - session_options = {}, - } = {} -) { - // Helper method to construct pipeline - - // Apply aliases - // @ts-ignore - task = TASK_ALIASES[task] ?? task; - - // Get pipeline info - const pipelineInfo = SUPPORTED_TASKS[task.split('_', 1)[0]]; - if (!pipelineInfo) { - throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`) - } - - // Use model if specified, otherwise, use default - if (!model) { - model = pipelineInfo.default.model - console.log(`No model specified. Using default model: "${model}".`); - } - - const pretrainedOptions = { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - device, - dtype, - subfolder, - use_external_data_format, - model_file_name, - session_options, - } - - const classes = new Map([ - ['tokenizer', pipelineInfo.tokenizer], - ['model', pipelineInfo.model], - ['processor', pipelineInfo.processor], - ]); +// src/models/roformer/tokenization_roformer.js +var RoFormerTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; - // Load model, tokenizer, and processor (if they exist) - const results = await loadItems(classes, model, pretrainedOptions); - results.task = task; +// src/models/siglip/tokenization_siglip.js +var SiglipTokenizer = class extends PreTrainedTokenizer { +}; - (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_5__.dispatchCallback)(progress_callback, { - 'status': 'ready', - 'task': task, - 'model': model, - }); +// src/models/speecht5/tokenization_speecht5.js +var SpeechT5Tokenizer = class extends PreTrainedTokenizer { +}; - const pipelineClass = pipelineInfo.pipeline; - return new pipelineClass(results); -} +// src/models/squeezebert/tokenization_squeezebert.js +var SqueezeBertTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; +}; +// src/models/t5/tokenization_t5.js +var T5Tokenizer = class extends PreTrainedTokenizer { +}; -/** - * Helper function to get applicable model, tokenizer, or processor classes for a given model. - * @param {Map} mapping The mapping of names to classes, arrays of classes, or null. - * @param {string} model The name of the model to load. - * @param {import('./utils/hub.js').PretrainedOptions} pretrainedOptions The options to pass to the `from_pretrained` method. - * @private - */ -async function loadItems(mapping, model, pretrainedOptions) { +// src/models/vits/tokenization_vits.js +var VitsDecoder = class extends Decoder_default { + /** @type {Decoder['decode_chain']} */ + decode_chain(tokens) { + let decoded = ""; + for (let i = 1; i < tokens.length; i += 2) { + decoded += tokens[i]; + } + return [decoded]; + } +}; +var VitsTokenizer = class extends PreTrainedTokenizer { + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + this._tokenizer.decoder = new VitsDecoder({ type: "VitsDecoder" }); + } +}; - const result = Object.create(null); +// src/models/wav2vec2/tokenization_wav2vec2.js +var Wav2Vec2CTCTokenizer = class extends PreTrainedTokenizer { +}; - /**@type {Promise[]} */ - const promises = []; - for (const [name, cls] of mapping.entries()) { - if (!cls) continue; - - /**@type {Promise} */ - let promise; - if (Array.isArray(cls)) { - promise = new Promise(async (resolve, reject) => { - let e; - for (const c of cls) { - if (c === null) { - // If null, we resolve it immediately, meaning the relevant - // class was not found, but it is optional. - resolve(null); - return; - } - try { - resolve(await c.from_pretrained(model, pretrainedOptions)); - return; - } catch (err) { - if (err.message?.includes('Unsupported model type')) { - // If the error is due to an unsupported model type, we - // save the error and try the next class. - e = err; - } else if (err.message?.includes('Could not locate file')) { - e = err; - } else { - reject(err); - return; - } +// src/models/whisper/common_whisper.js +var WHISPER_LANGUAGES = [ + ["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"] +]; +var WHISPER_LANGUAGE_MAPPING = new Map(WHISPER_LANGUAGES); +var WHISPER_TO_LANGUAGE_CODE_MAPPING = new Map([ + ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]), + ...[ + ["burmese", "my"], + ["valencian", "ca"], + ["flemish", "nl"], + ["haitian", "ht"], + ["letzeburgesch", "lb"], + ["pushto", "ps"], + ["panjabi", "pa"], + ["moldavian", "ro"], + ["moldovan", "ro"], + ["sinhalese", "si"], + ["castilian", "es"] + ] +]); +function whisper_language_to_code(language) { + language = language.toLowerCase(); + let language_code = WHISPER_TO_LANGUAGE_CODE_MAPPING.get(language); + if (language_code === void 0) { + const language_special_token = language.match(/^<\|([a-z]{2})\|>$/); + if (language_special_token) { + language = language_special_token[1]; + } + if (WHISPER_LANGUAGE_MAPPING.has(language)) { + language_code = language; + } else { + const is_language_code = language.length === 2; + const langs = is_language_code ? WHISPER_LANGUAGE_MAPPING.keys() : WHISPER_LANGUAGE_MAPPING.values(); + throw new Error( + `Language "${language}" is not supported. Must be one of: ${JSON.stringify(Array.from(langs))}` + ); + } + } + return language_code; +} +// src/models/whisper/tokenization_whisper.js +var PUNCTUATION_REGEX2 = "\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E"; +var PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX2}]+$`, "gu"); +var TIMESTAMP_MERGE_TOLERANCE = 0.1; +var WhisperTokenizer = class extends PreTrainedTokenizer { + get timestamp_begin() { + return this._tokenizer.token_to_id("<|notimestamps|>") + 1; + } + /** + * Decodes automatic speech recognition (ASR) sequences. + * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. + * @param {Object} options The options to use for decoding. + * @returns {Array, text: string}>}>} The decoded sequences. + */ + _decode_asr(sequences, { return_timestamps = false, return_language = false, time_precision = null, force_full_sequences = true } = {}) { + if (time_precision === null) { + throw Error("Must specify time_precision"); + } + let last_language = null; + const returnWordTimestamps = return_timestamps === "word"; + function new_chunk() { + return { language: last_language, timestamp: [null, null], text: "" }; + } + const chunks = []; + let chunk2 = new_chunk(); + let time_offset = 0; + const timestamp_begin = this.timestamp_begin; + const total_timestamp_tokens = 1500; + const timestamp_end = timestamp_begin + total_timestamp_tokens; + let previous_tokens = []; + let previous_token_timestamps = []; + let skip = false; + let right_stride_start = null; + const all_special_ids = new Set(this.all_special_ids); + for (const output of sequences) { + const token_ids = output.tokens; + const token_timestamps = returnWordTimestamps ? output.token_timestamps : null; + let last_timestamp = null; + let first_timestamp = timestamp_begin; + if ("stride" in output) { + const [chunk_len, stride_left, stride_right] = output.stride; + time_offset -= stride_left; + right_stride_start = chunk_len - stride_right; + if (stride_left) { + first_timestamp = stride_left / time_precision + timestamp_begin; + } + if (stride_right) { + for (let i = token_ids.length - 1; i >= 0; --i) { + const token = Number(token_ids[i]); + if (token >= timestamp_begin) { + if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) { + break; + } + last_timestamp = token; + } + } + } + } + let current_tokens = []; + let current_token_timestamps = []; + for (let i = 0; i < token_ids.length; ++i) { + const token = Number(token_ids[i]); + if (all_special_ids.has(token)) { + const text = this.decode([token]); + const language = WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2)); + if (language !== void 0) { + if (last_language !== null && language !== last_language && !return_timestamps) { + previous_tokens.push(current_tokens); + const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0]; + const resolved_text = this.decode(resolved_tokens); + chunk2.text = resolved_text; + chunks.push(chunk2); + previous_tokens = []; + current_tokens = []; + chunk2 = new_chunk(); + } + last_language = chunk2.language = language; + } else { + } + } else if (token >= timestamp_begin && token <= timestamp_end) { + const time = (token - timestamp_begin) * time_precision + time_offset; + const rounded_time = round(time, 2); + if (last_timestamp !== null && token >= last_timestamp) { + skip = true; + } else if (skip || previous_tokens.length > 0 && token < first_timestamp) { + skip = false; + } else if (chunk2.timestamp[0] === null) { + chunk2.timestamp[0] = rounded_time; + } else { + if (rounded_time === chunk2.timestamp[0]) { + } else { + chunk2.timestamp[1] = rounded_time; + previous_tokens.push(current_tokens); + if (returnWordTimestamps) { + previous_token_timestamps.push(current_token_timestamps); + } + const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( + previous_tokens, + previous_token_timestamps + ); + const resolved_text = this.decode(resolved_tokens); + chunk2.text = resolved_text; + if (returnWordTimestamps) { + chunk2.words = this.collateWordTimestamps( + resolved_tokens, + resolved_token_timestamps, + last_language + ); + if (chunk2.words.length > 0 && chunk2.timestamp[1] !== null) { + for (const word of chunk2.words) { + if (word.timestamp[1] > chunk2.timestamp[1] && chunk2.timestamp[1] >= word.timestamp[0]) { + word.timestamp[1] = chunk2.timestamp[1]; } + } } - reject(e); - }) + } + chunks.push(chunk2); + previous_tokens = []; + current_tokens = []; + previous_token_timestamps = []; + current_token_timestamps = []; + chunk2 = new_chunk(); + } + } } else { - promise = cls.from_pretrained(model, pretrainedOptions); + current_tokens.push(token); + if (returnWordTimestamps) { + let start_time = round(token_timestamps[i] + time_offset, 2); + let end_time; + if (i + 1 < token_timestamps.length) { + end_time = round(token_timestamps[i + 1] + time_offset, 2); + const decoded_text = this.decode([token]); + if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) { + end_time = round(Math.min(start_time + time_precision, end_time), 2); + } + } else { + end_time = null; + } + current_token_timestamps.push([start_time, end_time]); + } } - - result[name] = promise; - promises.push(promise); + } + if ("stride" in output) { + const [chunk_len, stride_left, stride_right] = output.stride; + time_offset += chunk_len - stride_right; + } + if (current_tokens.length > 0) { + previous_tokens.push(current_tokens); + if (returnWordTimestamps) { + previous_token_timestamps.push(current_token_timestamps); + } + } else if (previous_tokens.every((p) => p.length === 0)) { + chunk2 = new_chunk(); + previous_tokens = []; + current_tokens = []; + previous_token_timestamps = []; + current_token_timestamps = []; + } } - - // Wait for all promises to resolve (in parallel) - await Promise.all(promises); - - // Then assign to result - for (const [name, promise] of Object.entries(result)) { - result[name] = await promise; + if (previous_tokens.length > 0) { + if (force_full_sequences && return_timestamps) { + 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 [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( + previous_tokens, + previous_token_timestamps + ); + const resolved_text = this.decode(resolved_tokens); + chunk2.text = resolved_text; + if (returnWordTimestamps) { + chunk2.words = this.collateWordTimestamps(resolved_tokens, resolved_token_timestamps, last_language); + } + chunks.push(chunk2); } + let optional = /* @__PURE__ */ Object.create(null); + const full_text = chunks.map((chunk3) => chunk3.text).join(""); + if (return_timestamps || return_language) { + for (let i = 0; i < chunks.length; ++i) { + const chunk3 = chunks[i]; + if (!return_timestamps) { + delete chunk3["timestamp"]; + } + if (!return_language) { + delete chunk3["language"]; + } + } + if (returnWordTimestamps) { + const new_chunks = []; + for (const chunk3 of chunks) { + for (const word of chunk3.words) { + new_chunks.push(word); + } + } + optional = { chunks: new_chunks }; + } else { + optional = { chunks }; + } + } + return [full_text, optional]; + } + /** + * Finds the longest common sequence among the provided sequences. + * @param {number[][]} sequences An array of sequences of token ids to compare. + * @returns {number[][]} The longest common sequence found. + * @throws {Error} If there is a bug within the function. + * @private + */ + findLongestCommonSequence(sequences, token_timestamp_sequences = null) { + let leftSequence = sequences[0]; + let leftLength = leftSequence.length; + let totalSequence = []; + const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0; + let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null; + let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null; + for (let i = 1; i < sequences.length; ++i) { + const rightSequence = sequences[i]; + let max2 = 0; + let maxIndices = [leftLength, leftLength, 0, 0]; + const rightLength = rightSequence.length; + for (let j2 = 1; j2 < leftLength + rightLength; ++j2) { + const leftStart2 = Math.max(0, leftLength - j2); + const leftStop2 = Math.min(leftLength, leftLength + rightLength - j2); + const left = leftSequence.slice(leftStart2, leftStop2); + const rightStart2 = Math.max(0, j2 - leftLength); + const rightStop2 = Math.min(rightLength, j2); + const right = rightSequence.slice(rightStart2, rightStop2); + if (left.length !== right.length) { + throw new Error( + "There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference." + ); + } + let matches; + if (use_token_timestamp_sequences) { + matches = left.filter( + (elem, idx) => elem === right[idx] && left_token_timestamp_sequence[leftStart2 + idx][0] - TIMESTAMP_MERGE_TOLERANCE <= token_timestamp_sequences[i][rightStart2 + idx][0] + ).length; + } else { + matches = left.filter((elem, idx) => elem === right[idx]).length; + } + const eps = j2 / 1e4; + const matching = matches / j2 + eps; + if (matches > 1 && matching > max2) { + max2 = matching; + maxIndices = [leftStart2, leftStop2, rightStart2, rightStop2]; + } + } + const [leftStart, leftStop, rightStart, rightStop] = maxIndices; + const leftMid = Math.floor((leftStop + leftStart) / 2); + let rightMid = Math.floor((rightStop + rightStart) / 2); + if (use_token_timestamp_sequences && max2 === 0 && leftLength > 0) { + const lastLeftTs = left_token_timestamp_sequence[leftLength - 1][0]; + const idx = token_timestamp_sequences[i].findIndex((ts2) => ts2[0] >= lastLeftTs); + rightMid = idx === -1 ? rightSequence.length : idx; + } + totalSequence.push(...leftSequence.slice(0, leftMid)); + leftSequence = rightSequence.slice(rightMid); + leftLength = leftSequence.length; + if (use_token_timestamp_sequences) { + total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid)); + left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid); + } + } + totalSequence.push(...leftSequence); + if (use_token_timestamp_sequences) { + total_token_timestamp_sequence.push(...left_token_timestamp_sequence); + return [totalSequence, total_token_timestamp_sequence]; + } else { + return [totalSequence, []]; + } + } + /** @private */ + collateWordTimestamps(tokens, token_timestamps, language) { + const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language); + const timings = []; + for (let i = 0; i < words.length; ++i) { + const indices = token_indices[i]; + timings.push({ + text: words[i], + timestamp: [token_timestamps[indices.at(0)][0], token_timestamps[indices.at(-1)][1]] + }); + } + return timings; + } + /** + * Groups tokens by word. Returns a tuple containing a list of strings with the words, + * and a list of `token_id` sequences with the tokens making up each word. + * @param {number[]} tokens + * @param {string} [language] + * @param {string} prepend_punctionations + * @param {string} append_punctuations + * + * @private + */ + combineTokensIntoWords(tokens, language, prepend_punctionations = `"'\u201C\xA1\xBF([{-`, append_punctuations = `"'.\u3002,\uFF0C!\uFF01?\uFF1F:\uFF1A\u201D)]}\u3001`) { + language = language ?? "english"; + let words, word_tokens, token_indices; + if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) { + [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens); + } else { + [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens); + } + return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations); + } + /** @type {PreTrainedTokenizer['decode']} */ + decode(token_ids, decode_args) { + let text; + if (decode_args?.decode_with_timestamps) { + if (token_ids instanceof Tensor3) { + token_ids = prepareTensorForDecode(token_ids); + } + text = this.decodeWithTimestamps(token_ids, decode_args); + } else { + text = super.decode(token_ids, decode_args); + } + return text; + } + /** + * @param {number[]|bigint[]} token_ids List of token IDs to decode. + * @param {Object} decode_args Optional arguments for decoding + * @private + */ + decodeWithTimestamps(token_ids, decode_args) { + const time_precision = decode_args?.time_precision ?? 0.02; + const timestamp_begin = this.all_special_ids.at(-1) + 1; + let outputs = [[]]; + for (let token of token_ids) { + token = Number(token); + if (token >= timestamp_begin) { + const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2); + outputs.push(`<|${timestamp}|>`); + outputs.push([]); + } else { + outputs[outputs.length - 1].push(token); + } + } + outputs = outputs.map((s) => typeof s === "string" ? s : super.decode(s, decode_args)); + return outputs.join(""); + } + /** + * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. + * @param {number[]} tokens + * @returns {*} + * @private + */ + splitTokensOnUnicode(tokens) { + const decoded_full = this.decode(tokens, { + // @ts-ignore + decode_with_timestamps: true + }); + const replacement_char = "\uFFFD"; + const words = []; + const word_tokens = []; + const token_indices = []; + let current_tokens = []; + let current_indices = []; + let unicode_offset = 0; + for (let token_idx = 0; token_idx < tokens.length; ++token_idx) { + const token = tokens[token_idx]; + current_tokens.push(token); + current_indices.push(token_idx); + const decoded = this.decode(current_tokens, { + // @ts-ignore + decode_with_timestamps: true + }); + if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) { + words.push(decoded); + word_tokens.push(current_tokens); + token_indices.push(current_indices); + current_tokens = []; + current_indices = []; + unicode_offset += decoded.length; + } + } + return [words, word_tokens, token_indices]; + } + /** + * Combine tokens into words by splitting at whitespace and punctuation tokens. + * @param {number[]} tokens + * @private + */ + splitTokensOnSpaces(tokens) { + const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens); + const words = []; + const word_tokens = []; + const token_indices = []; + for (let i = 0; i < subwords.length; ++i) { + const subword = subwords[i]; + const subword_tokens = subword_tokens_list[i]; + const subword_indices = subword_indices_list[i]; + const special = subword_tokens[0] >= this._tokenizer.token_to_id("<|endoftext|>"); + const with_space = subword.startsWith(" "); + const trimmed = subword.trim(); + const punctuation = PUNCTUATION_ONLY_REGEX.test(trimmed); + if (special || with_space || punctuation || words.length === 0) { + words.push(subword); + word_tokens.push(subword_tokens); + token_indices.push(subword_indices); + } else { + const ix = words.length - 1; + words[ix] += subword; + word_tokens[ix].push(...subword_tokens); + token_indices[ix].push(...subword_indices); + } + } + return [words, word_tokens, token_indices]; + } + /** + * Merges punctuation tokens with neighboring words. + * @param {string[]} words + * @param {number[][]} tokens + * @param {number[][]} indices + * @param {string} prepended + * @param {string} appended + * @private + */ + mergePunctuations(words, tokens, indices, prepended, appended) { + const newWords = structuredClone(words); + const newTokens = structuredClone(tokens); + const newIndices = structuredClone(indices); + let i = newWords.length - 2; + let j2 = newWords.length - 1; + while (i >= 0) { + if (newWords[i].startsWith(" ") && prepended.includes(newWords[i].trim())) { + newWords[j2] = newWords[i] + newWords[j2]; + newTokens[j2] = mergeArrays(newTokens[i], newTokens[j2]); + newIndices[j2] = mergeArrays(newIndices[i], newIndices[j2]); + newWords[i] = ""; + newTokens[i] = []; + newIndices[i] = []; + } else { + j2 = i; + } + --i; + } + i = 0; + j2 = 1; + while (j2 < newWords.length) { + if (!newWords[i].endsWith(" ") && appended.includes(newWords[j2])) { + newWords[i] += newWords[j2]; + newTokens[i] = mergeArrays(newTokens[i], newTokens[j2]); + newIndices[i] = mergeArrays(newIndices[i], newIndices[j2]); + newWords[j2] = ""; + newTokens[j2] = []; + newIndices[j2] = []; + } else { + i = j2; + } + ++j2; + } + return [ + newWords.filter((x) => x), + newTokens.filter((x) => x.length > 0), + newIndices.filter((x) => x.length > 0) + ]; + } +}; - return result; -} - - -/***/ }), - -/***/ "./src/tokenizers.js": -/*!***************************!*\ - !*** ./src/tokenizers.js ***! - \***************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ AlbertTokenizer: () => (/* binding */ AlbertTokenizer), -/* harmony export */ AutoTokenizer: () => (/* binding */ AutoTokenizer), -/* harmony export */ BartTokenizer: () => (/* binding */ BartTokenizer), -/* harmony export */ BertTokenizer: () => (/* binding */ BertTokenizer), -/* harmony export */ BlenderbotSmallTokenizer: () => (/* binding */ BlenderbotSmallTokenizer), -/* harmony export */ BlenderbotTokenizer: () => (/* binding */ BlenderbotTokenizer), -/* harmony export */ BloomTokenizer: () => (/* binding */ BloomTokenizer), -/* harmony export */ CLIPTokenizer: () => (/* binding */ CLIPTokenizer), -/* harmony export */ CamembertTokenizer: () => (/* binding */ CamembertTokenizer), -/* harmony export */ CodeGenTokenizer: () => (/* binding */ CodeGenTokenizer), -/* harmony export */ CodeLlamaTokenizer: () => (/* binding */ CodeLlamaTokenizer), -/* harmony export */ CohereTokenizer: () => (/* binding */ CohereTokenizer), -/* harmony export */ ConvBertTokenizer: () => (/* binding */ ConvBertTokenizer), -/* harmony export */ DebertaTokenizer: () => (/* binding */ DebertaTokenizer), -/* harmony export */ DebertaV2Tokenizer: () => (/* binding */ DebertaV2Tokenizer), -/* harmony export */ DistilBertTokenizer: () => (/* binding */ DistilBertTokenizer), -/* harmony export */ ElectraTokenizer: () => (/* binding */ ElectraTokenizer), -/* harmony export */ Ernie4_5_Tokenizer: () => (/* binding */ Ernie4_5_Tokenizer), -/* harmony export */ EsmTokenizer: () => (/* binding */ EsmTokenizer), -/* harmony export */ FalconTokenizer: () => (/* binding */ FalconTokenizer), -/* harmony export */ GPT2Tokenizer: () => (/* binding */ GPT2Tokenizer), -/* harmony export */ GPTNeoXTokenizer: () => (/* binding */ GPTNeoXTokenizer), -/* harmony export */ GemmaTokenizer: () => (/* binding */ GemmaTokenizer), -/* harmony export */ Grok1Tokenizer: () => (/* binding */ Grok1Tokenizer), -/* harmony export */ HerbertTokenizer: () => (/* binding */ HerbertTokenizer), -/* harmony export */ LlamaTokenizer: () => (/* binding */ LlamaTokenizer), -/* harmony export */ M2M100Tokenizer: () => (/* binding */ M2M100Tokenizer), -/* harmony export */ MBart50Tokenizer: () => (/* binding */ MBart50Tokenizer), -/* harmony export */ MBartTokenizer: () => (/* binding */ MBartTokenizer), -/* harmony export */ MPNetTokenizer: () => (/* binding */ MPNetTokenizer), -/* harmony export */ MarianTokenizer: () => (/* binding */ MarianTokenizer), -/* harmony export */ MgpstrTokenizer: () => (/* binding */ MgpstrTokenizer), -/* harmony export */ MobileBertTokenizer: () => (/* binding */ MobileBertTokenizer), -/* harmony export */ NllbTokenizer: () => (/* binding */ NllbTokenizer), -/* harmony export */ NougatTokenizer: () => (/* binding */ NougatTokenizer), -/* harmony export */ PreTrainedTokenizer: () => (/* binding */ PreTrainedTokenizer), -/* harmony export */ Qwen2Tokenizer: () => (/* binding */ Qwen2Tokenizer), -/* harmony export */ RoFormerTokenizer: () => (/* binding */ RoFormerTokenizer), -/* harmony export */ RobertaTokenizer: () => (/* binding */ RobertaTokenizer), -/* harmony export */ SiglipTokenizer: () => (/* binding */ SiglipTokenizer), -/* harmony export */ SpeechT5Tokenizer: () => (/* binding */ SpeechT5Tokenizer), -/* harmony export */ SqueezeBertTokenizer: () => (/* binding */ SqueezeBertTokenizer), -/* harmony export */ T5Tokenizer: () => (/* binding */ T5Tokenizer), -/* harmony export */ TokenizerModel: () => (/* binding */ TokenizerModel), -/* harmony export */ VitsTokenizer: () => (/* binding */ VitsTokenizer), -/* harmony export */ Wav2Vec2CTCTokenizer: () => (/* binding */ Wav2Vec2CTCTokenizer), -/* harmony export */ WhisperTokenizer: () => (/* binding */ WhisperTokenizer), -/* harmony export */ XLMRobertaTokenizer: () => (/* binding */ XLMRobertaTokenizer), -/* harmony export */ XLMTokenizer: () => (/* binding */ XLMTokenizer), -/* harmony export */ is_chinese_char: () => (/* binding */ is_chinese_char) -/* harmony export */ }); -/* harmony import */ var _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/generic.js */ "./src/utils/generic.js"); -/* harmony import */ var _utils_core_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/core.js */ "./src/utils/core.js"); -/* harmony import */ var _utils_hub_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/data-structures.js */ "./src/utils/data-structures.js"); -/* harmony import */ var _huggingface_jinja__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @huggingface/jinja */ "./node_modules/@huggingface/jinja/dist/index.js"); -/* harmony import */ var _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./models/whisper/common_whisper.js */ "./src/models/whisper/common_whisper.js"); - -/** - * @file Tokenizers are used to prepare textual inputs for a model. - * - * **Example:** Create an `AutoTokenizer` and use it to tokenize a sentence. - * This will automatically detect the tokenizer type based on the tokenizer class defined in `tokenizer.json`. - * ```javascript - * import { AutoTokenizer } from '@huggingface/transformers'; - * - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); - * const { input_ids } = await tokenizer('I love transformers!'); - * // Tensor { - * // data: BigInt64Array(6) [101n, 1045n, 2293n, 19081n, 999n, 102n], - * // dims: [1, 6], - * // type: 'int64', - * // size: 6, - * // } - * ``` - * - * @module tokenizers - */ - - - - - - - - - - - - - - - -/** - * @typedef {Object} TokenizerProperties Additional tokenizer-specific properties. - * @property {boolean} [legacy=false] Whether or not the `legacy` behavior of the tokenizer should be used. - * @typedef {import('./utils/hub.js').PretrainedOptions & TokenizerProperties} PretrainedTokenizerOptions - */ - -/** - * Loads a tokenizer from the specified path. - * @param {string} pretrained_model_name_or_path The path to the tokenizer directory. - * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. - * @returns {Promise} A promise that resolves with information about the loaded tokenizer. - */ -async function loadTokenizer(pretrained_model_name_or_path, options) { +// src/models/xlm_roberta/tokenization_xlm_roberta.js +var XLMRobertaTokenizer = class extends PreTrainedTokenizer { +}; - const info = await Promise.all([ - (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, 'tokenizer.json', true, options), - (0,_utils_hub_js__WEBPACK_IMPORTED_MODULE_2__.getModelJSON)(pretrained_model_name_or_path, 'tokenizer_config.json', true, options), - ]) +// src/models/xlm/tokenization_xlm.js +var XLMTokenizer = class extends PreTrainedTokenizer { + return_token_type_ids = true; + constructor(tokenizerJSON, tokenizerConfig) { + super(tokenizerJSON, tokenizerConfig); + logger.warn( + 'WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.' + ); + } +}; - // Override legacy option if `options.legacy` is not null - if (options.legacy !== null) { - info[1].legacy = options.legacy; +// src/models/auto/tokenization_auto.js +var AutoTokenizer = class { + /** + * Instantiate one of the tokenizer classes of the library from a pretrained model. + * + * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. + * @param {import('../../tokenization_utils.js').PretrainedTokenizerOptions} options Additional options for loading the tokenizer. + * + * @returns {Promise} The loaded tokenizer. + */ + static async from_pretrained(pretrained_model_name_or_path, { progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main" } = {}) { + const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision + }); + const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, "") ?? "PreTrainedTokenizer"; + let cls = tokenizers_exports[tokenizerName]; + if (!cls) { + logger.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`); + cls = PreTrainedTokenizer; } - return info; -} - + return new cls(tokenizerJSON, tokenizerConfig); + } +}; -/** - * Helper function to split a string on a regex, but keep the delimiters. - * This is required, because the JavaScript `.split()` method does not keep the delimiters, - * and wrapping in a capturing group causes issues with existing capturing groups (due to nesting). - * @param {string} text The text to split. - * @param {RegExp} regex The regex to split on. - * @returns {string[]} The split string. - */ -function regexSplit(text, regex) { - const result = []; - let prev = 0; - for (const match of text.matchAll(regex)) { - const fullMatch = match[0]; - if (prev < match.index) { - result.push(text.slice(prev, match.index)); - } - if (fullMatch.length > 0) { - result.push(fullMatch); - } - prev = match.index + fullMatch.length; +// src/utils/constants.js +var GITHUB_ISSUE_URL = "https://github.com/huggingface/transformers.js/issues/new/choose"; +var FEATURE_EXTRACTOR_NAME = "preprocessor_config.json"; +var IMAGE_PROCESSOR_NAME = "preprocessor_config.json"; +var PROCESSOR_NAME = "processor_config.json"; +var CHAT_TEMPLATE_NAME = "chat_template.jinja"; + +// src/processing_utils.js +var Processor = class extends Callable { + static classes = ["image_processor_class", "tokenizer_class", "feature_extractor_class"]; + static uses_processor_config = false; + static uses_chat_template_file = false; + /** + * Create a processor from parsed config and its component preprocessors. + * @param {Object} config Processor configuration. + * @param {Record} components Loaded tokenizer, image processor, and/or feature extractor. + * @param {string|null} chat_template Optional chat template loaded from the model repo. + */ + constructor(config, components, chat_template) { + super(); + this.config = config; + this.components = components; + this.chat_template = chat_template; + } + /** + * The image processor used by this processor, if any. + * @returns {import('./image_processors_utils.js').ImageProcessor|undefined} The image processor of the processor, if it exists. + */ + get image_processor() { + return this.components.image_processor; + } + /** + * The tokenizer used by this processor, if any. + * @returns {PreTrainedTokenizer|undefined} The tokenizer of the processor, if it exists. + */ + get tokenizer() { + return this.components.tokenizer; + } + /** + * The feature extractor used by this processor, if any. + * @returns {import('./feature_extraction_utils.js').FeatureExtractor|undefined} The feature extractor of the processor, if it exists. + */ + get feature_extractor() { + return this.components.feature_extractor; + } + /** + * Delegates to the underlying tokenizer's `apply_chat_template`. + * @param {Parameters[0]} messages + * @param {Parameters[1]} options + * @returns {ReturnType} + */ + apply_chat_template(messages, options = {}) { + if (!this.tokenizer) { + throw new Error("Unable to apply chat template without a tokenizer."); + } + return this.tokenizer.apply_chat_template(messages, { + tokenize: false, + // default to false + chat_template: this.chat_template ?? void 0, + ...options + }); + } + /** + * Decode a batch of tokenized sequences via the underlying tokenizer. + * @param {Parameters} args + * @returns {ReturnType} + */ + batch_decode(...args) { + if (!this.tokenizer) { + throw new Error("Unable to decode without a tokenizer."); } - if (prev < text.length) { - result.push(text.slice(prev)); + return this.tokenizer.batch_decode(...args); + } + /** + * Decode a single tokenized sequence via the underlying tokenizer. + * @param {Parameters} args + * @returns {ReturnType} + */ + decode(...args) { + if (!this.tokenizer) { + throw new Error("Unable to decode without a tokenizer."); } - return result; -} - + return this.tokenizer.decode(...args); + } + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @param {...any} args Additional arguments. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(input, ...args) { + for (const item of [this.image_processor, this.feature_extractor, this.tokenizer]) { + if (item) { + return item(input, ...args); + } + } + throw new Error("No image processor, feature extractor, or tokenizer found."); + } + /** + * Instantiate one of the processor classes of the library from a pretrained model. + * + * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) + * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model ID* of a pretrained processor hosted inside a model repo on huggingface.co. + * Valid model IDs can be located at the root level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. + * @param {PretrainedProcessorOptions} options Additional options for loading the processor. + * + * @returns {Promise} A new processor instance. + */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const [config, components, chat_template] = await Promise.all([ + // TODO: + this.uses_processor_config ? getModelJSON(pretrained_model_name_or_path, PROCESSOR_NAME, true, options) : {}, + Promise.all( + this.classes.filter((cls) => cls in this).map(async (cls) => { + const component = await this[cls].from_pretrained(pretrained_model_name_or_path, options); + return [cls.replace(/_class$/, ""), component]; + }) + ).then(Object.fromEntries), + this.uses_chat_template_file ? getModelText(pretrained_model_name_or_path, CHAT_TEMPLATE_NAME, true, options) : null + ]); + return new this(config, components, chat_template); + } +}; -/** - * Helper method to construct a pattern from a config object. - * @param {Object} pattern The pattern object. - * @param {boolean} invert Whether to invert the pattern. - * @returns {RegExp|null} The compiled pattern. - */ -function createPattern(pattern, invert = true) { +// src/models/processors.js +var processors_exports = {}; +__export(processors_exports, { + ChatterboxProcessor: () => ChatterboxProcessor, + CohereAsrProcessor: () => CohereAsrProcessor, + EmbeddingGemma2Processor: () => EmbeddingGemma2Processor, + EmbeddingGemma2VideoProcessor: () => EmbeddingGemma2VideoProcessor, + Florence2Processor: () => Florence2Processor, + Gemma3Processor: () => Gemma3Processor, + Gemma3nProcessor: () => Gemma3nProcessor, + Gemma4Processor: () => Gemma4Processor, + Glm46VProcessor: () => Glm46VProcessor, + GraniteSpeechProcessor: () => GraniteSpeechProcessor, + GroundingDinoProcessor: () => GroundingDinoProcessor, + Idefics3Processor: () => Idefics3Processor, + JinaCLIPProcessor: () => JinaCLIPProcessor, + Lfm2VlProcessor: () => Lfm2VlProcessor, + Lfm3VlProcessor: () => Lfm3VlProcessor, + LlavaProcessor: () => LlavaProcessor, + MgpstrProcessor: () => MgpstrProcessor, + MoonshineProcessor: () => MoonshineProcessor, + OwlViTProcessor: () => OwlViTProcessor, + PaliGemmaProcessor: () => PaliGemmaProcessor, + Phi3VProcessor: () => Phi3VProcessor, + PixtralProcessor: () => PixtralProcessor, + Processor: () => Processor, + PyAnnoteProcessor: () => PyAnnoteProcessor, + Qwen2VLProcessor: () => Qwen2VLProcessor, + Qwen2_5_VLProcessor: () => Qwen2_5_VLProcessor, + Qwen3VLProcessor: () => Qwen3VLProcessor, + Sam2Processor: () => Sam2Processor, + Sam2VideoProcessor: () => Sam2VideoProcessor, + SamProcessor: () => SamProcessor, + SmolVLMProcessor: () => Idefics3Processor, + SpeechT5Processor: () => SpeechT5Processor, + UltravoxProcessor: () => UltravoxProcessor, + VLChatProcessor: () => VLChatProcessor, + VoxtralProcessor: () => VoxtralProcessor, + VoxtralRealtimeProcessor: () => VoxtralRealtimeProcessor, + Wav2Vec2Processor: () => Wav2Vec2Processor, + Wav2Vec2ProcessorWithLM: () => Wav2Vec2ProcessorWithLM, + WhisperProcessor: () => WhisperProcessor +}); - if (pattern.Regex !== undefined) { - // In certain cases, the pattern may contain unnecessary escape sequences (e.g., \# or \& or \~). - // i.e., valid in Python (where the patterns are exported from) but invalid in JavaScript (where the patterns are parsed). - // This isn't an issue when creating the regex w/o the 'u' flag, but it is when the 'u' flag is used. - // For this reason, it is necessary to remove these backslashes before creating the regex. - // See https://stackoverflow.com/a/63007777/13989043 for more information - let regex = pattern.Regex.replace(/\\([#&~])/g, '$1'); // TODO: add more characters to this list if necessary +// src/feature_extraction_utils.js +var FeatureExtractor = class extends Callable { + /** + * Create a feature extractor from a parsed `preprocessor_config.json`. + * + * @param {Object} config The configuration for the feature extractor. + */ + constructor(config) { + super(); + this.config = config; + } + /** + * Instantiate one of the feature extractor classes of the library from a pretrained model. + * + * The feature extractor class to instantiate is selected based on the `feature_extractor_type` property of + * the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model ID* of a pretrained feature extractor hosted inside a model repo on huggingface.co. + * Valid model IDs can be located at the root level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing feature_extractor files, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the feature_extractor. + * + * @returns {Promise} A new feature extractor instance. + */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const config = await getModelJSON(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME, true, options); + return new this(config); + } +}; +function validate_audio_inputs(audio, feature_extractor) { + if (!(audio instanceof Float32Array || audio instanceof Float64Array)) { + throw new Error( + `${feature_extractor} expects input to be a Float32Array or a Float64Array, but got ${audio?.constructor?.name ?? typeof audio} instead. If using the feature extractor directly, remember to use \`load_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.` + ); + } +} - // We also handle special cases where the regex contains invalid (non-JS compatible) syntax. - for (const [key, value] of PROBLEMATIC_REGEX_MAP) { - regex = regex.replaceAll(key, value); - } +// src/models/feature_extractors.js +var feature_extractors_exports = {}; +__export(feature_extractors_exports, { + ASTFeatureExtractor: () => ASTFeatureExtractor, + ChatterboxFeatureExtractor: () => ChatterboxFeatureExtractor, + ClapFeatureExtractor: () => ClapFeatureExtractor, + CohereAsrFeatureExtractor: () => CohereAsrFeatureExtractor, + DacFeatureExtractor: () => DacFeatureExtractor, + EncodecFeatureExtractor: () => EncodecFeatureExtractor, + FeatureExtractor: () => FeatureExtractor, + Gemma3nAudioFeatureExtractor: () => Gemma3nAudioFeatureExtractor, + Gemma4AudioFeatureExtractor: () => Gemma4AudioFeatureExtractor, + GraniteSpeechFeatureExtractor: () => GraniteSpeechFeatureExtractor, + MoonshineFeatureExtractor: () => MoonshineFeatureExtractor, + ParakeetFeatureExtractor: () => ParakeetFeatureExtractor, + PyAnnoteFeatureExtractor: () => PyAnnoteFeatureExtractor, + SeamlessM4TFeatureExtractor: () => SeamlessM4TFeatureExtractor, + SnacFeatureExtractor: () => SnacFeatureExtractor, + SpeechT5FeatureExtractor: () => SpeechT5FeatureExtractor, + VoxtralRealtimeFeatureExtractor: () => VoxtralRealtimeFeatureExtractor, + Wav2Vec2FeatureExtractor: () => Wav2Vec2FeatureExtractor, + WeSpeakerFeatureExtractor: () => WeSpeakerFeatureExtractor, + WhisperFeatureExtractor: () => WhisperFeatureExtractor +}); - return new RegExp(regex, 'gu'); +// ignore-modules:node:stream +var noop = () => { +}; +var Readable = { fromWeb: noop }; - } else if (pattern.String !== undefined) { - const escaped = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.escapeRegExp)(pattern.String); - // NOTE: if invert is true, we wrap the pattern in a group so that it is kept when performing .split() - return new RegExp(invert ? escaped : `(${escaped})`, 'gu'); +// ignore-modules:node:stream/promises +var noop2 = () => { +}; +var pipeline = noop2; - } else { - console.warn('Unknown pattern type:', pattern) - return null; +// src/utils/io.js +async function saveBlob(path, blob) { + if (apis.IS_BROWSER_ENV) { + if (apis.IS_WEBWORKER_ENV) { + throw new Error("Unable to save a file from a Web Worker."); } + const dataURL = URL.createObjectURL(blob); + const downloadLink = document.createElement("a"); + downloadLink.href = dataURL; + downloadLink.download = path; + downloadLink.click(); + downloadLink.remove(); + URL.revokeObjectURL(dataURL); + } else if (apis.IS_FS_AVAILABLE) { + const webStream = blob.stream(); + const nodeStream = Readable.fromWeb(webStream); + const fileStream = node_fs_default.createWriteStream(path); + await pipeline(nodeStream, fileStream); + } else { + throw new Error("Unable to save because filesystem is disabled in this environment."); + } } -/** - * Helper function to convert an Object to a Map - * @param {Object} obj The object to convert. - * @returns {Map} The map. - */ -function objectToMap(obj) { - return new Map(Object.entries(obj)); +// src/utils/audio.js +async function load_audio(url, sampling_rate) { + if (typeof AudioContext === "undefined") { + 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 response = await (await getFile(url)).arrayBuffer(); + const audioCTX = new AudioContext({ sampleRate: sampling_rate }); + if (typeof sampling_rate === "undefined") { + logger.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`); + } + const decoded = await audioCTX.decodeAudioData(response); + let audio; + if (decoded.numberOfChannels === 2) { + const SCALING_FACTOR = Math.sqrt(2); + const left = decoded.getChannelData(0); + const right = decoded.getChannelData(1); + audio = new Float32Array(left.length); + for (let i = 0; i < decoded.length; ++i) { + audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2; + } + } else { + audio = decoded.getChannelData(0); + } + return audio; } - -/** - * Helper function to convert a tensor to a list before decoding. - * @param {Tensor} tensor The tensor to convert. - * @returns {number[]} The tensor as a list. - */ -function prepareTensorForDecode(tensor) { - const dims = tensor.dims; - switch (dims.length) { - case 1: - return tensor.tolist(); - case 2: - if (dims[0] !== 1) { - throw new Error('Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.'); - } - return tensor.tolist()[0]; - default: - throw new Error(`Expected tensor to have 1-2 dimensions, got ${dims.length}.`) - } -} - -/** - * Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms - * @param {string} text The text to clean up. - * @returns {string} The cleaned up text. - */ -function clean_up_tokenization(text) { - // Clean up a list of simple English tokenization artifacts - // like spaces before punctuations and abbreviated forms - return text.replace(/ \./g, '.') - .replace(/ \?/g, '?') - .replace(/ \!/g, '!') - .replace(/ ,/g, ',') - .replace(/ \' /g, "'") - .replace(/ n\'t/g, "n't") - .replace(/ \'m/g, "'m") - .replace(/ \'s/g, "'s") - .replace(/ \'ve/g, "'ve") - .replace(/ \'re/g, "'re"); -} - -/** - * Helper function to remove accents from a string. - * @param {string} text The text to remove accents from. - * @returns {string} The text with accents removed. - */ -function remove_accents(text) { - return text.replace(/\p{M}/gu, ''); -} - -/** - * Helper function to lowercase a string and remove accents. - * @param {string} text The text to lowercase and remove accents from. - * @returns {string} The lowercased text with accents removed. - */ -function lowercase_and_remove_accent(text) { - return remove_accents(text.toLowerCase()); -} - - -/** - * Checks whether the given Unicode codepoint represents a CJK (Chinese, Japanese, or Korean) character. - * - * A "chinese character" is defined as anything in the CJK Unicode block: - * https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) - * - * Note that the CJK Unicode block is NOT all Japanese and Korean characters, despite its name. - * The modern Korean Hangul alphabet is a different block, as is Japanese Hiragana and Katakana. - * Those alphabets are used to write space-separated words, so they are not treated specially - * and are handled like all other languages. - * - * @param {number|bigint} cp The Unicode codepoint to check. - * @returns {boolean} True if the codepoint represents a CJK character, false otherwise. - */ -function is_chinese_char(cp) { - return ( - (cp >= 0x4E00 && cp <= 0x9FFF) - || (cp >= 0x3400 && cp <= 0x4DBF) - || (cp >= 0x20000 && cp <= 0x2A6DF) - || (cp >= 0x2A700 && cp <= 0x2B73F) - || (cp >= 0x2B740 && cp <= 0x2B81F) - || (cp >= 0x2B820 && cp <= 0x2CEAF) - || (cp >= 0xF900 && cp <= 0xFAFF) - || (cp >= 0x2F800 && cp <= 0x2FA1F) - ) +async function read_audio(url, sampling_rate) { + return await load_audio(url, sampling_rate); +} +function generalized_cosine_window(M, a_0) { + if (M < 1) { + return new Float64Array(); + } + if (M === 1) { + return new Float64Array([1]); + } + const a_1 = 1 - a_0; + const factor = 2 * Math.PI / (M - 1); + const cos_vals = new Float64Array(M); + for (let i = 0; i < M; ++i) { + cos_vals[i] = a_0 - a_1 * Math.cos(i * factor); + } + return cos_vals; +} +function hanning(M) { + return generalized_cosine_window(M, 0.5); +} +function hamming(M) { + return generalized_cosine_window(M, 0.54); +} +var HERTZ_TO_MEL_MAPPING = { + htk: (freq) => 2595 * Math.log10(1 + freq / 700), + kaldi: (freq) => 1127 * Math.log(1 + freq / 700), + slaney: (freq, min_log_hertz = 1e3, min_log_mel = 15, logstep = 27 / Math.log(6.4)) => freq >= min_log_hertz ? min_log_mel + Math.log(freq / min_log_hertz) * logstep : 3 * freq / 200 +}; +function hertz_to_mel(freq, mel_scale = "htk") { + const fn2 = HERTZ_TO_MEL_MAPPING[mel_scale]; + if (!fn2) { + throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); + } + return typeof freq === "number" ? fn2(freq) : freq.map((x) => fn2(x)); +} +var MEL_TO_HERTZ_MAPPING = { + htk: (mels) => 700 * (10 ** (mels / 2595) - 1), + kaldi: (mels) => 700 * (Math.exp(mels / 1127) - 1), + slaney: (mels, min_log_hertz = 1e3, min_log_mel = 15, logstep = Math.log(6.4) / 27) => mels >= min_log_mel ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) : 200 * mels / 3 +}; +function mel_to_hertz(mels, mel_scale = "htk") { + const fn2 = MEL_TO_HERTZ_MAPPING[mel_scale]; + if (!fn2) { + throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); + } + return typeof mels === "number" ? fn2(mels) : mels.map((x) => fn2(x)); } - -/** - * Helper function to fuse consecutive unknown tokens. - * @param {string[]} arr The list of input tokens - * @param {Map} tokens_to_ids The mapping from tokens to token ids. - * @param {number} unk_token_id The value to fuse on. - * @private - */ -function fuse_unk(arr, tokens_to_ids, unk_token_id) { - const fused = []; - let i = 0; - while (i < arr.length) { - fused.push(arr[i]) - if ((tokens_to_ids.get(arr[i]) ?? unk_token_id) !== unk_token_id) { - ++i; - continue; - } - - while (++i < arr.length && (tokens_to_ids.get(arr[i]) ?? unk_token_id) === unk_token_id) { - if (tokens_to_ids.get(fused.at(-1)) !== unk_token_id) { - fused[fused.length - 1] += arr[i]; - } - } +function _create_triangular_filter_bank(fft_freqs, filter_freqs) { + const filter_diff = Float64Array.from( + { length: filter_freqs.length - 1 }, + (_, i) => filter_freqs[i + 1] - filter_freqs[i] + ); + const slopes = Array.from( + { + length: fft_freqs.length + }, + () => new Array(filter_freqs.length) + ); + for (let j2 = 0; j2 < fft_freqs.length; ++j2) { + const slope = slopes[j2]; + for (let i = 0; i < filter_freqs.length; ++i) { + slope[i] = filter_freqs[i] - fft_freqs[j2]; } - - return fused; + } + const numFreqs = filter_freqs.length - 2; + const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length)); + for (let j2 = 0; j2 < fft_freqs.length; ++j2) { + const slope = slopes[j2]; + for (let i = 0; i < numFreqs; ++i) { + const down = -slope[i] / filter_diff[i]; + const up = slope[i + 2] / filter_diff[i + 1]; + ret[i][j2] = Math.max(0, Math.min(down, up)); + } + } + return ret; } - -/** - * Split a string on whitespace. - * @param {string} text The text to split. - * @returns {string[]} The split string. - */ -function whitespace_split(text) { - return text.match(/\S+/g) || []; +function linspace(start, end, num) { + const step = (end - start) / (num - 1); + return Float64Array.from({ length: num }, (_, i) => start + step * i); } - -const PUNCTUATION_REGEX = '\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E'; -const PUNCTUATION_ONLY_REGEX = new RegExp(`^[${PUNCTUATION_REGEX}]+$`, 'gu'); -const BLOOM_SPLIT_CHARS = '.,!?\u2026\u3002\uff0c\u3001\u0964\u06d4\u060c'; - -// A mapping of regex patterns to their equivalent (but possibly longer) JS-compatible versions. -const PROBLEMATIC_REGEX_MAP = new Map([ - // This uses the case insensitive group modifier, which is not supported in JavaScript. - // When parsing the regex, an "Invalid group" error is thrown. - ["(?i:'s|'t|'re|'ve|'m|'ll|'d)", "(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"], - - // Used to override the default (invalid) regex of the bloom pretokenizer. - // For more information, see https://github.com/huggingface/transformers.js/issues/94 - [` ?[^(\\s|[${BLOOM_SPLIT_CHARS}])]+`, ` ?[^\\s${BLOOM_SPLIT_CHARS}]+`], -]) - - -/** - * Represent a token added by the user on top of the existing Model vocabulary. - * AddedToken can be configured to specify the behavior they should have in various situations like: - * - Whether they should only match single words - * - Whether to include any whitespace on its left or right - */ -class AddedToken { - /** - * Creates a new instance of AddedToken. - * @param {Object} config Added token configuration object. - * @param {string} config.content The content of the added token. - * @param {number} config.id The id of the added token. - * @param {boolean} [config.single_word=false] Whether this token must be a single word or can break words. - * @param {boolean} [config.lstrip=false] Whether this token should strip whitespaces on its left. - * @param {boolean} [config.rstrip=false] Whether this token should strip whitespaces on its right. - * @param {boolean} [config.normalized=false] Whether this token should be normalized. - * @param {boolean} [config.special=false] Whether this token is special. - */ - constructor(config) { - this.content = config.content; - this.id = config.id; - this.single_word = config.single_word ?? false; - this.lstrip = config.lstrip ?? false; - this.rstrip = config.rstrip ?? false; - this.special = config.special ?? false; - this.normalized = config.normalized ?? null; - } -} - -/** - * Abstract base class for tokenizer models. - * - * @extends Callable - */ -class TokenizerModel extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Creates a new instance of TokenizerModel. - * @param {Object} config The configuration object for the TokenizerModel. - */ - constructor(config) { - super(); - this.config = config; - - /** @type {string[]} */ - this.vocab = []; - - /** - * A mapping of tokens to ids. - * @type {Map} - */ - this.tokens_to_ids = new Map(); - - this.unk_token_id = undefined; - this.unk_token = undefined; - this.end_of_word_suffix = undefined; - - /** @type {boolean} Whether to fuse unknown tokens when encoding. Defaults to false. */ - this.fuse_unk = this.config.fuse_unk ?? false; - } - - /** - * Instantiates a new TokenizerModel instance based on the configuration object provided. - * @param {Object} config The configuration object for the TokenizerModel. - * @param {...*} args Optional arguments to pass to the specific TokenizerModel constructor. - * @returns {TokenizerModel} A new instance of a TokenizerModel. - * @throws Will throw an error if the TokenizerModel type in the config is not recognized. - */ - static fromConfig(config, ...args) { - switch (config.type) { - case 'WordPiece': - return new WordPieceTokenizer(config); - case 'Unigram': - // @ts-ignore - return new Unigram(config, ...args); - case 'BPE': - return new BPE(config); - - default: - // Some older tokenizers, like `google-t5/t5-small`, `openai-community/gpt2`, and `distilbert/distilbert-base-uncased`, do not have a `type` field. - // In this case, we can infer the tokenizer type based on the structure of the `vocab` field and other properties. - if (config.vocab) { - if (Array.isArray(config.vocab)) { - // config.vocab is of type `[string, number][]` - // @ts-ignore - return new Unigram(config, ...args); - } else if (Object.hasOwn(config, 'continuing_subword_prefix') && Object.hasOwn(config, 'unk_token')) { - if (Object.hasOwn(config, 'merges')) { - return new BPE(config); - } else { - return new WordPieceTokenizer(config); - } - } else { - // @ts-ignore - return new LegacyTokenizerModel(config, ...args); - } - } - throw new Error(`Unknown TokenizerModel type: ${config.type}`); - } +function mel_filter_bank(num_frequency_bins, num_mel_filters, min_frequency, max_frequency, sampling_rate, norm = null, mel_scale = "htk", triangularize_in_mel_space = false) { + if (norm !== null && norm !== "slaney") { + throw new Error('norm must be one of null or "slaney"'); + } + if (num_frequency_bins < 2) { + throw new Error(`Require num_frequency_bins: ${num_frequency_bins} >= 2`); + } + if (min_frequency > max_frequency) { + throw new Error(`Require min_frequency: ${min_frequency} <= max_frequency: ${max_frequency}`); + } + const mel_min = hertz_to_mel(min_frequency, mel_scale); + const mel_max = hertz_to_mel(max_frequency, mel_scale); + const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2); + let filter_freqs = mel_to_hertz(mel_freqs, mel_scale); + let fft_freqs; + if (triangularize_in_mel_space) { + const fft_bin_width = sampling_rate / ((num_frequency_bins - 1) * 2); + fft_freqs = hertz_to_mel( + Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), + mel_scale + ); + filter_freqs = mel_freqs; + } else { + fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins); + } + const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs); + if (norm !== null && norm === "slaney") { + for (let i = 0; i < num_mel_filters; ++i) { + const filter = mel_filters[i]; + const enorm = 2 / (filter_freqs[i + 2] - filter_freqs[i]); + for (let j2 = 0; j2 < num_frequency_bins; ++j2) { + filter[j2] *= enorm; + } } - - /** - * Internal function to call the TokenizerModel instance. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} The encoded tokens. - */ - _call(tokens) { - tokens = this.encode(tokens); - if (this.fuse_unk) { - // Fuse unknown tokens - tokens = fuse_unk(tokens, this.tokens_to_ids, this.unk_token_id); - } - return tokens; + } + return mel_filters; +} +function padReflect(array, left, right) { + const padded = new array.constructor(array.length + left + right); + const w = array.length - 1; + for (let i = 0; i < array.length; ++i) { + padded[left + i] = array[i]; + } + for (let i = 1; i <= left; ++i) { + padded[left - i] = array[calculateReflectOffset(i, w)]; + } + for (let i = 1; i <= right; ++i) { + padded[w + left + i] = array[calculateReflectOffset(w - i, w)]; + } + return padded; +} +function _db_conversion_helper(spectrogram2, factor, reference, min_value, db_range) { + if (reference <= 0) { + throw new Error("reference must be greater than zero"); + } + if (min_value <= 0) { + throw new Error("min_value must be greater than zero"); + } + reference = Math.max(min_value, reference); + const logReference = Math.log10(reference); + for (let i = 0; i < spectrogram2.length; ++i) { + spectrogram2[i] = factor * Math.log10(Math.max(min_value, spectrogram2[i]) - logReference); + } + if (db_range !== null) { + if (db_range <= 0) { + throw new Error("db_range must be greater than zero"); } - - /** - * Encodes a list of tokens into a list of token IDs. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} The encoded tokens. - * @throws Will throw an error if not implemented in a subclass. - */ - encode(tokens) { - throw Error("encode should be implemented in subclass.") + const maxValue = max(spectrogram2)[0] - db_range; + for (let i = 0; i < spectrogram2.length; ++i) { + spectrogram2[i] = Math.max(spectrogram2[i], maxValue); } - - /** - * Converts a list of tokens into a list of token IDs. - * @param {string[]} tokens The tokens to convert. - * @returns {number[]} The converted token IDs. - */ - convert_tokens_to_ids(tokens) { - return tokens.map(t => this.tokens_to_ids.get(t) ?? this.unk_token_id); + } + return spectrogram2; +} +function amplitude_to_db(spectrogram2, reference = 1, min_value = 1e-5, db_range = null) { + return _db_conversion_helper(spectrogram2, 20, reference, min_value, db_range); +} +function power_to_db(spectrogram2, reference = 1, min_value = 1e-10, db_range = null) { + return _db_conversion_helper(spectrogram2, 10, reference, min_value, db_range); +} +async function spectrogram(waveform, window2, frame_length, hop_length, { + fft_length = null, + power = 1, + center = true, + pad_mode = "reflect", + onesided = true, + preemphasis = null, + preemphasis_htk_flavor = true, + mel_filters = null, + mel_floor = 1e-10, + log_mel = null, + max_log_mel = null, + reference = 1, + min_value = 1e-10, + db_range = null, + remove_dc_offset = null, + // Custom parameters for efficiency reasons + min_num_frames = null, + max_num_frames = null, + do_pad = true, + transpose = false, + mel_offset = 0, + mel_floor_mode = "clamp" +} = {}) { + const window_length = window2.length; + if (fft_length === null) { + fft_length = frame_length; + } + if (frame_length > fft_length) { + throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`); + } + if (window_length !== frame_length) { + throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`); + } + if (hop_length <= 0) { + throw new Error("hop_length must be greater than zero"); + } + if (power === null && mel_filters !== 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 (!preemphasis_htk_flavor) { + throw new Error("`preemphasis_htk_flavor=false` is not currently supported."); + } + if (center) { + const padding = Math.floor(frame_length / 2); + switch (pad_mode) { + case "reflect": { + waveform = padReflect(waveform, padding, padding); + break; + } + case "constant": { + const padded = new waveform.constructor(waveform.length + 2 * padding); + padded.set(waveform, padding); + waveform = padded; + break; + } + case "semicausal": { + const padded = new waveform.constructor(waveform.length + padding); + padded.set(waveform, padding); + waveform = padded; + break; + } + default: + throw new Error(`pad_mode="${pad_mode}" not implemented yet.`); } - - /** - * Converts a list of token IDs into a list of tokens. - * @param {number[]|bigint[]} ids The token IDs to convert. - * @returns {string[]} The converted tokens. - */ - convert_ids_to_tokens(ids) { - return ids.map(i => this.vocab[i] ?? this.unk_token); + } + let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length)); + if (min_num_frames !== null && num_frames < min_num_frames) { + num_frames = min_num_frames; + } + const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length; + let d1 = num_frames; + let d1Max = num_frames; + if (max_num_frames !== null) { + if (max_num_frames > num_frames) { + if (do_pad) { + d1Max = max_num_frames; + } + } else { + d1Max = d1 = max_num_frames; } -} - -/** - * A subclass of TokenizerModel that uses WordPiece encoding to encode tokens. - * @extends TokenizerModel - */ -class WordPieceTokenizer extends TokenizerModel { - /** - * @param {Object} config The configuration object. - * @param {Object} config.vocab A mapping of tokens to ids. - * @param {string} config.unk_token The unknown token string. - * @param {string} config.continuing_subword_prefix The prefix to use for continuing subwords. - * @param {number} [config.max_input_chars_per_word=100] The maximum number of characters per word. - */ - constructor(config) { - super(config); - /** - * A mapping of tokens to ids. - * @type {Map} - */ - this.tokens_to_ids = objectToMap(config.vocab); - - /** - * The id of the unknown token. - * @type {number} - */ - this.unk_token_id = this.tokens_to_ids.get(config.unk_token); - - /** - * The unknown token string. - * @type {string} - */ - this.unk_token = config.unk_token; - - /** - * The maximum number of characters allowed per word. - * @type {number} - */ - this.max_input_chars_per_word = config.max_input_chars_per_word ?? 100; - - /** - * An array of tokens. - * @type {string[]} - */ - this.vocab = new Array(this.tokens_to_ids.size); - for (const [key, value] of this.tokens_to_ids) { - this.vocab[value] = key; - } + } + const fft = new FFT(fft_length); + const inputBuffer = new Float64Array(fft_length); + const outputBuffer = new Float64Array(fft.outputBufferSize); + const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max); + for (let i = 0; i < d1; ++i) { + const offset = i * hop_length; + const buffer_size = Math.min(waveform.length - offset, frame_length); + if (buffer_size !== frame_length) { + inputBuffer.fill(0, 0, frame_length); + } + for (let j2 = 0; j2 < buffer_size; ++j2) { + inputBuffer[j2] = waveform[offset + j2]; + } + if (remove_dc_offset) { + let sum = 0; + for (let j2 = 0; j2 < buffer_size; ++j2) { + sum += inputBuffer[j2]; + } + const mean2 = sum / buffer_size; + for (let j2 = 0; j2 < buffer_size; ++j2) { + inputBuffer[j2] -= mean2; + } } - - /** - * Encodes an array of tokens using WordPiece encoding. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} An array of encoded tokens. - */ - encode(tokens) { - const outputTokens = []; - for (const token of tokens) { - const chars = [...token]; - if (chars.length > this.max_input_chars_per_word) { - outputTokens.push(this.unk_token); - continue; - } - - let isUnknown = false; - let start = 0; - const subTokens = []; - - while (start < chars.length) { - let end = chars.length; - let currentSubstring = null; - while (start < end) { - let substr = chars.slice(start, end).join(''); - - if (start > 0) { - substr = this.config.continuing_subword_prefix + substr; - } - if (this.tokens_to_ids.has(substr)) { - currentSubstring = substr; - break; - } - - --end; - } - if (currentSubstring === null) { - isUnknown = true; - break; - } - subTokens.push(currentSubstring); - start = end; - } - if (isUnknown) { - outputTokens.push(this.unk_token); - } else { - outputTokens.push(...subTokens); - } - } - - return outputTokens; + if (preemphasis !== null) { + for (let j2 = buffer_size - 1; j2 >= 1; --j2) { + inputBuffer[j2] -= preemphasis * inputBuffer[j2 - 1]; + } + inputBuffer[0] *= 1 - preemphasis; } - -} - -/** - * Class representing a Unigram tokenizer model. - * @extends TokenizerModel - */ -class Unigram extends TokenizerModel { - /** - * Create a new Unigram tokenizer model. - * @param {Object} config The configuration object for the Unigram model. - * @param {number} config.unk_id The ID of the unknown token - * @param {[string, number][]} config.vocab A 2D array representing a mapping of tokens to scores. - * @param {Object} moreConfig Additional configuration object for the Unigram model. - */ - constructor(config, moreConfig) { - super(config); - - const vocabSize = config.vocab.length; - this.vocab = new Array(vocabSize); - /** @type {number[]} */ - this.scores = new Array(vocabSize); - for (let i = 0; i < vocabSize; ++i) { - [this.vocab[i], this.scores[i]] = config.vocab[i]; - } - - this.unk_token_id = config.unk_id; - this.unk_token = this.vocab[config.unk_id]; - - this.tokens_to_ids = new Map(this.vocab.map((x, i) => [x, i])); - this.bos_token = ' '; // beginning of a sentence token - - this.bos_token_id = this.tokens_to_ids.get(this.bos_token); // NOTE: may be undefined - this.eos_token = moreConfig.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,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.min)(this.scores)[0]; - - this.unk_score = this.minScore - 10.0; - this.scores[this.unk_token_id] = this.unk_score; - - this.trie = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.CharTrie(); - this.trie.extend(this.vocab); - - // NOTE: `fuse_unk` is hardcoded to true for Unigram models - // See: https://github.com/huggingface/tokenizers/blob/b58227c7f1ccf8b73ee2268354336da56d91e492/tokenizers/src/models/unigram/model.rs#L119 - this.fuse_unk = true; + for (let j2 = 0; j2 < window2.length; ++j2) { + inputBuffer[j2] *= window2[j2]; } - - /** - * Populates lattice nodes. - * @param {TokenLattice} lattice The token lattice to populate with nodes. - */ - populateNodes(lattice) { - const chars = lattice.chars; - const mblen = 1; - let beginPos = 0; - while (beginPos < chars.length) { - let hasSingleNode = false; - - const tokens = []; - const sliced = chars.slice(beginPos).join(''); - const prefixedTokens = this.trie.commonPrefixSearch(sliced); - for (const token of prefixedTokens) { - tokens.push(token); - const tokenId = this.tokens_to_ids.get(token); - const tokenScore = this.scores[tokenId]; - const n = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.len)(token); - lattice.insert(beginPos, n, tokenScore, tokenId); - if (!hasSingleNode && n === mblen) { - hasSingleNode = true; - } - } - if (!hasSingleNode) { - lattice.insert(beginPos, mblen, this.unk_score, this.unk_token_id); - } - beginPos += mblen; - } + fft.realTransform(outputBuffer, inputBuffer); + for (let j2 = 0; j2 < num_frequency_bins; ++j2) { + const j22 = j2 << 1; + transposedMagnitudeData[j2 * d1Max + i] = outputBuffer[j22] ** 2 + outputBuffer[j22 + 1] ** 2; } - - /** - * Encodes an array of tokens into an array of subtokens using the unigram model. - * - * @param {string} normalized The normalized string. - * @returns {string[]} An array of subtokens obtained by encoding the input tokens using the unigram model. - */ - tokenize(normalized) { - const lattice = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.TokenLattice(normalized, this.bos_token_id, this.eos_token_id); - this.populateNodes(lattice); - return lattice.tokens(); + } + if (power !== null && power !== 2) { + const pow = power / 2; + for (let i = 0; i < transposedMagnitudeData.length; ++i) { + transposedMagnitudeData[i] **= pow; } - - /** - * Encodes an array of tokens using Unigram encoding. - * @param {string[]} tokens The tokens to encode. - * @returns {string[]} An array of encoded tokens. - */ - encode(tokens) { - const toReturn = []; - for (const token of tokens) { - const tokenized = this.tokenize(token); - toReturn.push(...tokenized); - } - return toReturn; + } + const num_mel_filters = mel_filters.length; + let mel_spec = await matmul( + // TODO: Make `mel_filters` a Tensor during initialization + new Tensor3("float32", mel_filters.flat(), [num_mel_filters, num_frequency_bins]), + new Tensor3("float32", transposedMagnitudeData, [num_frequency_bins, d1Max]) + ); + if (transpose) { + mel_spec = mel_spec.transpose(1, 0); + } + const mel_spec_data = ( + /** @type {Float32Array} */ + mel_spec.data + ); + if (mel_floor_mode === "add") { + for (let i = 0; i < mel_spec_data.length; ++i) { + mel_spec_data[i] = mel_offset + mel_spec_data[i] + mel_floor; } - -} - -/** - * Returns list of utf-8 byte and a mapping to unicode strings. - * Specifically avoids mapping to whitespace/control characters the BPE code barfs on. - * @returns {Object} Object with utf-8 byte keys and unicode string values. - */ -const BYTES_TO_UNICODE = (() => { - // Returns list of utf-8 byte and a mapping to unicode strings. - // We specifically avoids mapping to whitespace/control characters - // the bpe code barfs on. - - const bs = [ - ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i) => i + "!".charCodeAt(0)), - ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i) => i + "¡".charCodeAt(0)), - ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i) => i + "®".charCodeAt(0)), - ]; - const cs = bs.slice(); - let n = 0; - for (let b = 0; b < 256; ++b) { - if (!bs.includes(b)) { - bs.push(b); - cs.push(256 + n); - n += 1; - } + } else { + for (let i = 0; i < mel_spec_data.length; ++i) { + mel_spec_data[i] = mel_offset + Math.max(mel_floor, mel_spec_data[i]); } - const ccs = cs.map(n => String.fromCharCode(n)); - return Object.fromEntries(bs.map((b, i) => [b, ccs[i]])); -})(); - -const UNICODE_TO_BYTES = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.reverseDictionary)(BYTES_TO_UNICODE); - - -/** - * @typedef {Object} BPENode - * @property {string} token The token associated with the node - * @property {number} bias A positional bias for the node. - * @property {number} [score] The score of the node. - * @property {BPENode} [prev] The previous node in the linked list. - * @property {BPENode} [next] The next node in the linked list. - */ - -/** - * BPE class for encoding text into Byte-Pair-Encoding (BPE) tokens. - * @extends TokenizerModel - */ -class BPE extends TokenizerModel { - /** - * Create a BPE instance. - * @param {Object} config The configuration object for BPE. - * @param {Object} config.vocab A mapping of tokens to ids. - * @param {string[]|[string, string][]} config.merges An array of BPE merges as strings. - * @param {string} config.unk_token The unknown token used for out of vocabulary words. - * @param {string} config.end_of_word_suffix The suffix to place at the end of each word. - * @param {string} [config.continuing_subword_suffix] The suffix to insert between words. - * @param {boolean} [config.byte_fallback=false] Whether to use spm byte-fallback trick (defaults to False) - * @param {boolean} [config.ignore_merges=false] Whether or not to match tokens with the vocab before using merges. - */ - constructor(config) { - super(config); - - /** @type {Map} */ - this.tokens_to_ids = objectToMap(config.vocab); - - this.unk_token_id = this.tokens_to_ids.get(config.unk_token); - this.unk_token = config.unk_token; - - this.vocab = new Array(this.tokens_to_ids.size); - for (const [key, value] of this.tokens_to_ids) { - this.vocab[value] = key; - } - - // Tokenizers >= 0.20.0 serializes BPE merges as a [string, string][] instead of a string[], - // which resolves the ambiguity for merges containing spaces. - const use_new_merge_format = Array.isArray(config.merges[0]); - - /** @type {[string, string][]} */ - this.merges = use_new_merge_format - ? /** @type {[string, string][]} */(config.merges) - : (/** @type {string[]} */(config.merges)).map(x => /** @type {[string, string]} */(x.split(' ', 2))); - this.bpe_ranks = new Map(this.merges.map((x, i) => [JSON.stringify(x), i])); - - this.end_of_word_suffix = config.end_of_word_suffix; - - // NOTE: `continuing_subword_suffix` is custom (to support `BlenderbotSmallTokenizer`) - this.continuing_subword_suffix = config.continuing_subword_suffix ?? null; - - this.byte_fallback = this.config.byte_fallback ?? false; - - if (this.byte_fallback) { - this.text_encoder = new TextEncoder(); + } + if (power !== null && log_mel !== null) { + const o = Math.min(mel_spec_data.length, d1 * num_mel_filters); + switch (log_mel) { + case "log": + for (let i = 0; i < o; ++i) { + mel_spec_data[i] = Math.log(mel_spec_data[i]); } - - this.ignore_merges = this.config.ignore_merges ?? false; - - /** - * The maximum length we should cache in a model. - * Strings that are too long have minimal chances to cache hit anyway - */ - this.max_length_to_cache = 256; - - /** - * The default capacity for a `BPE`'s internal cache. - */ - this.cache_capacity = 10000; - this.cache = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.LRUCache(this.cache_capacity); - } - - /** - * Clears the cache. - */ - clear_cache() { - this.cache.clear(); - } - - /** - * Apply Byte-Pair-Encoding (BPE) to a given token. Efficient heap-based priority - * queue implementation adapted from https://github.com/belladoreai/llama-tokenizer-js. - * @param {string} token The token to encode. - * @returns {string[]} The BPE encoded tokens. - */ - bpe(token) { - if (token.length === 0) { - return []; + break; + case "log10": + for (let i = 0; i < o; ++i) { + mel_spec_data[i] = Math.log10(mel_spec_data[i]); } - - const cached = this.cache.get(token); - if (cached !== undefined) { - return cached; + break; + case "log10_max_norm": { + for (let i = 0; i < o; ++i) { + mel_spec_data[i] = Math.log10(mel_spec_data[i]); } - - const word = Array.from(token); - if (this.end_of_word_suffix) { - word[word.length - 1] += this.end_of_word_suffix; + const logMax = max_log_mel ?? max(mel_spec_data)[0]; + const threshold = logMax - 8; + for (let i = 0; i < o; ++i) { + mel_spec_data[i] = (Math.max(mel_spec_data[i], threshold) + 4) / 4; } - - let result = []; - if (word.length > 1) { - // Create a priority queue to store the nodes that will be merged. - // The comparator function compares the scores of the nodes. - const queue = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.PriorityQueue((a, b) => a.score < b.score); - - // Construct a doubly-linked list of nodes that will be inserted into the priority queue, - // starting with the individual characters. We also populate each node with a positional - // bias to break ties in the priority queue. - let startingNode = { - token: word[0], - bias: 0, - prev: null, - next: null, - } - - let previousNode = startingNode - for (let i = 1; i < word.length; ++i) { - const currentNode = { - bias: i / word.length, // Add fractional component to break ties - token: word[i], - prev: previousNode, - next: null, - } - previousNode.next = currentNode - this._add_node(queue, previousNode) - previousNode = currentNode - } - - while (!queue.isEmpty()) { - // Get the next node with the highest priority - const node = queue.pop(); - - // Check that this merge is still possible - if (node.deleted || !node.next || node.next.deleted) continue; - - // Here, we mark the current node (left side of the merge) and the next node (right side of the merge) as deleted. - // This is because they will both be replaced by a new node representing the merge result. - node.deleted = true; - node.next.deleted = true; - - // Next, we fix the node that comes before the current node (i.e., left side of the merge). - if (node.prev) { - - // Make a shallow copy of the previous node - const newPreviousNode = { ...node.prev }; - - // Mark the old previous node as deleted. This avoids erroneous merges later, - // because there may still be references to this node in the priority queue. - node.prev.deleted = true; - node.prev = newPreviousNode; - - // Update the reference of the previous node, by pointing its previous node to this new previous node. - if (newPreviousNode.prev) { - newPreviousNode.prev.next = newPreviousNode; - } else { - // If the previous of the previous node does not exist, it means that - // `newPreviousNode` must be the new `startingNode`. - startingNode = newPreviousNode; - } - } - - // Create a new node which represents the result of the merge. - const merged = { - token: node.token + node.next.token, - bias: node.bias, - prev: node.prev, - next: node.next.next, - } - - // We now consider where we can add the new merged node to the priority queue: - // 1. prev <-> merged - if (merged.prev) { - merged.prev.next = merged; - this._add_node(queue, merged.prev); - } else { - // If `merged.prev` does not exist, then `merged` must be the new `startingNode`. - startingNode = merged; - } - - // 2. merged <-> next - if (merged.next) { - merged.next.prev = merged; - this._add_node(queue, merged); - } - } - - // Traverse the linked list, starting from the `startingNode`, and collect the tokens. - for (let currentNode = startingNode; currentNode !== null; currentNode = currentNode.next) { - result.push(currentNode.token); - } + break; + } + case "dB": + if (power === 1) { + amplitude_to_db(mel_spec_data, reference, min_value, db_range); + } else if (power === 2) { + power_to_db(mel_spec_data, reference, min_value, db_range); } else { - result = word; - } - - // Possibly append suffix - if (this.continuing_subword_suffix) { - // Do not append suffix to the last token - for (let i = 0; i < result.length - 1; ++i) { - result[i] += this.continuing_subword_suffix; - } - } - - if (token.length < this.max_length_to_cache) { - // Save the result to the cache - this.cache.put(token, result); - } - - return result; - } - - - /** - * Helper function to add a node to the priority queue. - * @param {PriorityQueue} queue - * @param {BPENode} node - * @private - */ - _add_node(queue, node) { - // `score` is a measure of the merge priority: lower means higher priority - // We use the BPE rank as a measure of priority (i.e., the local of the merge in the merges list) - // We also add a fractional component to the score to break ties (with the earlier character having higher priority) - const rank = this.bpe_ranks.get(JSON.stringify([node.token, node.next.token])); - if (rank !== undefined) { - node.score = rank + node.bias; - queue.push(node); - } - } - - /** - * Encodes the input sequence of tokens using the BPE algorithm and returns the resulting subword tokens. - * @param {string[]} tokens The input sequence of tokens to encode. - * @returns {string[]} The resulting subword tokens after applying the BPE algorithm to the input sequence of tokens. - */ - encode(tokens) { - const outputTokens = []; - - for (const token of tokens) { - if (this.ignore_merges && this.tokens_to_ids.has(token)) { - outputTokens.push(token); - continue; - } - const bpe_token_list = this.bpe(token); - - for (const t of bpe_token_list) { - if (this.tokens_to_ids.has(t)) { - outputTokens.push(t); - } else if (this.byte_fallback) { - const byteTokens = Array.from(this.text_encoder.encode(t)) - .map(x => `<0x${x.toString(16).toUpperCase().padStart(2, '0')}>`); - if (byteTokens.every(x => this.tokens_to_ids.has(x))) { - // Ensure the byte tokens are actually in the vocabulary, otherwise - // we fall back to the unknown token. For more information, see - // https://github.com/huggingface/transformers/issues/28096. - outputTokens.push(...byteTokens); - } else { - outputTokens.push(this.unk_token); - } - } else { - outputTokens.push(this.unk_token); - } - } - } - - return outputTokens; - } - -} - -/** - * Legacy tokenizer class for tokenizers with only a vocabulary. - */ -class LegacyTokenizerModel extends TokenizerModel { - /** - * Create a LegacyTokenizerModel instance. - * @param {Object} config The configuration object for LegacyTokenizerModel. - * @param {Object} config.vocab A (possibly nested) mapping of tokens to ids. - * @param {Object} moreConfig Additional configuration object for the LegacyTokenizerModel model. - */ - constructor(config, moreConfig) { - super(config); - - /**@type {Map} */ - this.tokens_to_ids = objectToMap( - moreConfig.target_lang - ? config.vocab[moreConfig.target_lang] - : config.vocab - ); - - this.bos_token = moreConfig.bos_token; - this.bos_token_id = this.tokens_to_ids.get(this.bos_token); - - this.eos_token = moreConfig.eos_token; - this.eos_token_id = this.tokens_to_ids.get(this.eos_token); - - this.pad_token = moreConfig.pad_token; - this.pad_token_id = this.tokens_to_ids.get(this.pad_token); - - this.unk_token = moreConfig.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 [key, value] of this.tokens_to_ids) { - this.vocab[value] = key; - } - } - - encode(tokens) { - return tokens; + throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`); + } + break; + default: + throw new Error( + `log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${log_mel}'` + ); } + } + return mel_spec; +} +function window_function(window_length, name, { periodic = true, frame_length = null, center = true } = {}) { + const length = periodic ? window_length + 1 : window_length; + let window2; + switch (name) { + case "boxcar": + window2 = new Float64Array(length).fill(1); + break; + case "hann": + case "hann_window": + window2 = hanning(length); + break; + case "hamming": + window2 = hamming(length); + break; + case "povey": + window2 = hanning(length).map((x) => Math.pow(x, 0.85)); + break; + default: + throw new Error(`Unknown window type ${name}.`); + } + if (periodic) { + window2 = window2.subarray(0, window_length); + } + if (frame_length === null || window_length === frame_length) { + return window2; + } + if (window_length > frame_length) { + throw new Error( + `Length of the window (${window_length}) may not be larger than frame_length (${frame_length})` + ); + } + const padded = new Float64Array(frame_length); + const offset = center ? Math.floor((frame_length - window_length) / 2) : 0; + padded.set(window2, offset); + return padded; +} +function encodeWAV(chunks, rate) { + const totalLength = chunks.reduce((acc, chunk2) => acc + chunk2.length, 0); + const buffer = new ArrayBuffer(44); + const view = new DataView(buffer); + writeString(view, 0, "RIFF"); + view.setUint32(4, 36 + totalLength * 4, true); + writeString(view, 8, "WAVE"); + writeString(view, 12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 3, true); + view.setUint16(22, 1, true); + view.setUint32(24, rate, true); + view.setUint32(28, rate * 4, true); + view.setUint16(32, 4, true); + view.setUint16(34, 32, true); + writeString(view, 36, "data"); + view.setUint32(40, totalLength * 4, true); + return new Blob( + [ + buffer, + ...chunks.map( + (chunk2) => chunk2.buffer instanceof ArrayBuffer ? new Uint8Array(chunk2.buffer, chunk2.byteOffset, chunk2.byteLength) : chunk2.slice() + ) + ], + { type: "audio/wav" } + ); } - - -/** - * A base class for text normalization. - * @abstract - */ -class Normalizer extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * @param {Object} config The configuration object for the normalizer. - */ - constructor(config) { - super(); - this.config = config; +function writeString(view, offset, string) { + for (let i = 0; i < string.length; ++i) { + view.setUint8(offset + i, string.charCodeAt(i)); + } +} +var RawAudio = class { + /** + * Create a new `RawAudio` object. + * @param {Float32Array|Float32Array[]} audio Audio data, either as a single `Float32Array` chunk or multiple `Float32Array` chunks. + * @param {number} sampling_rate Sampling rate of the audio data + */ + constructor(audio, sampling_rate) { + this.audio = audio; + this.sampling_rate = sampling_rate; + } + /** + * Get the audio data, accumulating all chunks if necessary. + * @returns {Float32Array} The audio data. + */ + get data() { + if (Array.isArray(this.audio)) { + if (this.audio.length === 0) { + return new Float32Array(0); + } + if (this.audio.length === 1) { + return this.audio[0]; + } + const totalLength = this.audio.reduce((acc, chunk2) => acc + chunk2.length, 0); + const result = new Float32Array(totalLength); + let offset = 0; + for (const chunk2 of this.audio) { + result.set(chunk2, offset); + offset += chunk2.length; + } + return result; + } else { + return this.audio; } - - /** - * Factory method for creating normalizers from config objects. - * @static - * @param {Object} config The configuration object for the normalizer. - * @returns {Normalizer} A Normalizer object. - * @throws {Error} If an unknown Normalizer type is specified in the config. - */ - static fromConfig(config) { - if (config === null) return null; - switch (config.type) { - case 'BertNormalizer': - return new BertNormalizer(config); - case 'Precompiled': - return new Precompiled(config); - case 'Sequence': - return new NormalizerSequence(config); - case 'Replace': - return new Replace(config); - case 'NFC': - return new NFC(config); - case 'NFD': - return new NFD(config); - case 'NFKC': - return new NFKC(config); - case 'NFKD': - return new NFKD(config); - case 'Strip': - return new StripNormalizer(config); - case 'StripAccents': - return new StripAccents(config); - case 'Lowercase': - return new Lowercase(config); - case 'Prepend': - return new Prepend(config); - default: - throw new Error(`Unknown Normalizer type: ${config.type}`); - } + } + /** + * Convert the audio to a blob. + * @returns {Blob} + */ + toBlob() { + let audio = this.audio; + if (audio instanceof Float32Array) { + audio = [audio]; } + return encodeWAV(audio, this.sampling_rate); + } + /** + * Save the audio to a wav file. + * @param {string} path + * @returns {Promise} + */ + async save(path) { + return saveBlob(path, this.toBlob()); + } +}; - /** - * Normalize the input text. - * @abstract - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - * @throws {Error} If this method is not implemented in a subclass. - */ - normalize(text) { - throw Error("normalize should be implemented in subclass.") +// src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js +var ASTFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + const sampling_rate = this.config.sampling_rate; + const mel_filters = mel_filter_bank( + 257, + // num_frequency_bins + this.config.num_mel_bins, + // num_mel_filters + 20, + // min_frequency + Math.floor(sampling_rate / 2), + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "kaldi", + // mel_scale + true + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = window_function(400, "hann", { + periodic: false + }); + this.mean = this.config.mean; + this.std = this.config.std; + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, max_length) { + return spectrogram( + waveform, + this.window, + // window + 400, + // frame_length + 160, + // hop_length + { + fft_length: 512, + power: 2, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: 1192092955078125e-22, + remove_dc_offset: true, + // Custom + max_num_frames: max_length, + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + validate_audio_inputs(audio, "ASTFeatureExtractor"); + const features = await this._extract_fbank_features(audio, this.config.max_length); + if (this.config.do_normalize) { + const denom = this.std * 2; + const features_data = features.data; + for (let i = 0; i < features_data.length; ++i) { + features_data[i] = (features_data[i] - this.mean) / denom; + } } + return { + input_values: features.unsqueeze_(0) + }; + } +}; - /** - * Alias for {@link Normalizer#normalize}. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - _call(text) { - return this.normalize(text); +// src/models/encodec/feature_extraction_encodec.js +var EncodecFeatureExtractor = class extends FeatureExtractor { + /** + * Asynchronously extracts input values from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. + */ + async _call(audio) { + validate_audio_inputs(audio, "EncodecFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const num_channels = this.config.feature_size; + if (audio.length % num_channels !== 0) { + throw new Error( + `The length of the audio data must be a multiple of the number of channels (${num_channels}).` + ); } + const shape = [ + 1, + num_channels, + audio.length / num_channels + ]; + return { + input_values: new Tensor3("float32", audio, shape) + }; + } +}; -} +// src/models/chatterbox/feature_extraction_chatterbox.js +var ChatterboxFeatureExtractor = class extends FeatureExtractor { + /** + * Asynchronously extracts input values from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. + */ + async _call(audio) { + validate_audio_inputs(audio, "ChatterboxFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const shape = [ + 1, + audio.length + /* num_samples */ + ]; + return { + input_values: new Tensor3("float32", audio, shape) + }; + } +}; -/** - * Replace normalizer that replaces occurrences of a pattern with a given string or regular expression. - * @extends Normalizer - */ -class Replace extends Normalizer { - /** - * Normalize the input text by replacing the pattern with the content. - * @param {string} text The input text to be normalized. - * @returns {string} The normalized text after replacing the pattern with the content. - */ - normalize(text) { - const pattern = createPattern(this.config.pattern); - return pattern === null - ? text - : text.replaceAll(pattern, this.config.content); +// src/models/clap/feature_extraction_clap.js +var ClapFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + this.mel_filters = mel_filter_bank( + this.config.nb_frequency_bins, + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + this.config.frequency_min, + // min_frequency + this.config.frequency_max, + // max_frequency + this.config.sampling_rate, + // sampling_rate + null, + // norm + "htk" + // mel_scale + ); + this.mel_filters_slaney = mel_filter_bank( + this.config.nb_frequency_bins, + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + this.config.frequency_min, + // min_frequency + this.config.frequency_max, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + this.window = window_function(this.config.fft_window_size, "hann"); + } + /** + * Extracts the mel spectrogram and prepares it for the mode based on the `truncation` and `padding` arguments. + * + * Four different path are possible: + * - `truncation="fusion"` and the length of the waveform is greater than the max length: the mel spectrogram + * will be computed on the entire audio. 3 random crops and a dowsampled version of the full mel spectrogram + * are then stacked together. They will later be used for `feature_fusion`. + * - `truncation="rand_trunc"` and the length of the waveform is smaller than the max length: the audio is + * padded based on `padding`. + * - `truncation="fusion"` and the length of the waveform is smaller than the max length: the audio is padded + * based on `padding`, and is repeated `4` times. + * - `truncation="rand_trunc"` and the length of the waveform is greater than the max length: the mel + * spectrogram will be computed on a random crop of the waveform. + * + * @param {Float32Array|Float64Array} waveform The input waveform. + * @param {number} max_length The maximum length of the waveform. + * @param {string} truncation The truncation strategy to use. + * @param {string} padding The padding strategy to use. + * @returns {Promise} An object containing the mel spectrogram data as a Float32Array, its dimensions as an array of numbers, and a boolean indicating whether the waveform was longer than the max length. + * @private + */ + async _get_input_mel(waveform, max_length, truncation, padding) { + let input_mel; + let longer = false; + const diff = waveform.length - max_length; + if (diff > 0) { + if (truncation === "rand_trunc") { + longer = true; + const idx = Math.floor(random.random() * (diff + 1)); + waveform = waveform.subarray(idx, idx + max_length); + input_mel = await this._extract_fbank_features( + waveform, + this.mel_filters_slaney, + this.config.nb_max_samples + ); + } else { + throw new Error(`Truncation strategy "${truncation}" not implemented`); + } + } else { + if (diff < 0) { + let padded = new Float64Array(max_length); + padded.set(waveform); + if (padding === "repeat") { + for (let i = waveform.length; i < max_length; i += waveform.length) { + padded.set(waveform.subarray(0, Math.min(waveform.length, max_length - i)), i); + } + } else if (padding === "repeatpad") { + for (let i = waveform.length; i < -diff; i += waveform.length) { + padded.set(waveform, i); + } + } + waveform = padded; + } + if (truncation === "fusion") { + throw new Error(`Truncation strategy "${truncation}" not implemented`); + } + input_mel = await this._extract_fbank_features( + waveform, + this.mel_filters_slaney, + this.config.nb_max_samples + ); } -} - -/** - * A normalizer that applies Unicode normalization to the input text. - * @extends Normalizer - * @abstract - */ -class UnicodeNormalizer extends Normalizer { - /** - * @type {string} The Unicode normalization form to apply. - * Should be one of: 'NFC', 'NFD', 'NFKC', or 'NFKD'. - */ - form = undefined; + return input_mel.unsqueeze_(0); + } + /** + * Compute the log-mel spectrogram of the provided `waveform` using the Hann window. + * In CLAP, two different filter banks are used depending on the truncation pattern: + * - `self.mel_filters`: they correspond to the default parameters of `torchaudio` which can be obtained from + * calling `torchaudio.transforms.MelSpectrogram().mel_scale.fb`. These filters are used when `truncation` + * is set to `"fusion"`. + * - `self.mel_filteres_slaney` : they correspond to the default parameters of `librosa` which used + * `librosa.filters.mel` when computing the mel spectrogram. These filters were only used in the original + * implementation when the truncation mode is not `"fusion"`. + * + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number[][]} mel_filters The mel filters to use. + * @param {number} [max_length=null] The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, mel_filters, max_length = null) { + return spectrogram( + waveform, + this.window, + // window + this.config.fft_window_size, + // frame_length + this.config.hop_length, + // hop_length + { + power: 2, + mel_filters, + log_mel: "dB", + // Custom + max_num_frames: max_length, + do_pad: false, + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio, { max_length = null } = {}) { + validate_audio_inputs(audio, "ClapFeatureExtractor"); + const padded_inputs = await this._get_input_mel( + audio, + max_length ?? this.config.nb_max_samples, + this.config.truncation, + this.config.padding + ); + return { + input_features: padded_inputs.unsqueeze_(0) + }; + } +}; - /** - * Normalize the input text by applying Unicode normalization. - * @param {string} text The input text to be normalized. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.normalize(this.form) - return text; +// src/models/parakeet/feature_extraction_parakeet.js +var EPSILON = 1e-5; +var ParakeetFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + this.config.mel_filters ??= mel_filter_bank( + Math.floor(1 + this.config.n_fft / 2), + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + 0, + // min_frequency + this.config.sampling_rate / 2, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + const window2 = window_function(this.config.win_length, "hann", { + periodic: false + }); + this.window = new Float64Array(this.config.n_fft); + const offset = Math.floor((this.config.n_fft - this.config.win_length) / 2); + this.window.set(window2, offset); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform) { + const preemphasis = this.config.preemphasis; + waveform = new Float64Array(waveform); + for (let j2 = waveform.length - 1; j2 >= 1; --j2) { + waveform[j2] -= preemphasis * waveform[j2 - 1]; + } + const features = await spectrogram( + waveform, + this.window, + // window + this.window.length, + // frame_length + this.config.hop_length, + // hop_length + { + fft_length: this.config.n_fft, + power: 2, + mel_filters: this.config.mel_filters, + log_mel: "log", + mel_floor: -Infinity, + pad_mode: "constant", + center: true, + // Custom + transpose: true, + mel_offset: 2 ** -24 + } + ); + return features; + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor; attention_mask: Tensor; }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + validate_audio_inputs(audio, "ParakeetFeatureExtractor"); + const features = await this._extract_fbank_features(audio); + const features_length = Math.floor( + (audio.length + Math.floor(this.config.n_fft / 2) * 2 - this.config.n_fft) / this.config.hop_length + ); + const features_data = ( + /** @type {Float32Array} */ + features.data + ); + features_data.fill(0, features_length * features.dims[1]); + const [num_frames, num_features] = features.dims; + const sum = new Float64Array(num_features); + const sum_sq = new Float64Array(num_features); + for (let i = 0; i < features_length; ++i) { + const offset = i * num_features; + for (let j2 = 0; j2 < num_features; ++j2) { + const val = features_data[offset + j2]; + sum[j2] += val; + sum_sq[j2] += val * val; + } } -} - -/** - * A normalizer that applies Unicode normalization form C (NFC) to the input text. - * Canonical Decomposition, followed by Canonical Composition. - * @extends UnicodeNormalizer - */ -class NFC extends UnicodeNormalizer { - form = 'NFC'; -} - -/** - * A normalizer that applies Unicode normalization form D (NFD) to the input text. - * Canonical Decomposition. - * @extends UnicodeNormalizer - */ -class NFD extends UnicodeNormalizer { - form = 'NFD'; -} - -/** - * A normalizer that applies Unicode normalization form KC (NFKC) to the input text. - * Compatibility Decomposition, followed by Canonical Composition. - * @extends UnicodeNormalizer - */ -class NFKC extends UnicodeNormalizer { - form = 'NFKC'; -} - -/** - * A normalizer that applies Unicode normalization form KD (NFKD) to the input text. - * Compatibility Decomposition. - * @extends UnicodeNormalizer - */ -class NFKD extends UnicodeNormalizer { - form = 'NFKD'; -} - -/** - * A normalizer that strips leading and/or trailing whitespace from the input text. - */ -class StripNormalizer extends Normalizer { - /** - * Strip leading and/or trailing whitespace from the input text. - * @param {string} text The input text. - * @returns {string} The normalized text. - */ - normalize(text) { - if (this.config.strip_left && this.config.strip_right) { - // Fast path to avoid an extra trim call - text = text.trim(); - } else { - if (this.config.strip_left) { - text = text.trimStart(); - } - if (this.config.strip_right) { - text = text.trimEnd(); - } - } - return text; + const divisor = features_length > 1 ? features_length - 1 : 1; + for (let j2 = 0; j2 < num_features; ++j2) { + const mean2 = sum[j2] / features_length; + const variance = (sum_sq[j2] - features_length * mean2 * mean2) / divisor; + const std = Math.sqrt(variance) + EPSILON; + const inv_std = 1 / std; + for (let i = 0; i < features_length; ++i) { + const index = i * num_features + j2; + features_data[index] = (features_data[index] - mean2) * inv_std; + } } -} + const mask_data = new BigInt64Array(num_frames); + mask_data.fill(1n, 0, features_length); + return { + input_features: features.unsqueeze_(0), + attention_mask: new Tensor3("int64", mask_data, [1, num_frames]) + }; + } +}; -/** - * StripAccents normalizer removes all accents from the text. - * @extends Normalizer - */ -class StripAccents extends Normalizer { - /** - * Remove all accents from the text. - * @param {string} text The input text. - * @returns {string} The normalized text without accents. - */ - normalize(text) { - text = remove_accents(text); - return text; +// src/models/cohere_asr/feature_extraction_cohere_asr.js +var CohereAsrFeatureExtractor = class extends ParakeetFeatureExtractor { + /** + * Apply deterministic dithering seeded by the waveform length. + * @param {Float64Array} waveform + * @returns {Float64Array} The dithered waveform (mutated in-place). + */ + _apply_dither(waveform) { + const dither = this.config.dither ?? 0; + if (dither <= 0) return waveform; + const rng2 = new Random(waveform.length); + for (let i = 0; i < waveform.length; ++i) { + waveform[i] += dither * rng2.gauss(); + } + return waveform; + } + /** + * Split audio into chunks at energy-based boundaries for long audio. + * @param {Float32Array|Float64Array} audio The raw audio waveform. + * @returns {(Float32Array|Float64Array)[]} Array of audio chunks. + */ + split_audio(audio) { + const max_audio_clip_s = this.config.max_audio_clip_s ?? 35; + const overlap_chunk_second = this.config.overlap_chunk_second ?? 5; + const min_energy_window_samples = this.config.min_energy_window_samples ?? 1600; + const sampling_rate = this.config.sampling_rate; + const chunk_size = Math.max(1, Math.round(max_audio_clip_s * sampling_rate)); + const boundary_context_size = Math.max(1, Math.round(overlap_chunk_second * sampling_rate)); + if (audio.length <= chunk_size) { + return [audio]; } -} - -/** - * A Normalizer that lowercases the input string. - * @extends Normalizer - */ -class Lowercase extends Normalizer { - /** - * Lowercases the input string. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - text = text.toLowerCase(); - return text; + const chunks = []; + let idx = 0; + const total_samples = audio.length; + while (idx < total_samples) { + if (idx + chunk_size >= total_samples) { + chunks.push(audio.slice(idx, total_samples)); + break; + } + const search_start = Math.max(idx, idx + chunk_size - boundary_context_size); + const search_end = Math.min(idx + chunk_size, total_samples); + let split_point; + if (search_end <= search_start) { + split_point = idx + chunk_size; + } else { + split_point = this._find_split_point_energy(audio, search_start, search_end, min_energy_window_samples); + } + split_point = Math.max(idx + 1, Math.min(split_point, total_samples)); + chunks.push(audio.slice(idx, split_point)); + idx = split_point; } -} - -/** - * A Normalizer that prepends a string to the input string. - * @extends Normalizer - */ -class Prepend extends Normalizer { - /** - * Prepends the input string. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - text = this.config.prepend + text; - return text; + return chunks; + } + /** + * Find the quietest point (minimum energy) within a segment of audio. + * @param {Float32Array|Float64Array} waveform + * @param {number} start_idx + * @param {number} end_idx + * @param {number} window_size + * @returns {number} Index of the quietest point. + */ + _find_split_point_energy(waveform, start_idx, end_idx, window_size) { + const segment_len = end_idx - start_idx; + if (segment_len <= window_size) { + return Math.floor((start_idx + end_idx) / 2); + } + let min_energy = Infinity; + let quietest_idx = start_idx; + const upper = segment_len - window_size; + for (let i = 0; i <= upper; i += window_size) { + let energy = 0; + for (let j2 = 0; j2 < window_size; ++j2) { + const val = waveform[start_idx + i + j2]; + energy += val * val; + } + energy = Math.sqrt(energy / window_size); + if (energy < min_energy) { + min_energy = energy; + quietest_idx = start_idx + i; + } } -} + return quietest_idx; + } + /** + * Extracts features from a given audio waveform. + * @param {Float32Array|Float64Array} audio The audio data. + * @returns {Promise<{ input_features: import('../../utils/tensor.js').Tensor; attention_mask: import('../../utils/tensor.js').Tensor; }>} + */ + async _call(audio) { + validate_audio_inputs(audio, "CohereAsrFeatureExtractor"); + const waveform = new Float64Array(audio); + this._apply_dither(waveform); + return super._call(waveform); + } +}; -/** - * A Normalizer that applies a sequence of Normalizers. - * @extends Normalizer - */ -class NormalizerSequence extends Normalizer { - /** - * Create a new instance of NormalizerSequence. - * @param {Object} config The configuration object. - * @param {Object[]} config.normalizers An array of Normalizer configuration objects. +// src/models/dac/feature_extraction_dac.js +var DacFeatureExtractor = class extends EncodecFeatureExtractor { +}; + +// src/models/gemma3n/feature_extraction_gemma3n.js +var Gemma3nAudioFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + const { fft_length, feature_size, min_frequency, max_frequency, sampling_rate, frame_length } = this.config; + const mel_filters = mel_filter_bank( + Math.floor(1 + fft_length / 2), + // num_frequency_bins + feature_size, + // num_mel_filters + min_frequency, + // min_frequency + max_frequency, + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "htk", + // mel_scale + false + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = window_function(frame_length, "hann"); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. */ - constructor(config) { - super(config); - this.normalizers = config.normalizers.map(x => Normalizer.fromConfig(x)); - } - /** - * Apply a sequence of Normalizers to the input text. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - return this.normalizers.reduce((t, normalizer) => { - return normalizer.normalize(t); - }, text); - } -} - -/** - * A class representing a normalizer used in BERT tokenization. - * @extends Normalizer - */ -class BertNormalizer extends Normalizer { - /** - * Adds whitespace around any CJK (Chinese, Japanese, or Korean) character in the input text. - * - * @param {string} text The input text to tokenize. - * @returns {string} The tokenized text with whitespace added around CJK characters. - */ - _tokenize_chinese_chars(text) { - /* Adds whitespace around any CJK character. */ - const output = []; - for (let i = 0; i < text.length; ++i) { - const char = text[i]; - const cp = char.charCodeAt(0); - if (is_chinese_char(cp)) { - output.push(" "); - output.push(char); - output.push(" "); - } else { - output.push(char); - } - } - return output.join(""); + async _extract_fbank_features(waveform, max_length) { + return spectrogram( + waveform, + this.window, + // window + this.config.frame_length, + // frame_length + this.config.hop_length, + // hop_length + { + fft_length: this.config.fft_length, + center: false, + onesided: true, + preemphasis: this.config.preemphasis, + preemphasis_htk_flavor: this.config.preemphasis_htk_flavor, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: this.config.mel_floor, + remove_dc_offset: false, + // Custom + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @param {Object} options Optional parameters for feature extraction. + * @param {number} [options.max_length=480_000] If provided, defines the maximum length of the audio to allow. + * Audio longer than this will be truncated if `truncation=True`. + * @param {boolean} [options.truncation=true] Whether or not to truncate audio above `max_length`. + * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. + * @param {number} [options.pad_to_multiple_of=128] The number to pad the sequence to a multiple of. + * @returns {Promise<{ input_features: Tensor, input_features_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. + */ + async _call(audio, { max_length = 48e4, truncation = true, padding = true, pad_to_multiple_of = 128 } = {}) { + validate_audio_inputs(audio, "Gemma3nAudioFeatureExtractor"); + if (truncation && audio.length > max_length) { + audio = audio.slice(0, max_length); + } + if (padding && audio.length % pad_to_multiple_of !== 0) { + const padding_length = pad_to_multiple_of - audio.length % pad_to_multiple_of; + const padded_audio = new Float64Array(audio.length + padding_length); + padded_audio.set(audio); + if (this.config.padding_value !== 0) { + padded_audio.fill(this.config.padding_value, audio.length); + } + audio = padded_audio; } + const features = await this._extract_fbank_features(audio, this.config.max_length); + const padded_attention_mask = full([1, features.dims[0]], true); + return { + input_features: features.unsqueeze_(0), + input_features_mask: padded_attention_mask + }; + } +}; - /** - * Strips accents from the given text. - * @param {string} text The text to strip accents from. - * @returns {string} The text with accents removed. - */ - stripAccents(text) { - // "Mark, Nonspacing" (Mn) - return text.normalize('NFD').replace(/\p{Mn}/gu, ''); +// src/models/gemma4/feature_extraction_gemma4.js +var Gemma4AudioFeatureExtractor = class extends Gemma3nAudioFeatureExtractor { + /** + * @override + * Gemma4 uses semicausal padding, unfold(frame_length+1) framing, and + * additive mel_floor — all controlled via flags on the shared spectrogram(). + */ + async _extract_fbank_features(waveform, max_length) { + const { frame_length, hop_length, fft_length } = this.config; + const pad_left = Math.floor(frame_length / 2); + const num_frames = Math.floor((waveform.length + pad_left - (frame_length + 1)) / hop_length) + 1; + return spectrogram(waveform, this.window, frame_length, hop_length, { + fft_length, + center: true, + pad_mode: "semicausal", + onesided: true, + preemphasis: this.config.preemphasis, + preemphasis_htk_flavor: this.config.preemphasis_htk_flavor, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: this.config.mel_floor, + mel_floor_mode: "add", + remove_dc_offset: false, + transpose: true, + max_num_frames: num_frames + }); + } + /** + * @override + * Wraps the base class result with a frame-aware attention mask + * and zeros out features for invalid (padded) frames. + */ + async _call(audio, options = {}) { + validate_audio_inputs(audio, "Gemma4AudioFeatureExtractor"); + const original_length = audio.length; + const result = await super._call(audio, options); + const { input_features } = result; + const [, num_frames, num_features] = input_features.dims; + const { frame_length, hop_length } = this.config; + const pad_left = Math.floor(frame_length / 2); + const frame_size_for_unfold = frame_length + 1; + const sample_mask = new Uint8Array(original_length + pad_left + (options.pad_to_multiple_of ?? 128)); + sample_mask.fill(1, pad_left, pad_left + original_length); + const frame_mask = new Uint8Array(num_frames); + for (let i = 0; i < num_frames; ++i) { + frame_mask[i] = sample_mask[i * hop_length + frame_size_for_unfold - 1] ? 1 : 0; + } + const feat_data = ( + /** @type {Float32Array} */ + input_features.data + ); + for (let i = 0; i < num_frames; ++i) { + if (!frame_mask[i]) { + feat_data.fill(0, i * num_features, (i + 1) * num_features); + } } + result.input_features_mask = new Tensor3("bool", frame_mask, [1, num_frames]); + return result; + } +}; +// src/models/granite_speech/feature_extraction_granite_speech.js +var GraniteSpeechFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + const { n_fft, win_length, n_mels, sample_rate } = config.melspec_kwargs; + this.mel_filters = mel_filter_bank( + Math.floor(1 + n_fft / 2), + // num_frequency_bins = 257 + n_mels, + // 80 + 0, + // min_frequency + sample_rate / 2, + // max_frequency = 8000 + sample_rate, + // 16000 + null, + // norm (torchaudio default: no norm) + "htk" + // mel_scale (torchaudio default) + ); + const raw_window = window_function(win_length, "hann"); + this.window = new Float64Array(n_fft); + const pad = Math.floor((n_fft - win_length) / 2); + this.window.set(raw_window, pad); + } + /** + * Extract mel spectrogram features from audio, matching the Python GraniteSpeechFeatureExtractor. + * @param {Float32Array|Float64Array} audio The audio waveform. + * @returns {Promise<{input_features: Tensor}>} + */ + async _call(audio) { + validate_audio_inputs(audio, "GraniteSpeechFeatureExtractor"); + const { n_fft, hop_length, n_mels } = this.config.melspec_kwargs; + const num_frames = Math.floor(audio.length / hop_length) + 1; + const max_num_frames = num_frames - num_frames % 2; + const mel = await spectrogram(audio, this.window, n_fft, hop_length, { + power: 2, + mel_filters: this.mel_filters, + log_mel: "log10_max_norm", + transpose: true, + // [time, n_mels] + max_num_frames, + do_pad: false + }); + const input_features = mel.view(-1, 2 * n_mels).unsqueeze_(0); + return { input_features }; + } +}; - /** - * Checks whether `char` is a control character. - * @param {string} char The character to check. - * @returns {boolean} Whether `char` is a control character. - * @private - */ - _is_control(char) { - switch (char) { - case '\t': - case '\n': - case '\r': - // These are technically control characters but we count them as whitespace characters. - return false; +// src/models/moonshine/feature_extraction_moonshine.js +var MoonshineFeatureExtractor = class extends FeatureExtractor { + /** + * Asynchronously extracts input values from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input values. + */ + async _call(audio) { + validate_audio_inputs(audio, "MoonshineFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const shape = [ + 1, + audio.length + /* num_samples */ + ]; + return { + input_values: new Tensor3("float32", audio, shape) + }; + } +}; - default: - // Check if unicode category starts with C: - // Cc - Control - // Cf - Format - // Co - Private Use - // Cs - Surrogate - return /^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(char); +// src/models/pyannote/feature_extraction_pyannote.js +var PyAnnoteFeatureExtractor = class extends FeatureExtractor { + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; }>} The extracted input features. + */ + async _call(audio) { + validate_audio_inputs(audio, "PyAnnoteFeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); + } + const shape = [ + 1, + 1, + audio.length + /* num_samples */ + ]; + return { + input_values: new Tensor3("float32", audio, shape) + }; + } + /** + * NOTE: Can return fractional values. `Math.ceil` will ensure correct value. + * @param {number} samples The number of frames in the audio. + * @returns {number} The number of frames in the audio. + */ + samples_to_frames(samples) { + return (samples - this.config.offset) / this.config.step; + } + /** + * Post-processes the speaker diarization logits output by the model. + * @param {import('../../utils/tensor.js').Tensor} logits The speaker diarization logits output by the model. + * @param {number} num_samples Number of samples in the input audio. + * @returns {Array>} The post-processed speaker diarization results. + */ + post_process_speaker_diarization(logits, num_samples) { + const ratio = num_samples / this.samples_to_frames(num_samples) / this.config.sampling_rate; + const results = []; + for (const scores of logits.tolist()) { + const accumulated_segments = []; + let current_speaker = -1; + for (let i = 0; i < scores.length; ++i) { + const probabilities = softmax(scores[i]); + const [score, id] = max(probabilities); + const [start, end] = [i, i + 1]; + if (id !== current_speaker) { + current_speaker = id; + accumulated_segments.push({ id, start, end, score }); + } else { + accumulated_segments.at(-1).end = end; + accumulated_segments.at(-1).score += score; } + } + results.push( + accumulated_segments.map( + // Convert frame-space to time-space + // and compute the confidence + ({ id, start, end, score }) => ({ + id, + start: start * ratio, + end: end * ratio, + confidence: score / (end - start) + }) + ) + ); } + return results; + } +}; - /** - * Performs invalid character removal and whitespace cleanup on text. - * @param {string} text The text to clean. - * @returns {string} The cleaned text. - * @private - */ - _clean_text(text) { - const output = []; - for (const char of text) { - const cp = char.charCodeAt(0); - if (cp === 0 || cp === 0xFFFD || this._is_control(char)) { - continue; - } - if (/^\s$/.test(char)) { // is whitespace - output.push(" "); - } else { - output.push(char); - } +// src/models/seamless_m4t/feature_extraction_seamless_m4t.js +var SeamlessM4TFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + const sampling_rate = this.config.sampling_rate; + const mel_filters = mel_filter_bank( + 257, + // num_frequency_bins + this.config.num_mel_bins, + // num_mel_filters + 20, + // min_frequency + Math.floor(sampling_rate / 2), + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "kaldi", + // mel_scale + true + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = window_function(400, "povey", { + periodic: false + }); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {number} max_length The maximum number of frames to return. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform, max_length) { + waveform = waveform.map((x) => x * 32768); + return spectrogram( + waveform, + this.window, + // window + 400, + // frame_length + 160, + // hop_length + { + fft_length: 512, + power: 2, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: 1192092955078125e-22, + remove_dc_offset: true, + // Custom + max_num_frames: max_length, + transpose: true + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @param {Object} options Optional parameters for feature extraction. + * @param {boolean} [options.padding=true] Whether to pad the sequence to a multiple of `pad_to_multiple_of`. + * @param {number} [options.pad_to_multiple_of=2] The number to pad the sequence to a multiple of. + * @param {boolean} [options.do_normalize_per_mel_bins=true] Whether or not to zero-mean unit-variance normalize the input per mel-channel. + * @param {boolean} [options.return_attention_mask=true] Whether to return the attention mask. + * @returns {Promise<{ input_features: Tensor, attention_mask?: Tensor }>} A Promise resolving to an object containing the extracted input features and attention masks as Tensors. + */ + async _call(audio, { padding = true, pad_to_multiple_of = 2, do_normalize_per_mel_bins = true, return_attention_mask = true } = {}) { + validate_audio_inputs(audio, "SeamlessM4TFeatureExtractor"); + let features = await this._extract_fbank_features(audio, this.config.max_length); + if (do_normalize_per_mel_bins) { + const [num_features, feature_size] = features.dims; + const data = features.data; + for (let i = 0; i < feature_size; ++i) { + let sum = 0; + for (let j2 = 0; j2 < num_features; ++j2) { + sum += data[j2 * feature_size + i]; + } + const mean2 = sum / num_features; + let variance = 0; + for (let j2 = 0; j2 < num_features; ++j2) { + variance += (data[j2 * feature_size + i] - mean2) ** 2; + } + variance /= num_features - 1; + const std = Math.sqrt(variance + 1e-7); + for (let j2 = 0; j2 < num_features; ++j2) { + const index = j2 * feature_size + i; + data[index] = (data[index] - mean2) / std; } - return output.join(""); + } } - /** - * Normalizes the given text based on the configuration. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - if (this.config.clean_text) { - text = this._clean_text(text); - } - - if (this.config.handle_chinese_chars) { - text = this._tokenize_chinese_chars(text); - } - - if (this.config.lowercase) { - text = text.toLowerCase(); - - if (this.config.strip_accents !== false) { - text = this.stripAccents(text); - } - } else if (this.config.strip_accents) { - text = this.stripAccents(text); + let padded_attention_mask; + if (padding) { + const [num_frames2, num_channels2] = features.dims; + const data = ( + /** @type {Float32Array} */ + features.data + ); + const pad_size = num_frames2 % pad_to_multiple_of; + if (pad_size > 0) { + const padded_data = new Float32Array(num_channels2 * (num_frames2 + pad_size)); + padded_data.set(data); + padded_data.fill(this.config.padding_value, data.length); + const numPaddedFrames = num_frames2 + pad_size; + features = new Tensor3(features.type, padded_data, [numPaddedFrames, num_channels2]); + if (return_attention_mask) { + padded_attention_mask = new Tensor3("int64", new BigInt64Array(numPaddedFrames), [ + 1, + numPaddedFrames + ]); + padded_attention_mask.data.fill(1n, 0, num_frames2); } - - return text; + } } -} - -/** - * A callable class representing a pre-tokenizer used in tokenization. Subclasses - * should implement the `pre_tokenize_text` method to define the specific pre-tokenization logic. - * @extends Callable - */ -class PreTokenizer extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - /** - * Factory method that returns an instance of a subclass of `PreTokenizer` based on the provided configuration. - * - * @static - * @param {Object} config A configuration object for the pre-tokenizer. - * @returns {PreTokenizer} An instance of a subclass of `PreTokenizer`. - * @throws {Error} If the provided configuration object does not correspond to any known pre-tokenizer. - */ - static fromConfig(config) { - if (config === null) return null; - - switch (config.type) { - case 'BertPreTokenizer': - return new BertPreTokenizer(config); - case 'Sequence': - return new PreTokenizerSequence(config); - case 'Whitespace': - return new WhitespacePreTokenizer(config); - case 'WhitespaceSplit': - return new WhitespaceSplit(config); - case 'Metaspace': - return new MetaspacePreTokenizer(config); - - case 'ByteLevel': - return new ByteLevelPreTokenizer(config); - case 'Split': - return new SplitPreTokenizer(config); - case 'Punctuation': - return new PunctuationPreTokenizer(config); - case 'Digits': - return new DigitsPreTokenizer(config); - case 'Replace': - return new ReplacePreTokenizer(config); - default: - throw new Error(`Unknown PreTokenizer type: ${config.type}`); + const [num_frames, num_channels] = features.dims; + const stride = this.config.stride; + const remainder = num_frames % stride; + if (remainder !== 0) { + throw new Error(`The number of frames (${num_frames}) must be a multiple of the stride (${stride}).`); + } + const input_features = features.view(1, Math.floor(num_frames / stride), num_channels * stride); + const result = { input_features }; + if (return_attention_mask) { + const reshapedNumFrames = input_features.dims[1]; + const attention_mask_data = new BigInt64Array(reshapedNumFrames); + if (padded_attention_mask) { + const padded_attention_mask_data = padded_attention_mask.data; + for (let i = 1, j2 = 0; i < num_frames; i += stride, ++j2) { + attention_mask_data[j2] = padded_attention_mask_data[i]; } + } else { + attention_mask_data.fill(1n); + } + result.attention_mask = new Tensor3("int64", attention_mask_data, [1, reshapedNumFrames]); } + return result; + } +}; - /** - * Method that should be implemented by subclasses to define the specific pre-tokenization logic. - * - * @abstract - * @param {string} text The text to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} The pre-tokenized text. - * @throws {Error} If the method is not implemented in the subclass. - */ - pre_tokenize_text(text, options) { - throw Error("pre_tokenize_text should be implemented in subclass.") - } - - /** - * Tokenizes the given text into pre-tokens. - * @param {string|string[]} text The text or array of texts to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of pre-tokens. - */ - pre_tokenize(text, options) { - return (Array.isArray(text) - ? text.map(x => this.pre_tokenize_text(x, options)) - : this.pre_tokenize_text(text, options) - ).flat(); - } +// src/models/snac/feature_extraction_snac.js +var SnacFeatureExtractor = class extends DacFeatureExtractor { +}; - /** - * Alias for {@link PreTokenizer#pre_tokenize}. - * @param {string|string[]} text The text or array of texts to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of pre-tokens. - */ - _call(text, options) { - return this.pre_tokenize(text, options); - } -} +// src/models/speecht5/feature_extraction_speecht5.js +var SpeechT5FeatureExtractor = class extends FeatureExtractor { +}; -/** - * @extends PreTokenizer - */ -class BertPreTokenizer extends PreTokenizer { - /** - * A PreTokenizer that splits text into wordpieces using a basic tokenization scheme - * similar to that used in the original implementation of BERT. - * - * @param {Object} config The configuration object. - */ - constructor(config) { - super(); - // Construct a pattern which matches the rust implementation: - // https://github.com/huggingface/tokenizers/blob/b4fcc9ce6e4ad5806e82826f816acfdfdc4fcc67/tokenizers/src/pre_tokenizers/bert.rs#L11 - // Equivalent to removing whitespace and splitting on punctuation (both \p{P} and other ascii characters) - this.pattern = new RegExp(`[^\\s${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]`, 'gu'); - } - /** - * Tokenizes a single text using the BERT pre-tokenization scheme. - * - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - return text.trim().match(this.pattern) || []; +// src/models/wav2vec2/feature_extraction_wav2vec2.js +var Wav2Vec2FeatureExtractor = class extends FeatureExtractor { + /** + * @param {Float32Array} input_values + * @returns {Float32Array} + */ + _zero_mean_unit_var_norm(input_values) { + const sum = input_values.reduce((a, b) => a + b, 0); + const mean2 = sum / input_values.length; + const variance = input_values.reduce((a, b) => a + (b - mean2) ** 2, 0) / input_values.length; + return input_values.map((x) => (x - mean2) / Math.sqrt(variance + 1e-7)); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_values: Tensor; attention_mask: Tensor }>} A Promise resolving to an object containing the extracted input features and attention mask as Tensors. + */ + async _call(audio) { + validate_audio_inputs(audio, "Wav2Vec2FeatureExtractor"); + if (audio instanceof Float64Array) { + audio = new Float32Array(audio); } -} - -/** - * A pre-tokenizer that splits text into Byte-Pair-Encoding (BPE) subwords. - * @extends PreTokenizer - */ -class ByteLevelPreTokenizer extends PreTokenizer { - /** - * Creates a new instance of the `ByteLevelPreTokenizer` class. - * @param {Object} config The configuration object. - */ - constructor(config) { - super(); - this.config = config; - - /** - * @type {boolean} Whether to add a leading space to the first word. - * This allows to treat the leading word just as any other word. - */ - this.add_prefix_space = this.config.add_prefix_space; - - /** - * @type {boolean} Whether the post processing step should trim offsets - * to avoid including whitespaces. - * @todo Use this in the pretokenization step. - */ - this.trim_offsets = this.config.trim_offsets; - - /** - * @type {boolean} Whether to use the standard GPT2 regex for whitespace splitting. - * Set it to False if you want to use your own splitting. Defaults to true. - */ - this.use_regex = this.config.use_regex ?? true; - this.pattern = /'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu; - - this.byte_encoder = BYTES_TO_UNICODE; - this.text_encoder = new TextEncoder(); + let input_values = audio; + if (this.config.do_normalize) { + input_values = this._zero_mean_unit_var_norm(input_values); } + const shape = [1, input_values.length]; + return { + input_values: new Tensor3("float32", input_values, shape), + attention_mask: new Tensor3("int64", new BigInt64Array(input_values.length).fill(1n), shape) + }; + } +}; - /** - * Tokenizes a single piece of text using byte-level tokenization. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - // Add a leading space if the option is enabled - if (this.add_prefix_space && !text.startsWith(' ')) { - text = ' ' + text; +// src/models/wespeaker/feature_extraction_wespeaker.js +var WeSpeakerFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + const sampling_rate = this.config.sampling_rate; + const mel_filters = mel_filter_bank( + 257, + // num_frequency_bins + this.config.num_mel_bins, + // num_mel_filters + 20, + // min_frequency + Math.floor(sampling_rate / 2), + // max_frequency + sampling_rate, + // sampling_rate + null, + // norm + "kaldi", + // mel_scale + true + // triangularize_in_mel_space + ); + this.mel_filters = mel_filters; + this.window = window_function(400, "hamming", { + periodic: false + }); + this.min_num_frames = this.config.min_num_frames; + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform) { + waveform = waveform.map((x) => x * 32768); + return spectrogram( + waveform, + this.window, + // window + 400, + // frame_length + 160, + // hop_length + { + fft_length: 512, + power: 2, + center: false, + preemphasis: 0.97, + mel_filters: this.mel_filters, + log_mel: "log", + mel_floor: 1192092955078125e-22, + remove_dc_offset: true, + // Custom + transpose: true, + min_num_frames: this.min_num_frames + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio) { + validate_audio_inputs(audio, "WeSpeakerFeatureExtractor"); + const features = (await this._extract_fbank_features(audio)).unsqueeze_(0); + if (this.config.fbank_centering_span === null) { + const meanData = ( + /** @type {Float32Array} */ + features.mean(1).data + ); + const featuresData = ( + /** @type {Float32Array} */ + features.data + ); + const [batch_size, num_frames, feature_size] = features.dims; + for (let i = 0; i < batch_size; ++i) { + const offset1 = i * num_frames * feature_size; + const offset2 = i * feature_size; + for (let j2 = 0; j2 < num_frames; ++j2) { + const offset3 = offset1 + j2 * feature_size; + for (let k = 0; k < feature_size; ++k) { + featuresData[offset3 + k] -= meanData[offset2 + k]; + } } - - // Split on whitespace and punctuation - const tokens = this.use_regex ? (text.match(this.pattern) || []) : [text]; - - // Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) - return tokens.map( - token => Array.from(this.text_encoder.encode(token), byte => this.byte_encoder[byte]).join('') - ); - } -} - -/** - * @typedef {'removed'|'isolated'|'mergedWithPrevious'|'mergedWithNext'|'contiguous'} SplitDelimiterBehavior - */ - -/** - * Splits text using a given pattern. - * @extends PreTokenizer - */ -class SplitPreTokenizer extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. - * @param {string|undefined} config.pattern.String The string to use for splitting. Only defined if the pattern is a string. - * @param {string|undefined} config.pattern.Regex The regex to use for splitting. Only defined if the pattern is a regex. - * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. - * @param {boolean} config.invert Whether to split (invert=false) or match (invert=true) the pattern. - */ - constructor(config) { - super(); - this.config = config; - // TODO support all behaviours (config.behavior) - - this.pattern = createPattern(this.config.pattern, this.config.invert); + } } + return { + input_features: features + }; + } +}; - /** - * Tokenizes text by splitting it using the given pattern. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - if (this.pattern === null) { - return []; - } +// src/models/voxtral_realtime/feature_extraction_voxtral_realtime.js +var VoxtralRealtimeFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + this.config.mel_filters ??= mel_filter_bank( + Math.floor(1 + this.config.n_fft / 2), + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + 0, + // min_frequency + 8e3, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + this.window = window_function(this.config.n_fft, "hann"); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @param {Object} [options] + * @param {boolean} [options.center=true] Whether to center-pad the waveform for STFT. + * @returns {Promise} The log-Mel spectrogram tensor of shape [num_mel_bins, num_frames]. + */ + async _extract_fbank_features(waveform, { center = true } = {}) { + const { n_fft, hop_length, mel_filters, global_log_mel_max } = this.config; + const max_num_frames = center ? Math.floor(waveform.length / hop_length) : Math.floor((waveform.length - n_fft) / hop_length); + return await spectrogram( + waveform, + this.window, + n_fft, + // frame_length + hop_length, + { + power: 2, + mel_filters, + log_mel: "log10_max_norm", + max_log_mel: global_log_mel_max, + center, + max_num_frames, + do_pad: false + } + ); + } + /** + * Extract mel spectrogram features from audio. + * @param {Float32Array|Float64Array} audio The audio data. + * @param {Object} [options] + * @param {boolean} [options.center=true] Whether to center-pad the waveform. + * @returns {Promise<{ input_features: import('../../utils/tensor.js').Tensor }>} + */ + async _call(audio, { center = true } = {}) { + validate_audio_inputs(audio, "VoxtralRealtimeFeatureExtractor"); + const features = await this._extract_fbank_features(audio, { center }); + return { + input_features: features.unsqueeze_(0) + }; + } +}; - if (this.config.invert) { - return text.match(this.pattern) || []; - } else if (this.config.behavior?.toLowerCase() === 'removed') { - return text.split(this.pattern).filter(x => x); - } else { - return regexSplit(text, this.pattern); - } +// src/models/whisper/feature_extraction_whisper.js +var WhisperFeatureExtractor = class extends FeatureExtractor { + constructor(config) { + super(config); + this.config.mel_filters ??= mel_filter_bank( + Math.floor(1 + this.config.n_fft / 2), + // num_frequency_bins + this.config.feature_size, + // num_mel_filters + 0, + // min_frequency + 8e3, + // max_frequency + this.config.sampling_rate, + // sampling_rate + "slaney", + // norm + "slaney" + // mel_scale + ); + this.window = window_function(this.config.n_fft, "hann"); + } + /** + * Computes the log-Mel spectrogram of the provided audio waveform. + * @param {Float32Array|Float64Array} waveform The audio waveform to process. + * @returns {Promise} An object containing the log-Mel spectrogram data as a Float32Array and its dimensions as an array of numbers. + */ + async _extract_fbank_features(waveform) { + return await spectrogram( + waveform, + this.window, + // window + this.config.n_fft, + // frame_length + this.config.hop_length, + // hop_length + { + power: 2, + mel_filters: this.config.mel_filters, + log_mel: "log10_max_norm", + // Custom + max_num_frames: Math.min( + Math.floor(waveform.length / this.config.hop_length), + this.config.nb_max_frames + // 3000 + ) + } + ); + } + /** + * Asynchronously extracts features from a given audio using the provided configuration. + * @param {Float32Array|Float64Array} audio The audio data as a Float32Array/Float64Array. + * @returns {Promise<{ input_features: Tensor }>} A Promise resolving to an object containing the extracted input features as a Tensor. + */ + async _call(audio, { max_length = null } = {}) { + validate_audio_inputs(audio, "WhisperFeatureExtractor"); + let waveform; + const length = max_length ?? this.config.n_samples; + if (audio.length > length) { + if (audio.length > this.config.n_samples) { + logger.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`." + ); + } + waveform = audio.slice(0, length); + } else { + waveform = new Float32Array(length); + waveform.set(audio); } -} + const features = await this._extract_fbank_features(waveform); + return { + input_features: features.unsqueeze_(0) + }; + } +}; -/** - * Splits text based on punctuation. - * @extends PreTokenizer - */ -class PunctuationPreTokenizer extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {SplitDelimiterBehavior} config.behavior The behavior to use when splitting. - */ - constructor(config) { - super(); - this.config = config; - this.pattern = new RegExp(`[^${PUNCTUATION_REGEX}]+|[${PUNCTUATION_REGEX}]+`, 'gu'); +// src/models/auto/feature_extraction_auto.js +var AutoFeatureExtractor = class { + /** @type {typeof FeatureExtractor.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await getModelJSON( + pretrained_model_name_or_path, + FEATURE_EXTRACTOR_NAME, + true, + options + ); + const key = preprocessorConfig.feature_extractor_type; + const feature_extractor_class = feature_extractors_exports[key]; + if (!feature_extractor_class) { + throw new Error(`Unknown feature_extractor_type: '${key}'. Please report this at ${GITHUB_ISSUE_URL}.`); } + return new feature_extractor_class(preprocessorConfig); + } +}; - /** - * Tokenizes text by splitting it using the given pattern. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - return text.match(this.pattern) || []; - } -} +// src/models/chatterbox/processing_chatterbox.js +var ChatterboxProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + async _call(text, audio = null) { + const text_features = this.tokenizer(text); + const audio_features = audio ? await this.feature_extractor(audio) : {}; + return { ...text_features, ...audio_features }; + } +}; +// src/models/cohere_asr/processing_cohere_asr.js +var NO_SPACE_LANGUAGES = /* @__PURE__ */ new Set(["ja", "zh"]); +var CohereAsrProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + static uses_processor_config = true; + /** + * Build the 10-token decoder prompt for the given language. + * @param {string} [language='en'] Language code. + * @returns {number[]} Token IDs for the decoder prompt. + */ + get_decoder_prompt_ids(language = "en") { + const tokens = [ + "\u2581", + "<|startofcontext|>", + "<|startoftranscript|>", + "<|emo:undefined|>", + `<|${language}|>`, + `<|${language}|>`, + "<|pnc|>", + "<|noitn|>", + "<|notimestamp|>", + "<|nodiarize|>" + ]; + return this.tokenizer.convert_tokens_to_ids(tokens); + } + /** + * Join chunk texts back together, using the appropriate separator for the language. + * @param {string[]} texts Decoded texts, one per chunk. + * @param {string} [language='en'] Language code. + * @returns {string} The joined text. + */ + static join_chunks(texts, language = "en") { + const non_empty = texts.filter((t) => t && t.trim()); + if (non_empty.length === 0) return ""; + const separator = NO_SPACE_LANGUAGES.has(language) ? "" : " "; + const parts = [non_empty[0].trimEnd(), ...non_empty.slice(1).map((t) => t.trim())]; + return parts.join(separator); + } + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} + */ + async _call(audio) { + return await this.feature_extractor(audio); + } +}; -/** - * Splits text based on digits. - * @extends PreTokenizer - */ -class DigitsPreTokenizer extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {boolean} config.individual_digits Whether to split on individual digits. - */ - constructor(config) { - super(); - this.config = config; +// ignore-modules:sharp +var sharp_default = {}; - // Construct a pattern which matches the rust implementation: - const digit_pattern = `[^\\d]+|\\d${this.config.individual_digits ? '' : '+'}`; - this.pattern = new RegExp(digit_pattern, 'gu'); +// src/utils/image.js +var createCanvasFunction; +var ImageDataClass; +var loadImageFunction; +if (apis.IS_WEB_ENV) { + createCanvasFunction = (width, height) => { + if (!self.OffscreenCanvas) { + throw new Error("OffscreenCanvas not supported by this environment."); } - - /** - * Tokenizes text by splitting it using the given pattern. - * @param {string} text The text to tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens. - */ - pre_tokenize_text(text, options) { - return text.match(this.pattern) || []; + return new self.OffscreenCanvas(width, height); + }; + loadImageFunction = self.createImageBitmap; + ImageDataClass = self.ImageData; +} else if (sharp_default) { + loadImageFunction = async (img) => { + const metadata = await img.metadata(); + const rawChannels = metadata.channels; + const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true }); + const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels); + if (rawChannels !== void 0 && rawChannels !== info.channels) { + newImage.convert(rawChannels); + } + return newImage; + }; +} else { + throw new Error("Unable to load image processing library."); +} +var RESAMPLING_MAPPING = { + 0: "nearest", + 1: "lanczos", + 2: "bilinear", + 3: "bicubic", + 4: "box", + 5: "hamming" +}; +var CONTENT_TYPE_MAP2 = /* @__PURE__ */ new Map([ + ["png", "image/png"], + ["jpg", "image/jpeg"], + ["jpeg", "image/jpeg"], + ["gif", "image/gif"] +]); +var RawImage = class _RawImage { + /** + * Create a new `RawImage` object. + * @param {Uint8ClampedArray|Uint8Array} data The pixel data. + * @param {number} width The width of the image. + * @param {number} height The height of the image. + * @param {1|2|3|4} channels The number of channels. + */ + constructor(data, width, height, channels) { + this.data = data; + this.width = width; + this.height = height; + this.channels = channels; + } + /** + * Returns the size of the image (width, height). + * @returns {[number, number]} The size of the image (width, height). + */ + get size() { + return [this.width, this.height]; + } + /** + * Helper method for reading an image from a variety of input types. + * @param {RawImage|string|URL|Blob|HTMLCanvasElement|OffscreenCanvas} input + * @returns {Promise} The image object. + * + * **Example:** Read image from a URL. + * ```javascript + * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); + * // RawImage { + * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], + * // "width": 800, + * // "height": 533, + * // "channels": 3 + * // } + * ``` + */ + static async read(input) { + if (input instanceof _RawImage) { + return input; + } else if (typeof input === "string" || input instanceof URL) { + return await this.fromURL(input); + } else if (input instanceof Blob) { + return await this.fromBlob(input); + } else if (typeof HTMLCanvasElement !== "undefined" && input instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && input instanceof OffscreenCanvas) { + return this.fromCanvas(input); + } else { + throw new Error(`Unsupported input type: ${typeof input}`); } -} - -/** - * @typedef {Object} PostProcessedOutput - * @property {string[]} tokens List of token produced by the post-processor. - * @property {number[]} [token_type_ids] List of token type ids produced by the post-processor. - */ - - -/** - * @typedef {Object} EncodingSingle - * @property {number[]} input_ids List of token ids to be fed to a model. - * @property {number[]} attention_mask List of token type ids to be fed to a model - * @property {number[]} [token_type_ids] List of indices specifying which tokens should be attended to by the model - */ - - -/** - * @extends Callable - */ -class PostProcessor extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - - /** - * @param {Object} config The configuration for the post-processor. - */ - constructor(config) { - super(); - this.config = config; + } + /** + * Read an image from a canvas. + * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from. + * @returns {RawImage} The image object. + */ + static fromCanvas(canvas) { + if (!apis.IS_WEB_ENV) { + throw new Error("fromCanvas() is only supported in browser environments."); } - - /** - * Factory method to create a PostProcessor object from a configuration object. - * - * @param {Object} config Configuration object representing a PostProcessor. - * @returns {PostProcessor} A PostProcessor object created from the given configuration. - * @throws {Error} If an unknown PostProcessor type is encountered. - */ - static fromConfig(config) { - if (config === null) return null; - switch (config.type) { - case 'TemplateProcessing': - return new TemplateProcessing(config); - - case 'ByteLevel': - return new ByteLevelPostProcessor(config); - - case 'RobertaProcessing': - return new RobertaProcessing(config); - case 'BertProcessing': - return new BertProcessing(config); - - case 'Sequence': - return new PostProcessorSequence(config); - default: - throw new Error(`Unknown PostProcessor type: ${config.type}`); - } + const ctx = ( + /** @type {CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D} */ + canvas.getContext("2d") + ); + const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data; + return new _RawImage(data, canvas.width, canvas.height, 4); + } + /** + * Read an image from a URL or file path. + * @param {string|URL} url The URL or file path to read the image from. + * @returns {Promise} The image object. + */ + static async fromURL(url) { + const response = await getFile(url); + if (response.status !== 200) { + throw new Error(`Unable to read image from "${url}" (${response.status} ${response.statusText})`); } - - /** - * Method to be implemented in subclass to apply post-processing on the given tokens. - * - * @param {Array} tokens The input tokens to be post-processed. - * @param {...*} args Additional arguments required by the post-processing logic. - * @returns {PostProcessedOutput} The post-processed tokens. - * @throws {Error} If the method is not implemented in subclass. - */ - post_process(tokens, ...args) { - throw Error("post_process should be implemented in subclass.") + const blob = await response.blob(); + return this.fromBlob(blob); + } + /** + * Helper method to create a new Image from a blob. + * @param {Blob} blob The blob to read the image from. + * @returns {Promise} The image object. + */ + static async fromBlob(blob) { + if (apis.IS_WEB_ENV) { + const img = await loadImageFunction(blob); + const ctx = createCanvasFunction(img.width, img.height).getContext("2d"); + ctx.drawImage(img, 0, 0); + return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); + } else { + const img = sharp_default(await blob.arrayBuffer()); + return await loadImageFunction(img); } - - /** - * Alias for {@link PostProcessor#post_process}. - * @param {Array} tokens The text or array of texts to post-process. - * @param {...*} args Additional arguments required by the post-processing logic. - * @returns {PostProcessedOutput} The post-processed tokens. - */ - _call(tokens, ...args) { - return this.post_process(tokens, ...args); + } + /** + * Helper method to create a new Image from a tensor + * @param {Tensor} tensor The 3D tensor containing the image data. Must be of type `uint8`. + * @param {'CHW'|'HWC'} [channel_format='CHW'] The dimension ordering of the tensor. + * @returns {RawImage} The image created from the tensor. + * @throws {Error} If the tensor does not have 3 dimensions, or the channel format, + * tensor type, or number of channels is unsupported. + */ + static fromTensor(tensor, channel_format = "CHW") { + if (tensor.dims.length !== 3) { + throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`); } -} - -/** - * A post-processor that adds special tokens to the beginning and end of the input. - */ -class BertProcessing extends PostProcessor { - /** - * @param {Object} config The configuration for the post-processor. - * @param {string[]} config.cls The special tokens to add to the beginning of the input. - * @param {string[]} config.sep The special tokens to add to the end of the input. - */ - constructor(config) { - super(config); - // TODO use all of config: add_prefix_space, trim_offsets - - this.cls = config.cls[0]; - this.sep = config.sep[0]; + if (channel_format === "CHW") { + tensor = tensor.permute(1, 2, 0); + } else if (channel_format === "HWC") { + } else { + throw new Error(`Unsupported channel format: ${channel_format}`); } - - /** - * Adds the special tokens to the beginning and end of the input. - * @param {string[]} tokens The input tokens. - * @param {string[]} [tokens_pair=null] An optional second set of input tokens. - * @returns {PostProcessedOutput} The post-processed tokens with the special tokens added to the beginning and end. - */ - post_process(tokens, tokens_pair = null, { - add_special_tokens = true, - } = {}) { - if (add_special_tokens) { - tokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)([this.cls], tokens, [this.sep]); - } - - let token_type_ids = new Array(tokens.length).fill(0); - if (tokens_pair !== null) { - // NOTE: It is intended to add 2 EOS tokens after the first set of tokens - // https://github.com/huggingface/tokenizers/issues/983 - const middle = (add_special_tokens && this instanceof RobertaProcessing) - ? [this.sep] - : []; - const after = add_special_tokens ? [this.sep] : []; - - tokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(tokens, middle, tokens_pair, after); - token_type_ids = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(token_type_ids, new Array(tokens_pair.length + middle.length + after.length).fill(1)); - } - return { tokens, token_type_ids }; + if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) { + throw new Error(`Unsupported tensor type: ${tensor.type}`); } -} -class RobertaProcessing extends BertProcessing { } // NOTE: extends BertProcessing - -/** - * Post processor that replaces special tokens in a template with actual tokens. - * @extends PostProcessor - */ -class TemplateProcessing extends PostProcessor { - /** - * Creates a new instance of `TemplateProcessing`. - * @param {Object} config The configuration options for the post processor. - * @param {Array} config.single The template for a single sequence of tokens. - * @param {Array} config.pair The template for a pair of sequences of tokens. - */ - constructor(config) { - super(config); - - this.single = config.single; - this.pair = config.pair; + switch (tensor.dims[2]) { + case 1: + case 2: + case 3: + case 4: + return new _RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]); + default: + throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`); } - - /** - * Replaces special tokens in the template with actual tokens. - * @param {string[]} tokens The list of tokens for the first sequence. - * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). - * @returns {PostProcessedOutput} An object containing the list of tokens with the special tokens replaced with actual tokens. - */ - post_process(tokens, tokens_pair = null, { - add_special_tokens = true, - } = {}) { - const type = tokens_pair === null ? this.single : this.pair - - let processedTokens = []; - let types = []; - for (const item of type) { - if ('SpecialToken' in item) { - if (add_special_tokens) { - processedTokens.push(item.SpecialToken.id); - types.push(item.SpecialToken.type_id); - } - } else if ('Sequence' in item) { - if (item.Sequence.id === 'A') { - processedTokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(processedTokens, tokens); - types = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(types, new Array(tokens.length).fill(item.Sequence.type_id)); - - } else if (item.Sequence.id === 'B') { - processedTokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(processedTokens, tokens_pair); - types = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(types, new Array(tokens_pair.length).fill(item.Sequence.type_id)); - } - } - } - return { tokens: processedTokens, token_type_ids: types }; + } + /** + * Convert the image to grayscale format. + * @returns {RawImage} `this` to support chaining. + */ + grayscale() { + if (this.channels === 1) { + return this; } -} - -/** - * A PostProcessor that returns the given tokens as is. - * @extends PostProcessor - */ -class ByteLevelPostProcessor extends PostProcessor { - /** - * Post process the given tokens. - * @param {string[]} tokens The list of tokens for the first sequence. - * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). - * @returns {PostProcessedOutput} An object containing the post-processed tokens. - */ - post_process(tokens, tokens_pair = null) { - if (tokens_pair) { - tokens = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(tokens, tokens_pair); + const newData = new Uint8ClampedArray(this.width * this.height * 1); + switch (this.channels) { + case 3: + // rgb to grayscale + case 4: + for (let i = 0, offset = 0; i < this.data.length; i += this.channels) { + const red = this.data[i]; + const green = this.data[i + 1]; + const blue = this.data[i + 2]; + newData[offset++] = Math.round(0.2989 * red + 0.587 * green + 0.114 * blue); } - return { tokens }; + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } -} - - -/** - * A post-processor that applies multiple post-processors in sequence. - */ -class PostProcessorSequence extends PostProcessor { - - /** - * Creates a new instance of PostProcessorSequence. - * @param {Object} config The configuration object. - * @param {Object[]} config.processors The list of post-processors to apply. - */ - constructor(config) { - super(config); - - this.processors = config.processors.map(x => PostProcessor.fromConfig(x)); + return this._update(newData, this.width, this.height, 1); + } + /** + * Convert the image to RGB format. + * @returns {RawImage} `this` to support chaining. + */ + rgb() { + if (this.channels === 3) { + return this; } - - /** - * Post process the given tokens. - * @param {string[]} tokens The list of tokens for the first sequence. - * @param {string[]} [tokens_pair=null] The list of tokens for the second sequence (optional). - * @returns {PostProcessedOutput} An object containing the post-processed tokens. - */ - post_process(tokens, tokens_pair = null, options = {}) { - let token_type_ids; - for (const processor of this.processors) { - if (processor instanceof ByteLevelPostProcessor) { - // Special case where we need to pass the tokens_pair to the post-processor - const output = processor.post_process(tokens); - tokens = output.tokens; - if (tokens_pair) { - const pair_output = processor.post_process(tokens_pair); - tokens_pair = pair_output.tokens; - } - } else { - const output = processor.post_process(tokens, tokens_pair, options); - tokens = output.tokens; - token_type_ids = output.token_type_ids; - } + const newData = new Uint8ClampedArray(this.width * this.height * 3); + switch (this.channels) { + case 1: + for (let i = 0, offset = 0; i < this.data.length; ++i) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + } + break; + case 4: + for (let i = 0, offset = 0; i < this.data.length; i += 4) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i + 1]; + newData[offset++] = this.data[i + 2]; } - return { tokens, token_type_ids }; + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } -} - -/** - * The base class for token decoders. - * @extends Callable - */ -class Decoder extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - - /** - * Creates an instance of `Decoder`. - * - * @param {Object} config The configuration object. - */ - constructor(config) { - super(); - this.config = config; - - /** @type {AddedToken[]} */ - this.added_tokens = []; - this.end_of_word_suffix = null; - this.trim_offsets = config.trim_offsets; + return this._update(newData, this.width, this.height, 3); + } + /** + * Convert the image to RGBA format. + * @returns {RawImage} `this` to support chaining. + */ + rgba() { + if (this.channels === 4) { + return this; } - - /** - * Creates a decoder instance based on the provided configuration. - * - * @param {Object} config The configuration object. - * @returns {Decoder} A decoder instance. - * @throws {Error} If an unknown decoder type is provided. - */ - static fromConfig(config) { - if (config === null) return null; - switch (config.type) { - case 'WordPiece': - return new WordPieceDecoder(config); - case 'Metaspace': - return new MetaspaceDecoder(config); - case 'ByteLevel': - return new ByteLevelDecoder(config); - - case 'Replace': - return new ReplaceDecoder(config); - case 'ByteFallback': - return new ByteFallback(config); - case 'Fuse': - return new FuseDecoder(config); - case 'Strip': - return new StripDecoder(config); - - case 'Sequence': - return new DecoderSequence(config); - - case 'CTC': - return new CTCDecoder(config); - case 'BPEDecoder': - return new BPEDecoder(config); - default: - throw new Error(`Unknown Decoder type: ${config.type}`); + const newData = new Uint8ClampedArray(this.width * this.height * 4); + switch (this.channels) { + case 1: + for (let i = 0, offset = 0; i < this.data.length; ++i) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i]; + newData[offset++] = 255; + } + break; + case 3: + for (let i = 0, offset = 0; i < this.data.length; i += 3) { + newData[offset++] = this.data[i]; + newData[offset++] = this.data[i + 1]; + newData[offset++] = this.data[i + 2]; + newData[offset++] = 255; } + break; + default: + throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); } - - /** - * Calls the `decode` method. - * - * @param {string[]} tokens The list of tokens. - * @returns {string} The decoded string. - */ - _call(tokens) { - return this.decode(tokens); + return this._update(newData, this.width, this.height, 4); + } + /** + * Apply an alpha mask to the image. Operates in place. + * @param {RawImage} mask The mask to apply. It should have a single channel. + * @returns {RawImage} The masked image. + * @throws {Error} If the mask is not the same size as the image. + * @throws {Error} If the image does not have 4 channels. + * @throws {Error} If the mask is not a single channel. + */ + putAlpha(mask) { + if (mask.width !== this.width || mask.height !== this.height) { + throw new Error( + `Expected mask size to be ${this.width}x${this.height}, but got ${mask.width}x${mask.height}` + ); } - - /** - * Decodes a list of tokens. - * @param {string[]} tokens The list of tokens. - * @returns {string} The decoded string. - */ - decode(tokens) { - return this.decode_chain(tokens).join(''); + if (mask.channels !== 1) { + throw new Error(`Expected mask to have 1 channel, but got ${mask.channels}`); + } + const this_data = this.data; + const mask_data = mask.data; + const num_pixels = this.width * this.height; + if (this.channels === 3) { + const newData = new Uint8ClampedArray(num_pixels * 4); + for (let i = 0, in_offset = 0, out_offset = 0; i < num_pixels; ++i) { + newData[out_offset++] = this_data[in_offset++]; + newData[out_offset++] = this_data[in_offset++]; + newData[out_offset++] = this_data[in_offset++]; + newData[out_offset++] = mask_data[i]; + } + return this._update(newData, this.width, this.height, 4); + } else if (this.channels === 4) { + for (let i = 0; i < num_pixels; ++i) { + this_data[4 * i + 3] = mask_data[i]; + } + return this; } - - /** - * Apply the decoder to a list of tokens. - * - * @param {string[]} tokens The list of tokens. - * @returns {string[]} The decoded list of tokens. - * @throws {Error} If the `decode_chain` method is not implemented in the subclass. - */ - decode_chain(tokens) { - throw Error("`decode_chain` should be implemented in subclass.") + throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`); + } + /** + * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. + * @param {number} width The width of the new image. `null` or `-1` will preserve the aspect ratio. + * @param {number} height The height of the new image. `null` or `-1` will preserve the aspect ratio. + * @param {Object} options Additional options for resizing. + * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. + * @returns {Promise} `this` to support chaining. + */ + async resize(width, height, { resample = 2 } = {}) { + if (this.width === width && this.height === height) { + return this; } - -} - -class ReplaceDecoder extends Decoder { - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - const pattern = createPattern(this.config.pattern); - return pattern === null - ? tokens - : tokens.map(token => token.replaceAll(pattern, this.config.content)) + let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample; + const nullish_width = isNullishDimension(width); + const nullish_height = isNullishDimension(height); + if (nullish_width && nullish_height) { + return this; + } else if (nullish_width) { + width = height / this.height * this.width; + } else if (nullish_height) { + height = width / this.width * this.height; + } + if (apis.IS_WEB_ENV) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const ctx = createCanvasFunction(width, height).getContext("2d"); + ctx.drawImage(canvas, 0, 0, width, height); + const resizedImage = new _RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4); + return resizedImage.convert(numChannels); + } else { + let img = this.toSharp(); + switch (resampleMethod) { + case "box": + case "hamming": + if (resampleMethod === "box" || resampleMethod === "hamming") { + logger.warn( + `Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.` + ); + resampleMethod = "bilinear"; + } + case "nearest": + case "bilinear": + case "bicubic": + img = img.affine([width / this.width, 0, 0, height / this.height], { + interpolator: resampleMethod + }); + break; + case "lanczos": + img = img.resize({ + width, + height, + fit: "fill", + kernel: "lanczos3" + // PIL Lanczos uses a kernel size of 3 + }); + break; + default: + throw new Error(`Resampling method ${resampleMethod} is not supported.`); + } + return await loadImageFunction(img); } -} - - -class ByteFallback extends Decoder { - constructor(config) { - super(config); - - this.text_decoder = new TextDecoder(); + } + async pad([left, right, top, bottom]) { + left = Math.max(left, 0); + right = Math.max(right, 0); + top = Math.max(top, 0); + bottom = Math.max(bottom, 0); + if (left === 0 && right === 0 && top === 0 && bottom === 0) { + return this; } - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - - const new_tokens = []; - let previous_byte_tokens = []; - - for (const token of tokens) { - let bytes = null; - if (token.length === 6 && token.startsWith('<0x') && token.endsWith('>')) { - const byte = parseInt(token.slice(3, 5), 16); - if (!isNaN(byte)) { - bytes = byte; - } - } - if (bytes !== null) { - previous_byte_tokens.push(bytes); - } else { - if (previous_byte_tokens.length > 0) { - const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); - new_tokens.push(string); - previous_byte_tokens = []; - } - new_tokens.push(token); - } - } - if (previous_byte_tokens.length > 0) { - const string = this.text_decoder.decode(Uint8Array.from(previous_byte_tokens)); - new_tokens.push(string); - previous_byte_tokens = []; - } - - return new_tokens; + if (apis.IS_WEB_ENV) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const newWidth = this.width + left + right; + const newHeight = this.height + top + bottom; + const ctx = createCanvasFunction(newWidth, newHeight).getContext("2d"); + ctx.drawImage(canvas, 0, 0, this.width, this.height, left, top, this.width, this.height); + const paddedImage = new _RawImage(ctx.getImageData(0, 0, newWidth, newHeight).data, newWidth, newHeight, 4); + return paddedImage.convert(numChannels); + } else { + const img = this.toSharp().extend({ left, right, top, bottom }); + return await loadImageFunction(img); } -} - -/** - * Fuse simply fuses all tokens into one big string. - * It's usually the last decoding step anyway, but this decoder - * exists incase some decoders need to happen after that step - */ -class FuseDecoder extends Decoder { - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return [tokens.join('')]; + } + async crop([x_min, y_min, x_max, y_max]) { + x_min = Math.max(x_min, 0); + y_min = Math.max(y_min, 0); + x_max = Math.min(x_max, this.width - 1); + y_max = Math.min(y_max, this.height - 1); + if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) { + return this; } -} - - -class StripDecoder extends Decoder { - constructor(config) { - super(config); - - this.content = this.config.content; - this.start = this.config.start; - this.stop = this.config.stop; + const crop_width = x_max - x_min + 1; + const crop_height = y_max - y_min + 1; + if (apis.IS_WEB_ENV) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); + ctx.drawImage(canvas, x_min, y_min, crop_width, crop_height, 0, 0, crop_width, crop_height); + const resizedImage = new _RawImage( + ctx.getImageData(0, 0, crop_width, crop_height).data, + crop_width, + crop_height, + 4 + ); + return resizedImage.convert(numChannels); + } else { + const img = this.toSharp().extract({ + left: x_min, + top: y_min, + width: crop_width, + height: crop_height + }); + return await loadImageFunction(img); } - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return tokens.map(token => { - let start_cut = 0; - for (let i = 0; i < this.start; ++i) { - if (token[i] === this.content) { - start_cut = i + 1; - continue; - } else { - break; - } - } - - let stop_cut = token.length; - for (let i = 0; i < this.stop; ++i) { - const index = token.length - i - 1; - if (token[index] === this.content) { - stop_cut = index; - continue; - } else { - break; - } - } - - return token.slice(start_cut, stop_cut) - }); + } + async center_crop(crop_width, crop_height) { + if (this.width === crop_width && this.height === crop_height) { + return this; } -} - -/** - * A decoder that decodes a list of WordPiece tokens into a single string. - * @extends Decoder - */ -class WordPieceDecoder extends Decoder { - - /** - * Creates a new instance of WordPieceDecoder. - * @param {Object} config The configuration object. - * @param {string} config.prefix The prefix used for WordPiece encoding. - * @param {boolean} config.cleanup Whether to cleanup the decoded string. - */ - constructor(config) { - super(config); - this.cleanup = config.cleanup; - } - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return tokens.map((token, i) => { - if (i !== 0) { - if (token.startsWith(this.config.prefix)) { - // NOTE: .replace() is intended; only replace first occurrence - token = token.replace(this.config.prefix, ''); - } else { - token = ' ' + token; - } - } - if (this.cleanup) { - token = clean_up_tokenization(token) - } - - return token; + const width_offset = (this.width - crop_width) / 2; + const height_offset = (this.height - crop_height) / 2; + if (apis.IS_WEB_ENV) { + const numChannels = this.channels; + const canvas = this.toCanvas(); + const ctx = createCanvasFunction(crop_width, crop_height).getContext("2d"); + let sourceX = 0; + let sourceY = 0; + let destX = 0; + let destY = 0; + if (width_offset >= 0) { + sourceX = width_offset; + } else { + destX = -width_offset; + } + if (height_offset >= 0) { + sourceY = height_offset; + } else { + destY = -height_offset; + } + ctx.drawImage(canvas, sourceX, sourceY, crop_width, crop_height, destX, destY, crop_width, crop_height); + const resizedImage = new _RawImage( + ctx.getImageData(0, 0, crop_width, crop_height).data, + crop_width, + crop_height, + 4 + ); + return resizedImage.convert(numChannels); + } else { + let img = this.toSharp(); + if (width_offset >= 0 && height_offset >= 0) { + img = img.extract({ + left: Math.floor(width_offset), + top: Math.floor(height_offset), + width: crop_width, + height: crop_height }); - } -} - -/** - * Byte-level decoder for tokenization output. Inherits from the `Decoder` class. - * @extends Decoder - */ -class ByteLevelDecoder extends Decoder { - - /** - * Create a `ByteLevelDecoder` object. - * @param {Object} config Configuration object. - */ - constructor(config) { - super(config); - - this.byte_decoder = UNICODE_TO_BYTES; - this.text_decoder = new TextDecoder("utf-8", { - fatal: false, - ignoreBOM: true, + } else if (width_offset <= 0 && height_offset <= 0) { + const top = Math.floor(-height_offset); + const left = Math.floor(-width_offset); + img = img.extend({ + top, + left, + // Ensures the resulting image has the desired dimensions + right: crop_width - this.width - left, + bottom: crop_height - this.height - top }); - - this.end_of_word_suffix = null; - } - - /** - * Convert an array of tokens to string by decoding each byte. - * @param {string[]} tokens Array of tokens to be decoded. - * @returns {string} The decoded string. - */ - convert_tokens_to_string(tokens) { - const text = tokens.join(''); - const byteArray = new Uint8Array([...text].map(c => this.byte_decoder[c])); - const decoded_text = this.text_decoder.decode(byteArray); - return decoded_text; - } - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - // TODO move to base class (like HF) - // tokens === filtered_tokens - - // To avoid mixing byte-level and unicode for byte-level BPT - // we need to build string separately for added tokens and byte-level tokens - // cf. https://github.com/huggingface/transformers/issues/1133 - const sub_texts = []; - let current_sub_text = []; - for (const token of tokens) { - // tokens sent here are already filtered, so we don't need to do this - // if (skip_special_tokens && this.all_special_ids.includes(token)) { - // continue; - // } - - if (this.added_tokens.find(x => x.content === token) !== undefined) { - if (current_sub_text.length > 0) { - sub_texts.push(this.convert_tokens_to_string(current_sub_text)); - current_sub_text = []; - } - sub_texts.push(token); - } else { - current_sub_text.push(token); - } - } - if (current_sub_text.length > 0) { - sub_texts.push(this.convert_tokens_to_string(current_sub_text)); - } - - // TODO add spaces_between_special_tokens and clean_up_tokenization_spaces options - - return sub_texts; - } -} - -/** - * The CTC (Connectionist Temporal Classification) decoder. - * See https://github.com/huggingface/tokenizers/blob/bb38f390a61883fc2f29d659af696f428d1cda6b/tokenizers/src/decoders/ctc.rs - */ -class CTCDecoder extends Decoder { - - constructor(config) { - super(config); - - this.pad_token = this.config.pad_token; - this.word_delimiter_token = this.config.word_delimiter_token; - this.cleanup = this.config.cleanup; - } - /** - * Converts a connectionist-temporal-classification (CTC) output tokens into a single string. - * @param {string[]} tokens Array of tokens to be decoded. - * @returns {string} The decoded string. - */ - convert_tokens_to_string(tokens) { - if (tokens.length === 0) return ''; - - // group same tokens into non-repeating tokens in CTC style decoding - const grouped_tokens = [tokens[0]]; - for (let i = 1; i < tokens.length; ++i) { - if (tokens[i] !== grouped_tokens.at(-1)) { - grouped_tokens.push(tokens[i]); - } - } - - // filter self.pad_token which is used as CTC-blank token - const filtered_tokens = grouped_tokens.filter(token => token !== this.pad_token); - - let text = filtered_tokens.join(''); - if (this.cleanup) { - // cleanup and replace delimiter token - text = clean_up_tokenization(text) - .replaceAll(this.word_delimiter_token, ' ') - .trim(); + } else { + let y_padding = [0, 0]; + let y_extract = 0; + if (height_offset < 0) { + y_padding[0] = Math.floor(-height_offset); + y_padding[1] = crop_height - this.height - y_padding[0]; + } else { + y_extract = Math.floor(height_offset); } - return text; + let x_padding = [0, 0]; + let x_extract = 0; + if (width_offset < 0) { + x_padding[0] = Math.floor(-width_offset); + x_padding[1] = crop_width - this.width - x_padding[0]; + } else { + x_extract = Math.floor(width_offset); + } + img = img.extend({ + top: y_padding[0], + bottom: y_padding[1], + left: x_padding[0], + right: x_padding[1] + }).extract({ + left: x_extract, + top: y_extract, + width: crop_width, + height: crop_height + }); + } + return await loadImageFunction(img); } - - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return [this.convert_tokens_to_string(tokens)]; + } + async toBlob(type = "image/png", quality = 1) { + if (!apis.IS_WEB_ENV) { + throw new Error("toBlob() is only supported in browser environments."); } -} - -/** - * Apply a sequence of decoders. - * @extends Decoder - */ -class DecoderSequence extends Decoder { - - /** - * Creates a new instance of DecoderSequence. - * @param {Object} config The configuration object. - * @param {Object[]} config.decoders The list of decoders to apply. - */ - constructor(config) { - super(config); - this.decoders = config.decoders.map(x => Decoder.fromConfig(x)); + const canvas = this.toCanvas(); + return await canvas.convertToBlob({ type, quality }); + } + toTensor(channel_format = "CHW") { + let tensor = new Tensor3("uint8", new Uint8Array(this.data), [this.height, this.width, this.channels]); + if (channel_format === "HWC") { + } else if (channel_format === "CHW") { + tensor = tensor.permute(2, 0, 1); + } else { + throw new Error(`Unsupported channel format: ${channel_format}`); } - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - // Use reduce to apply each decoder to the tokens - return this.decoders.reduce((toks, decoder) => { - return decoder.decode_chain(toks); - }, tokens); + return tensor; + } + toCanvas() { + if (!apis.IS_WEB_ENV) { + throw new Error("toCanvas() is only supported in browser environments."); + } + const cloned = this.clone().rgba(); + const clonedCanvas = createCanvasFunction(cloned.width, cloned.height); + const data = new ImageDataClass(cloned.data, cloned.width, cloned.height); + clonedCanvas.getContext("2d").putImageData(data, 0, 0); + return clonedCanvas; + } + /** + * Split this image into individual bands. This method returns an array of individual image bands from an image. + * For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). + * + * Inspired by PIL's `Image.split()` [function](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.split). + * @returns {RawImage[]} An array containing bands. + */ + split() { + const { data, width, height, channels } = this; + const data_type = ( + /** @type {any} */ + data.constructor + ); + const per_channel_length = data.length / channels; + const split_data = Array.from({ length: channels }, () => new data_type(per_channel_length)); + for (let i = 0; i < per_channel_length; ++i) { + const data_offset = channels * i; + for (let j2 = 0; j2 < channels; ++j2) { + split_data[j2][i] = data[data_offset + j2]; + } } - -} - -class BPEDecoder extends Decoder { - constructor(config) { - super(config); - - this.suffix = this.config.suffix; + return split_data.map((data2) => new _RawImage(data2, width, height, 1)); + } + /** + * Helper method to update the image data. + * @param {Uint8ClampedArray} data The new image data. + * @param {number} width The new width of the image. + * @param {number} height The new height of the image. + * @param {1|2|3|4|null} [channels] The new number of channels of the image. + * @private + */ + _update(data, width, height, channels = null) { + this.data = data; + this.width = width; + this.height = height; + if (channels !== null) { + this.channels = channels; + } + return this; + } + /** + * Clone the image + * @returns {RawImage} The cloned image + */ + clone() { + return new _RawImage(this.data.slice(), this.width, this.height, this.channels); + } + /** + * Helper method for converting image to have a certain number of channels + * @param {number} numChannels The number of channels. Must be 1, 3, or 4. + * @returns {RawImage} `this` to support chaining. + */ + convert(numChannels) { + if (this.channels === numChannels) return this; + switch (numChannels) { + 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}`); } - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - return tokens.map((token, i) => { - return token.replaceAll(this.suffix, (i === tokens.length - 1) ? '' : ' ') - }); + return this; + } + /** + * Save the image to the given path. + * @param {string} path The path to save the image to. + * @returns {Promise} + */ + async save(path) { + if (apis.IS_WEB_ENV) { + if (apis.IS_WEBWORKER_ENV) { + throw new Error("Unable to save an image from a Web Worker."); + } + const extension = path.split(".").pop().toLowerCase(); + const mime = CONTENT_TYPE_MAP2.get(extension) ?? "image/png"; + const blob = await this.toBlob(mime); + return saveBlob(path, blob); + } else if (apis.IS_FS_AVAILABLE) { + const img = this.toSharp(); + await img.toFile(path); + } else { + throw new Error("Unable to save the image because filesystem is disabled in this environment."); } -} - -// Custom decoder for VITS -class VitsDecoder extends Decoder { - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - let decoded = ''; - for (let i = 1; i < tokens.length; i += 2) { - decoded += tokens[i]; + } + /** + * Convert the image to a Sharp instance. + * @returns {import('sharp').Sharp} The Sharp instance. + */ + toSharp() { + if (apis.IS_WEB_ENV) { + throw new Error("toSharp() is only supported in server-side environments."); + } + return sharp_default(this.data, { + raw: { + width: this.width, + height: this.height, + channels: this.channels + } + }); + } +}; +var load_image = RawImage.read.bind(RawImage); + +// src/models/gemma4/image_processing_gemma4.js +function get_aspect_ratio_preserving_size(height, width, patch_size, max_patches, pooling_kernel_size) { + const target_px = max_patches * patch_size ** 2; + const factor = Math.sqrt(target_px / (height * width)); + const side_mult = pooling_kernel_size * patch_size; + let target_height = Math.floor(factor * height / side_mult) * side_mult; + let target_width = Math.floor(factor * width / side_mult) * side_mult; + if (target_height === 0 && target_width === 0) { + throw new Error( + `Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${side_mult}.` + ); + } + const max_side_length = Math.floor(max_patches / pooling_kernel_size ** 2) * side_mult; + if (target_height === 0) { + target_height = side_mult; + target_width = Math.min(Math.floor(width / height) * side_mult, max_side_length); + } else if (target_width === 0) { + target_width = side_mult; + target_height = Math.min(Math.floor(height / width) * side_mult, max_side_length); + } + return [target_height, target_width]; +} +function patchify(hwc_data, H, W, C, patch_size, max_patches, pooling_kernel_size) { + const num_patches_h = Math.floor(H / patch_size); + const num_patches_w = Math.floor(W / patch_size); + const num_patches = num_patches_h * num_patches_w; + const patch_dim = patch_size * patch_size * C; + const patch_data = new Float32Array(max_patches * patch_dim); + let out = 0; + for (let ph = 0; ph < num_patches_h; ++ph) { + for (let pw = 0; pw < num_patches_w; ++pw) { + for (let dy = 0; dy < patch_size; ++dy) { + const row_offset = (ph * patch_size + dy) * W * C + pw * patch_size * C; + for (let dx = 0; dx < patch_size; ++dx) { + const src = row_offset + dx * C; + for (let c = 0; c < C; ++c) { + patch_data[out++] = hwc_data[src + c]; + } } - return [decoded]; - } -} - - -/** - * This PreTokenizer replaces spaces with the given replacement character, adds a prefix space if requested, - * and returns a list of tokens. - * @extends PreTokenizer - */ -class MetaspacePreTokenizer extends PreTokenizer { - /** - * @param {Object} config The configuration object for the MetaspacePreTokenizer. - * @param {boolean} config.add_prefix_space Whether to add a prefix space to the first token. - * @param {string} config.replacement The character to replace spaces with. - * @param {string} [config.str_rep=config.replacement] An optional string representation of the replacement character. - * @param {'first'|'never'|'always'} [config.prepend_scheme='always'] The metaspace prepending scheme. - */ - constructor(config) { - super(); - - this.addPrefixSpace = config.add_prefix_space; - this.replacement = config.replacement; - this.strRep = config.str_rep || this.replacement; - this.prepend_scheme = config.prepend_scheme ?? 'always'; + } } - - /** - * This method takes a string, replaces spaces with the replacement character, - * adds a prefix space if requested, and returns a new list of tokens. - * @param {string} text The text to pre-tokenize. - * @param {Object} [options] The options for the pre-tokenization. - * @param {number} [options.section_index] The index of the section to pre-tokenize. - * @returns {string[]} A new list of pre-tokenized tokens. - */ - pre_tokenize_text(text, { - section_index = undefined, - } = {}) { - - let normalized = text.replaceAll(' ', this.strRep); - - if ( - // We add a prefix space if: - // (1) The addPrefixSpace option is enabled and the normalized - // token does not already start with the replacement character. - (this.addPrefixSpace && !normalized.startsWith(this.replacement)) - - // and (2) either: - // (a) prepend_scheme is 'always' - // (b) prepend_scheme is 'first' and this is the first section - && ( - this.prepend_scheme === 'always' || - (this.prepend_scheme === 'first' && section_index === 0) - ) - ) { - normalized = this.strRep + normalized; - } - return [normalized]; + } + const pos_data = new BigInt64Array(max_patches * 2).fill(-1n); + let idx = 0; + for (let row = 0; row < num_patches_h; ++row) { + for (let col = 0; col < num_patches_w; ++col) { + pos_data[idx++] = BigInt(col); + pos_data[idx++] = BigInt(row); } + } + return { + patches: new Tensor3("float32", patch_data, [max_patches, patch_dim]), + positions: new Tensor3("int64", pos_data, [max_patches, 2]), + num_soft_tokens: Math.floor(num_patches / pooling_kernel_size ** 2) + }; } - -/** - * MetaspaceDecoder class extends the Decoder class and decodes Metaspace tokenization. - * @extends Decoder - */ -class MetaspaceDecoder extends Decoder { - /** - * Constructs a new MetaspaceDecoder object. - * @param {Object} config The configuration object for the MetaspaceDecoder. - * @param {boolean} config.add_prefix_space Whether to add a prefix space to the decoded string. - * @param {string} config.replacement The string to replace spaces with. - */ - constructor(config) { - super(config); - - this.addPrefixSpace = config.add_prefix_space; - this.replacement = config.replacement; - } - - /** @type {Decoder['decode_chain']} */ - decode_chain(tokens) { - const result = []; - for (let i = 0; i < tokens.length; ++i) { - let normalized = tokens[i].replaceAll(this.replacement, ' '); - if (this.addPrefixSpace && i == 0 && normalized.startsWith(' ')) { - normalized = normalized.substring(1); - } - result.push(normalized); +var Gemma4ImageProcessor = class extends Callable { + /** @param {Record} config */ + constructor(config) { + super(); + this.config = config; + this.patch_size = config.patch_size ?? 16; + this.max_soft_tokens = config.max_soft_tokens ?? 280; + this.pooling_kernel_size = config.pooling_kernel_size ?? 3; + this.resample = config.resample ?? 3; + this.rescale_factor = config.rescale_factor ?? 1 / 255; + this.do_rescale = config.do_rescale ?? true; + this.do_resize = config.do_resize ?? true; + this.do_convert_rgb = config.do_convert_rgb ?? true; + } + /** + * @param {RawImage|RawImage[]} images + * @returns {Promise<{ pixel_values: Tensor, image_position_ids: Tensor, num_soft_tokens_per_image: number[] }>} + */ + async _call(images) { + if (!Array.isArray(images)) { + images = [images]; + } + const { patch_size, pooling_kernel_size } = this; + const max_patches = this.max_soft_tokens * pooling_kernel_size ** 2; + const all_patches = []; + const all_positions = []; + const num_soft_tokens_per_image = []; + for (let image of images) { + if (this.do_convert_rgb) { + image = image.rgb(); + } + if (this.do_resize) { + const [target_h, target_w] = get_aspect_ratio_preserving_size( + image.height, + image.width, + patch_size, + max_patches, + pooling_kernel_size + ); + if (target_h !== image.height || target_w !== image.width) { + image = await image.resize(target_w, target_h, { resample: this.resample }); + } + } + const pixelData = Float32Array.from(image.data); + if (this.do_rescale) { + for (let i = 0; i < pixelData.length; ++i) { + pixelData[i] *= this.rescale_factor; } - return result; + } + const { patches, positions, num_soft_tokens } = patchify( + pixelData, + image.height, + image.width, + image.channels, + patch_size, + max_patches, + pooling_kernel_size + ); + all_patches.push(patches); + all_positions.push(positions); + num_soft_tokens_per_image.push(num_soft_tokens); } -} + return { + pixel_values: stack(all_patches, 0), + image_position_ids: stack(all_positions, 0), + num_soft_tokens_per_image + }; + } +}; -/** - * A normalizer that applies a precompiled charsmap. - * This is useful for applying complex normalizations in C++ and exposing them to JavaScript. - * @extends Normalizer - * @param {Object} config The configuration object for the Precompiled normalizer. - * @param {Object} config.precompiled_charsmap The precompiled charsmap object. - */ -class Precompiled extends Normalizer { - /** - * Create a new instance of Precompiled normalizer. - * @param {Object} config The configuration object. - * @param {any} config.precompiled_charsmap Precompiled chars mapping. - */ - constructor(config) { - super(config); - this.charsmap = config.precompiled_charsmap; +// src/models/gemma4/processing_gemma4.js +var Gemma4Processor = class extends Processor { + static uses_processor_config = true; + static uses_chat_template_file = true; + constructor(config, components, chat_template) { + super(config, components, chat_template); + this.audio_ms_per_token = this.config.audio_ms_per_token ?? 40; + this.audio_seq_length = this.config.audio_seq_length ?? 750; + this.image_seq_length = this.config.image_seq_length ?? 280; + const { audio_token, boa_token, eoa_token, image_token, boi_token, eoi_token } = this.tokenizer.config; + this.audio_token = audio_token; + this.boa_token = boa_token; + this.eoa_token = eoa_token; + this.image_token = image_token; + this.boi_token = boi_token; + this.eoi_token = eoi_token; + } + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const [config, tokenizer, chat_template] = await Promise.all([ + getModelJSON(pretrained_model_name_or_path, PROCESSOR_NAME, true, options), + AutoTokenizer.from_pretrained(pretrained_model_name_or_path, options), + getModelText(pretrained_model_name_or_path, CHAT_TEMPLATE_NAME, false, options) + ]); + const components = { tokenizer }; + if (config.image_processor) { + components.image_processor = new Gemma4ImageProcessor(config.image_processor); } - - /** - * Normalizes the given text by applying the precompiled charsmap. - * @param {string} text The text to normalize. - * @returns {string} The normalized text. - */ - normalize(text) { - // As stated in the sentencepiece normalization docs (https://github.com/google/sentencepiece/blob/master/doc/normalization.md#use-pre-defined-normalization-rule), - // there are 5 pre-defined normalization rules: - // 1. nmt_nfkc: NFKC normalization with some additional normalization around spaces. (default) - // 2. nfkc: original NFKC normalization. - // 3. nmt_nfkc_cf: nmt_nfkc + Unicode case folding (mostly lower casing) - // 4. nfkc_cf: nfkc + Unicode case folding. - // 5. identity: no normalization - // - // For now, we only implement the default (nmt_nfkc). - // See https://raw.githubusercontent.com/google/sentencepiece/master/data/nmt_nfkc.tsv for the full list of rules. - // TODO: detect when a different `this.charsmap` is used. - - text = text.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm, ''); // Remove control characters - text = text.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm, '\u0020'); // Replace certain characters with a space - - if (text.includes('\uFF5E')) { - // To match the sentencepiece implementation 100%, we must handle a very strange edge-case. - // For some reason, the "Fullwidth Tilde" character (\uFF5E) should not be converted to the standard Tilde character (\u007E). - // However, NFKC normalization does do this conversion. As a result, we split the string on the Fullwidth Tilde character, - // perform NFKC normalization on each substring, and then join them back together with the Fullwidth Tilde character. - const parts = text.split('\uFF5E'); - text = parts.map(part => part.normalize('NFKC')).join('\uFF5E'); - } else { - text = text.normalize('NFKC'); - } - - return text; + if (config.feature_extractor) { + components.feature_extractor = new Gemma4AudioFeatureExtractor(config.feature_extractor); } -} - -/** - * A pre-tokenizer that applies a sequence of pre-tokenizers to the input text. - * @extends PreTokenizer - */ -class PreTokenizerSequence extends PreTokenizer { - /** - * Creates an instance of PreTokenizerSequence. - * @param {Object} config The configuration object for the pre-tokenizer sequence. - * @param {Object[]} config.pretokenizers An array of pre-tokenizer configurations. - */ - constructor(config) { - super(); - this.tokenizers = config.pretokenizers.map(x => PreTokenizer.fromConfig(x)); + return new this(config, components, chat_template); + } + /** + * Compute the number of audio soft tokens for a single waveform. + * Replicates the audio encoder's sequence-length arithmetic: + * mel framing → two SSCP conv layers (kernel=3, stride=2) → cap. + * @param {number} num_samples + * @param {number} sampling_rate + * @returns {number} + */ + _compute_audio_num_tokens(num_samples, sampling_rate) { + const frame_length = Math.round(sampling_rate * 20 / 1e3); + const hop_length = Math.round(sampling_rate * 10 / 1e3); + const pad_left = Math.floor(frame_length / 2); + let t = Math.floor((num_samples + pad_left - frame_length - 1) / hop_length) + 1; + if (t <= 0) return 0; + for (let i = 0; i < 2; ++i) t = Math.floor((t - 1) / 2) + 1; + return Math.min(t, this.audio_seq_length); + } + async _call(text, images = null, audio = null, options = {}) { + if (typeof text === "string") { + text = [text]; + } + let image_inputs; + if (images) { + image_inputs = await this.image_processor(images, options); + const counts = image_inputs.num_soft_tokens_per_image; + let i = 0; + text = text.map( + (t) => t.replaceAll( + this.image_token, + () => ` + +${this.boi_token}${this.image_token.repeat(counts[i++])}${this.eoi_token} + +` + ) + ); } + let audio_inputs; + if (audio) { + const audio_array = Array.isArray(audio) ? audio : [audio]; + audio_inputs = await this.feature_extractor(audio_array[0], options); + const sampling_rate = this.feature_extractor.config.sampling_rate ?? 16e3; + let i = 0; + text = text.map( + (t) => t.replaceAll( + this.audio_token, + () => ` - /** - * Applies each pre-tokenizer in the sequence to the input text in turn. - * @param {string} text The text to pre-tokenize. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} The pre-tokenized text. - */ - pre_tokenize_text(text, options) { - // Use reduce to apply each tokenizer to the text - return this.tokenizers.reduce((preTokenizedText, tokenizer) => { - return tokenizer.pre_tokenize(preTokenizedText, options); - }, [text]); - } -} +${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(audio_array[i++].length, sampling_rate))}${this.eoa_token} -/** - * Splits on word boundaries (using the following regular expression: `\w+|[^\w\s]+`). - */ -class WhitespacePreTokenizer extends PreTokenizer { - /** - * Creates an instance of WhitespacePreTokenizer. - * @param {Object} config The configuration object for the pre-tokenizer. - */ - constructor(config) { - super(); - } - /** - * Pre-tokenizes the input text by splitting it on word boundaries. - * @param {string} text The text to be pre-tokenized. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. - */ - pre_tokenize_text(text, options) { - return text.match(/\w+|[^\w\s]+/g) || []; +` + ) + ); } -} + return { + ...this.tokenizer(text, options), + ...image_inputs, + ...audio_inputs + }; + } +}; -/** - * Splits a string of text by whitespace characters into individual tokens. - * @extends PreTokenizer - */ -class WhitespaceSplit extends PreTokenizer { - /** - * Creates an instance of WhitespaceSplit. - * @param {Object} config The configuration object for the pre-tokenizer. - */ - constructor(config) { - super(); - } - /** - * Pre-tokenizes the input text by splitting it on whitespace characters. - * @param {string} text The text to be pre-tokenized. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens produced by splitting the input text on whitespace. - */ - pre_tokenize_text(text, options) { - return whitespace_split(text); +// src/models/embedding_gemma2/video_processing_embedding_gemma2.js +var EmbeddingGemma2VideoProcessor = class extends Callable { + /** @param {Record} config */ + constructor(config) { + super(); + this.config = config; + this.frame_processor = new Gemma4ImageProcessor(config); + this.max_frames = config.max_frames ?? 32; + this.overflow_strategy = config.overflow_strategy ?? "uniform"; + } + /** + * @template T + * @param {T[]} frames + * @returns {T[]} At most `max_frames` of the frames. + */ + sample_frames(frames) { + const num_frames = frames.length; + const { max_frames } = this; + if (num_frames <= max_frames) return frames; + if (this.overflow_strategy === "truncate") return frames.slice(0, max_frames); + const step = max_frames > 1 ? (num_frames - 1) / (max_frames - 1) : 0; + return Array.from( + { length: max_frames }, + (_, i) => frames[i > 0 && i === max_frames - 1 ? num_frames - 1 : Math.floor(i * step)] + ); + } + /** + * @param {import('../../utils/video.js').RawVideo|import('../../utils/video.js').RawVideo[]} videos + */ + async _call(videos) { + if (!Array.isArray(videos)) { + videos = [videos]; } -} + const frames = videos.map((video) => this.sample_frames(video.frames.map((frame) => frame.image))); + const { pixel_values, image_position_ids, num_soft_tokens_per_image } = await this.frame_processor( + frames.flat() + ); + let num_previous_frames = 0; + return { + // The frames of all videos, concatenated + pixel_values_videos: pixel_values, + video_position_ids: image_position_ids, + num_frames_per_video: frames.map((x) => x.length), + // The frames of a video have the same size, hence the same number of soft tokens + num_soft_tokens_per_video: frames.map( + (x) => num_soft_tokens_per_image[(num_previous_frames += x.length) - 1] + ) + }; + } +}; -// NOTE: `ReplacePreTokenizer` is custom (to support `BlenderbotSmallTokenizer`) -class ReplacePreTokenizer extends PreTokenizer { - /** - * @param {Object} config The configuration options for the pre-tokenizer. - * @param {Object} config.pattern The pattern used to split the text. Can be a string or a regex object. - * @param {string} config.content What to replace the pattern with. - */ - constructor(config) { - super(); - this.config = config; - this.pattern = createPattern(this.config.pattern); - this.content = this.config.content; +// src/models/embedding_gemma2/processing_embedding_gemma2.js +function nest(items, flat_is_one_sample) { + if (!Array.isArray(items)) return [[items]]; + if (items.every((x) => Array.isArray(x))) return items; + return flat_is_one_sample ? [items] : items.map((x) => [x]); +} +function expand_placeholders(text, token, replacements) { + let i = 0; + text = text.map((t) => t.replaceAll(token, () => replacements[i++] ?? "")); + if (i !== replacements.length) { + throw new Error(`Found ${i} ${token} tokens in the text, but ${replacements.length} inputs were passed.`); + } + return text; +} +var EmbeddingGemma2Processor = class extends Gemma4Processor { + constructor(config, components, chat_template) { + super(config, components, chat_template); + this.video_token = this.tokenizer.config.video_token; + this.video_processor = config.video_processor && new EmbeddingGemma2VideoProcessor(config.video_processor); + } + /** + * Prepares any mix of text, images, audio and videos for `EmbeddingGemma2Model`. + * + * Each `<|image|>`, `<|audio|>` or `<|video|>` placeholder of the text is expanded to the soft tokens of the next + * item of that modality, in order across the batch. Without text, each sample holds the placeholders of its media + * (images, then videos, then audio). As in Python, a flat list of images is then a single sample, and a flat list + * of audio clips or videos is one sample per item: pass one list per sample to group them differently. + * + * @param {string|string[]|null} text The text, with a placeholder per media item. + * @param {import('../../utils/image.js').RawImage|import('../../utils/image.js').RawImage[]|import('../../utils/image.js').RawImage[][]} [images] + * @param {Float32Array|Float32Array[]|Float32Array[][]} [audio] Mono audio at the feature extractor's sampling rate (16 kHz). + * @param {import('../../utils/video.js').RawVideo|import('../../utils/video.js').RawVideo[]|import('../../utils/video.js').RawVideo[][]} [videos] + * @param {Object} [options] Additional options for the tokenizer. + */ + async _call(text, images = null, audio = null, videos = null, options = {}) { + const media = [ + [this.image_token, images && nest(images, true)], + [this.video_token, videos && nest(videos, false)], + [this.audio_token, audio && nest(audio, false)] + ]; + if (text == null) { + const present = media.filter(([, samples]) => samples); + const batch_size = present[0]?.[1].length; + if (present.some(([, samples]) => samples.length !== batch_size)) { + throw new Error("Received a different number of samples per modality."); + } + text = Array.from( + { length: batch_size }, + (_, i) => present.flatMap(([token, samples]) => Array(samples[i].length).fill(token)).join(" ") + ); + } else if (typeof text === "string") { + text = [text]; + } + const [image_list, video_list, audio_list] = media.map(([, samples]) => samples?.flat()); + const image_inputs = image_list && await this.image_processor(image_list); + const video_inputs = video_list && await this.video_processor(video_list); + const audio_inputs = audio_list && await this._process_audio(audio_list); + const { image_token, video_token, audio_token, boi_token, eoi_token, boa_token, eoa_token } = this; + const replacements = { + [image_token]: image_inputs?.num_soft_tokens_per_image.map( + (n) => boi_token + image_token.repeat(n) + eoi_token + ), + // One image-like block per frame + [video_token]: video_inputs?.num_soft_tokens_per_video.map( + (n, i) => (boi_token + video_token.repeat(n) + eoi_token).repeat(video_inputs.num_frames_per_video[i]) + ), + [audio_token]: audio_inputs?.num_soft_tokens_per_audio.map( + (n) => boa_token + audio_token.repeat(n) + eoa_token + ) + }; + for (const [token, strings] of Object.entries(replacements)) { + text = expand_placeholders(text, token, strings ?? []); } + return { + ...this.tokenizer(text, { padding: true, ...options }), + ...image_inputs, + ...video_inputs, + ...audio_inputs + }; + } + /** + * Extracts the features of each clip and pads them to the longest one. + * @param {Float32Array[]} clips + */ + async _process_audio(clips) { + const outputs = []; + for (const clip of clips) { + outputs.push(await this.feature_extractor(clip)); + } + const num_frames = Math.max(...outputs.map((x) => x.input_features.dims[1])); + const feature_size = outputs[0].input_features.dims[2]; + const input_features = new Float32Array(clips.length * num_frames * feature_size); + const input_features_mask = new Uint8Array(clips.length * num_frames); + outputs.forEach((x, i) => { + input_features.set(x.input_features.data, i * num_frames * feature_size); + input_features_mask.set(x.input_features_mask.data, i * num_frames); + }); + return { + input_features: new Tensor3("float32", input_features, [clips.length, num_frames, feature_size]), + input_features_mask: new Tensor3("bool", input_features_mask, [clips.length, num_frames]), + // The audio encoder keeps every 4th frame (two stride-2 convolutions) + num_soft_tokens_per_audio: outputs.map(({ input_features_mask: { data } }) => { + let num_tokens = 0; + for (let i = 0; i < data.length; i += 4) num_tokens += Number(data[i]); + return num_tokens; + }) + }; + } +}; - /** - * Pre-tokenizes the input text by replacing certain characters. - * @param {string} text The text to be pre-tokenized. - * @param {Object} [options] Additional options for the pre-tokenization logic. - * @returns {string[]} An array of tokens produced by replacing certain characters. - */ - pre_tokenize_text(text, options) { - if (this.pattern === null) { - return [text]; - } - return [text.replaceAll(this.pattern, this.config.content)]; - } -} - -const SPECIAL_TOKEN_ATTRIBUTES = [ - 'bos_token', - 'eos_token', - 'unk_token', - 'sep_token', - 'pad_token', - 'cls_token', - 'mask_token', - // additional_special_tokens (TODO) -] - -/** - * - * Helper function for padding values of an object, which are each arrays. - * NOTE: No additional checks are made here for validity of arguments. - * @param {Record} item The input object. - * @param {number} length The length to pad to. - * @param {(key: string) => any} value_fn Determine the value to fill the array, based on its key. - * @param {string} side Which side to pad the array. - * @private - */ -function padHelper(item, length, value_fn, side) { - for (const key of Object.keys(item)) { - const diff = length - item[key].length; - const value = value_fn(key); - - const padData = new Array(diff).fill(value); - item[key] = side === 'right' - ? (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(item[key], padData) - : (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(padData, item[key]); - } +// src/image_processors_utils.js +function constraint_to_multiple_of(val, multiple, minVal = 0, maxVal = null) { + const a = val / multiple; + let x = bankers_round(a) * multiple; + if (maxVal !== null && x > maxVal) { + x = Math.floor(a) * multiple; + } + if (x < minVal) { + x = Math.ceil(a) * multiple; + } + return x; } - -/** - * Helper function for truncating values of an object, which are each arrays. - * NOTE: No additional checks are made here for validity of arguments. - * @param {Record} item The input object. - * @param {number} length The length to truncate to. - * @private - */ -function truncateHelper(item, length) { - // Setting .length to a lower value truncates the array in-place: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length - for (const key of Object.keys(item)) { - item[key].length = length; - } +function enforce_size_divisibility([width, height], divisor) { + return [Math.max(Math.floor(width / divisor), 1) * divisor, Math.max(Math.floor(height / divisor), 1) * divisor]; } - - -/** - * @typedef {Object} Message - * @property {string} role The role of the message (e.g., "user" or "assistant" or "system"). - * @property {string} content The content of the message. - */ - -class PreTrainedTokenizer extends _utils_generic_js__WEBPACK_IMPORTED_MODULE_0__.Callable { - return_token_type_ids = false; - - padding_side = 'right'; - /** - * Create a new PreTrainedTokenizer instance. - * @param {Object} tokenizerJSON The JSON of the tokenizer. - * @param {Object} tokenizerConfig The config of the tokenizer. - */ - constructor(tokenizerJSON, tokenizerConfig) { - super(); - - this.config = tokenizerConfig; - - // Construct parts of the tokenizer from the JSON - this.normalizer = Normalizer.fromConfig(tokenizerJSON.normalizer); - this.pre_tokenizer = PreTokenizer.fromConfig(tokenizerJSON.pre_tokenizer); - this.model = TokenizerModel.fromConfig(tokenizerJSON.model, tokenizerConfig); - this.post_processor = PostProcessor.fromConfig(tokenizerJSON.post_processor); - this.decoder = Decoder.fromConfig(tokenizerJSON.decoder); - - // Add added_tokens to model - this.special_tokens = []; - this.all_special_ids = []; - - /** @type {AddedToken[]} */ - this.added_tokens = []; - for (const addedToken of tokenizerJSON.added_tokens) { - const token = new AddedToken(addedToken); - this.added_tokens.push(token); - - this.model.tokens_to_ids.set(token.content, token.id); - this.model.vocab[token.id] = token.content; - - if (token.special) { - this.special_tokens.push(token.content); - this.all_special_ids.push(token.id); - } - } - - // Update additional_special_tokens - this.additional_special_tokens = tokenizerConfig.additional_special_tokens ?? []; - this.special_tokens.push(...this.additional_special_tokens); - this.special_tokens = [...new Set(this.special_tokens)]; // Remove duplicates - - if (this.decoder) { - // Slight hack, but it prevents code duplication: - this.decoder.added_tokens = this.added_tokens; - - // Another slight hack to add `end_of_word_suffix` (if present) to the decoder - // This is needed for cases where BPE model and ByteLevel decoder are used - // For more information, see https://github.com/huggingface/transformers.js/issues/74 - // TODO: save this to the decoder when exporting? - this.decoder.end_of_word_suffix = this.model.end_of_word_suffix; +function center_to_corners_format([centerX, centerY, width, height]) { + return [centerX - width / 2, centerY - height / 2, centerX + width / 2, centerY + height / 2]; +} +function post_process_object_detection(outputs, threshold = 0.5, target_sizes = null, is_zero_shot = false) { + const out_logits = outputs.logits; + const out_bbox = outputs.pred_boxes; + const [batch_size, num_boxes, num_classes] = out_logits.dims; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + let toReturn = []; + for (let i = 0; i < batch_size; ++i) { + let target_size = target_sizes !== null ? target_sizes[i] : null; + let info = { + boxes: [], + classes: [], + scores: [] + }; + let logits = out_logits[i]; + let bbox = out_bbox[i]; + for (let j2 = 0; j2 < num_boxes; ++j2) { + let logit = logits[j2]; + let indices = []; + let probs; + if (is_zero_shot) { + probs = logit.sigmoid().data; + for (let k = 0; k < probs.length; ++k) { + if (probs[k] > threshold) { + indices.push(k); + } } - - this.added_tokens_splitter = new _utils_data_structures_js__WEBPACK_IMPORTED_MODULE_5__.DictionarySplitter( - this.added_tokens.map(x => x.content), - ); - - /** @type {Map} */ - this.added_tokens_map = new Map(this.added_tokens.map(x => [x.content, x])) - - // Set mask token if present (otherwise will be undefined, which is fine) - 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 = tokenizerConfig.model_max_length; - - /** @type {boolean} Whether or not to strip the text when tokenizing (removing excess spaces before and after the string). */ - this.remove_space = tokenizerConfig.remove_space; - - this.clean_up_tokenization_spaces = tokenizerConfig.clean_up_tokenization_spaces ?? true; - this.do_lowercase_and_remove_accent = tokenizerConfig.do_lowercase_and_remove_accent ?? false; - - if (tokenizerConfig.padding_side) { - this.padding_side = tokenizerConfig.padding_side; + } else { + let maxIndex = max(logit.data)[1]; + if (maxIndex === num_classes - 1) { + continue; } - - this.add_bos_token = tokenizerConfig.add_bos_token; - this.add_eos_token = tokenizerConfig.add_eos_token; - - this.legacy = false; - - this.chat_template = tokenizerConfig.chat_template ?? null; - if (Array.isArray(this.chat_template)) { - // Chat templates are stored as lists of dicts with fixed key names, - // we reconstruct that into a single dict while loading them. - const chat_template = Object.create(null); - for (const { name, template } of this.chat_template) { - if (typeof name !== 'string' || typeof template !== 'string') { - throw new Error('Chat template must be a list of objects with "name" and "template" properties'); - } - chat_template[name] = template; - } - this.chat_template = chat_template; + probs = softmax(logit.data); + if (probs[maxIndex] < threshold) { + continue; } - this._compiled_template_cache = new Map(); - } - - /** - * Returns the value of the first matching key in the tokenizer config object. - * @param {...string} keys One or more keys to search for in the tokenizer config object. - * @returns {string|null} The value associated with the first matching key, or null if no match is found. - * @throws {Error} If an object is found for a matching key and its __type property is not "AddedToken". - * @private - */ - getToken(...keys) { - for (const key of keys) { - const item = this.config[key]; - - if (!item) continue; - - if (typeof item === 'object') { - if (item.__type === 'AddedToken') { - return item.content; - } else { - throw Error(`Unknown token: ${item}`); - } - } else { - return item; - } + indices.push(maxIndex); + } + for (const index of indices) { + let box = bbox[j2].data; + box = center_to_corners_format(box); + if (target_size !== null) { + box = box.map((x, i2) => x * target_size[(i2 + 1) % 2]); } - return null; + info.boxes.push(box); + info.classes.push(index); + info.scores.push(probs[index]); + } } - - /** - * Loads a pre-trained tokenizer from the given `pretrained_model_name_or_path`. - * - * @param {string} pretrained_model_name_or_path The path to the pre-trained tokenizer. - * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. - * - * @throws {Error} Throws an error if the tokenizer.json or tokenizer_config.json files are not found in the `pretrained_model_name_or_path`. - * @returns {Promise} A new instance of the `PreTrainedTokenizer` class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = 'main', - legacy = null, - } = {}) { - - const info = await loadTokenizer(pretrained_model_name_or_path, { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - legacy, - }) - - // @ts-ignore - return new this(...info); + toReturn.push(info); + } + return toReturn; +} +function post_process_semantic_segmentation(outputs, target_sizes = null) { + const logits = outputs.logits; + const batch_size = logits.dims[0]; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + const toReturn = []; + for (let i = 0; i < batch_size; ++i) { + const target_size = target_sizes !== null ? target_sizes[i] : null; + let data = logits[i]; + if (target_size !== null) { + data = interpolate(data, target_size, "bilinear", false); } - - /** - * @typedef {number[]|number[][]|Tensor} BatchEncodingItem - * - * @typedef {Object} BatchEncoding Holds the output of the tokenizer's call function. - * @property {BatchEncodingItem} input_ids List of token ids to be fed to a model. - * @property {BatchEncodingItem} attention_mask List of indices specifying which tokens should be attended to by the model. - * @property {BatchEncodingItem} [token_type_ids] List of token type ids to be fed to a model. - */ - - /** - * Encode/tokenize the given text(s). - * @param {string|string[]} text The text to tokenize. - * @param {Object} options An optional object containing the following properties: - * @param {string|string[]} [options.text_pair=null] Optional second sequence to be encoded. If set, must be the same type as text. - * @param {boolean|'max_length'} [options.padding=false] Whether to pad the input sequences. - * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. - * @param {boolean} [options.truncation=null] Whether to truncate the input sequences. - * @param {number} [options.max_length=null] Maximum length of the returned list and optionally padding length. - * @param {boolean} [options.return_tensor=true] Whether to return the results as Tensors or arrays. - * @param {boolean} [options.return_token_type_ids=null] Whether to return the token type ids. - * @returns {BatchEncoding} Object to be passed to the model. - */ - _call( - // Required positional arguments - text, - - // Optional keyword arguments - { - text_pair = null, - add_special_tokens = true, - padding = false, - truncation = null, - max_length = null, - return_tensor = true, // Different to HF - return_token_type_ids = null, - } = {}, - ) { - - const isBatched = Array.isArray(text); - - /** @type {EncodingSingle[]} */ - let encodedTokens; - - if (isBatched) { - if (text.length === 0) { - throw Error('text array must be non-empty') - } - - if (text_pair !== null) { - if (!Array.isArray(text_pair)) { - throw Error('text_pair must also be an array') - - } else if (text.length !== text_pair.length) { - throw Error('text and text_pair must have the same length') - } - - encodedTokens = text.map( - (t, i) => this._encode_plus(t, { text_pair: text_pair[i], add_special_tokens, return_token_type_ids }) - ) - - } else { - encodedTokens = text.map(x => this._encode_plus(x, { add_special_tokens, return_token_type_ids })); - } - - } else { - if (text === null || text === undefined) { - throw Error('text may not be null or undefined') - } - - if (Array.isArray(text_pair)) { - throw Error('When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).') - } - - // For single input, we just wrap in an array, and then unwrap later. - encodedTokens = [this._encode_plus(text, { text_pair, add_special_tokens, return_token_type_ids })]; - } - // At this point, `encodedTokens` is batched, of shape [batch_size, tokens]. - // However, array may be jagged. So, we may need pad to max_length. - if (max_length === null) { - max_length = this.model_max_length; - } else if (truncation === null) { - if (padding === true) { - console.warn( - "`max_length` is ignored when `padding: true` and there is no truncation strategy. " + - "To pad to max length, use `padding: 'max_length'`." - ) - max_length = this.model_max_length; - } else if (padding === false) { - 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."); - truncation = true; - } - } - - // padding: 'max_length' doesn't require any additional calculation - // but padding: true has to calculate max_length from the sequences - if (padding === true) { - max_length = Math.min((0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.max)(encodedTokens.map(x => x.input_ids.length))[0], max_length ?? Infinity); - } - - // Ensure it is less than model max length - max_length = Math.min(max_length, this.model_max_length ?? Infinity); - - if (padding || truncation) { - - // Perform padding and/or truncation - for (let i = 0; i < encodedTokens.length; ++i) { - if (encodedTokens[i].input_ids.length === max_length) { - continue; - - } else if (encodedTokens[i].input_ids.length > max_length) { - // possibly truncate - if (truncation) { - truncateHelper(encodedTokens[i], max_length); - } - - } else { // t.length < max_length - // possibly pad - if (padding) { - padHelper( - encodedTokens[i], - max_length, - key => key === 'input_ids' ? this.pad_token_id : 0, - this.padding_side - ); - } - } - } - } - - const result = {}; - - if (return_tensor) { - if (!(padding && truncation)) { - // Not, guaranteed that all items have same length, so - // we perform additional check - - if ( - encodedTokens.some(x => { - for (const key of Object.keys(x)) { - if (x[key].length !== encodedTokens[0][key]?.length) { - return true; - } - } - return false; - }) - ) { - 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." - ) - } - } - - // Now we actually convert to tensor - // NOTE: In the same way as the python library, we return a batched tensor, regardless of - // whether we have a single input or multiple inputs. - const dims = [encodedTokens.length, encodedTokens[0].input_ids.length]; - - for (const key of Object.keys(encodedTokens[0])) { - result[key] = new _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('int64', - BigInt64Array.from(encodedTokens.flatMap(x => x[key]).map(BigInt)), - dims - ); - } - - } else { - for (const key of Object.keys(encodedTokens[0])) { - result[key] = encodedTokens.map(x => x[key]); - } - - // If not returning a tensor, we match the input type - if (!isBatched) { - // Input was not batched, so we unwrap - for (const key of Object.keys(result)) { - result[key] = result[key][0]; - } - } + const [height, width] = target_size ?? data.dims.slice(-2); + const segmentation = new Tensor3("int32", new Int32Array(height * width), [height, width]); + const buffer = data[0].data; + const segmentation_data = segmentation.data; + for (let j2 = 1; j2 < data.dims[0]; ++j2) { + const row = data[j2].data; + for (let k = 0; k < row.length; ++k) { + if (row[k] > buffer[k]) { + buffer[k] = row[k]; + segmentation_data[k] = j2; } - - return /** @type {BatchEncoding} */(result); + } } - - /** - * Encodes a single text using the preprocessor pipeline of the tokenizer. - * - * @param {string|null} text The text to encode. - * @returns {string[]|null} The encoded tokens. - */ - _encode_text(text) { - if (text === null) return null; - - // Actual function which does encoding, for a single text - // First, we take care of special tokens. Needed to avoid issues arising from - // normalization and/or pretokenization (which may not preserve special tokens) - const sections = this.added_tokens_splitter.split(text); - - // Process left/right stripping of added tokens - for (let i = 0; i < sections.length; ++i) { - const addedToken = this.added_tokens_map.get(sections[i]); - if (addedToken) { - if (addedToken.lstrip && i > 0) { - sections[i - 1] = sections[i - 1].trimEnd(); - } - if (addedToken.rstrip && i < sections.length - 1) { - sections[i + 1] = sections[i + 1].trimStart(); - } - } - } - - const tokens = sections.flatMap((x, section_index) => { - if (x.length === 0) return []; - if (this.added_tokens_map.has(x)) return [x]; // Return added tokens unchanged - - if (this.remove_space === true) { - x = x.trim().split(/\s+/).join(' '); - } - if (this.do_lowercase_and_remove_accent) { - x = lowercase_and_remove_accent(x); - } - - if (this.normalizer !== null) { - x = this.normalizer(x); - } - - // If, after normalization, this section is empty (e.g., trimming whitespace), - // we return an empty array - if (x.length === 0) { - return []; - } - - const sectionTokens = (this.pre_tokenizer !== null) ? this.pre_tokenizer(x, { - section_index, - }) : [x]; - - const tokens = this.model(sectionTokens); - - return tokens; - }); - - return tokens; + const hasLabel = new Array(data.dims[0]); + for (let j2 = 0; j2 < segmentation_data.length; ++j2) { + const index = segmentation_data[j2]; + hasLabel[index] = index; } - - /** - * Encodes a single text or a pair of texts using the model's tokenizer. - * - * @param {string} text The text to encode. - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.text_pair=null] The optional second text to encode. - * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. - * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids. - * @returns {EncodingSingle} An object containing the encoded text. - * @private - */ - _encode_plus(text, { - text_pair = null, - add_special_tokens = true, - return_token_type_ids = null, - } = {}) { - - const { tokens, token_type_ids } = this._tokenize_helper(text, { pair: text_pair, add_special_tokens }); - - const input_ids = this.model.convert_tokens_to_ids(tokens); - - const result = { - input_ids, - attention_mask: new Array(input_ids.length).fill(1), - } - if ((return_token_type_ids ?? this.return_token_type_ids) && token_type_ids) { - result.token_type_ids = token_type_ids; - } - return result; + const labels = hasLabel.filter((x) => x !== void 0); + toReturn.push({ segmentation, labels }); + } + return toReturn; +} +function remove_low_and_no_objects(class_logits, mask_logits, object_mask_threshold, num_labels) { + const mask_probs_item = []; + const pred_scores_item = []; + const pred_labels_item = []; + for (let j2 = 0; j2 < class_logits.dims[0]; ++j2) { + const cls = class_logits[j2]; + const mask = mask_logits[j2]; + const pred_label = max(cls.data)[1]; + if (pred_label === num_labels) { + continue; + } + const scores = softmax(cls.data); + const pred_score = scores[pred_label]; + if (pred_score > object_mask_threshold) { + mask_probs_item.push(mask); + pred_scores_item.push(pred_score); + pred_labels_item.push(pred_label); + } + } + return [mask_probs_item, pred_scores_item, pred_labels_item]; +} +function check_segment_validity(mask_labels, mask_probs, k, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8) { + const mask_k = []; + let mask_k_area = 0; + let original_area = 0; + const mask_probs_k_data = mask_probs[k].data; + for (let i = 0; i < mask_labels.length; ++i) { + if (mask_labels[i] === k) { + mask_k.push(i); + ++mask_k_area; } - - /** - * Internal helper function to tokenize a text, and optionally a pair of texts. - * @param {string} text The text to tokenize. - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.pair=null] The optional second text to tokenize. - * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. - * @returns {{tokens: string[], token_type_ids?: number[]}} An object containing the tokens and optionally the token type IDs. - */ - _tokenize_helper(text, { - pair = null, - add_special_tokens = false, - } = {}) { - const tokens = this._encode_text(text); - const tokens2 = this._encode_text(pair); - - return this.post_processor - ? this.post_processor(tokens, tokens2, { add_special_tokens }) - : { tokens: (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(tokens ?? [], tokens2 ?? []) }; + if (mask_probs_k_data[i] >= mask_threshold) { + ++original_area; } - - /** - * Converts a string into a sequence of tokens. - * @param {string} text The sequence to be encoded. - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.pair] A second sequence to be encoded with the first. - * @param {boolean} [options.add_special_tokens=false] Whether or not to add the special tokens associated with the corresponding model. - * @returns {string[]} The list of tokens. - */ - tokenize(text, { - pair = null, - add_special_tokens = false, - } = {}) { - return this._tokenize_helper(text, { pair, add_special_tokens }).tokens; + } + let mask_exists = mask_k_area > 0 && original_area > 0; + if (mask_exists) { + let area_ratio = mask_k_area / original_area; + mask_exists = area_ratio > overlap_mask_area_threshold; + } + return [mask_exists, mask_k]; +} +function compute_segments(mask_probs, pred_scores, pred_labels, mask_threshold, overlap_mask_area_threshold, label_ids_to_fuse = null, target_size = null) { + const [height, width] = target_size ?? mask_probs[0].dims; + const segmentation = new Tensor3("int32", new Int32Array(height * width), [height, width]); + const segments = []; + if (target_size !== null) { + for (let i = 0; i < mask_probs.length; ++i) { + mask_probs[i] = interpolate(mask_probs[i], target_size, "bilinear", false); } - - /** - * Encodes a single text or a pair of texts using the model's tokenizer. - * - * @param {string} text The text to encode. - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.text_pair=null] The optional second text to encode. - * @param {boolean} [options.add_special_tokens=true] Whether or not to add the special tokens associated with the corresponding model. - * @param {boolean} [options.return_token_type_ids=null] Whether to return token_type_ids. - * @returns {number[]} An array of token IDs representing the encoded text(s). - */ - encode(text, { - text_pair = null, - add_special_tokens = true, - return_token_type_ids = null, - } = {}) { - return this._encode_plus(text, { - text_pair, - add_special_tokens, - return_token_type_ids, - }).input_ids; + } + const mask_labels = new Int32Array(mask_probs[0].data.length); + const bestScores = new Float32Array(mask_probs[0].data.length); + for (let i = 0; i < mask_probs.length; ++i) { + let score = pred_scores[i]; + const mask_probs_i_data = mask_probs[i].data; + for (let j2 = 0; j2 < mask_probs_i_data.length; ++j2) { + mask_probs_i_data[j2] *= score; + if (mask_probs_i_data[j2] > bestScores[j2]) { + mask_labels[j2] = i; + bestScores[j2] = mask_probs_i_data[j2]; + } } - - /** - * Decode a batch of tokenized sequences. - * @param {number[][]|Tensor} batch List/Tensor of tokenized input sequences. - * @param {Object} decode_args (Optional) Object with decoding arguments. - * @returns {string[]} List of decoded sequences. - */ - batch_decode(batch, decode_args = {}) { - if (batch instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) { - batch = batch.tolist(); + } + let current_segment_id = 0; + const segmentation_data = segmentation.data; + for (let k = 0; k < pred_labels.length; ++k) { + const pred_class = pred_labels[k]; + const [mask_exists, mask_k] = check_segment_validity( + mask_labels, + mask_probs, + k, + mask_threshold, + overlap_mask_area_threshold + ); + if (!mask_exists) { + continue; + } + ++current_segment_id; + for (const index of mask_k) { + segmentation_data[index] = current_segment_id; + } + segments.push({ + id: current_segment_id, + label_id: pred_class, + // was_fused: should_fuse, TODO + score: pred_scores[k] + }); + } + return [segmentation, segments]; +} +function smart_resize(height, width, factor = 28, min_pixels = 56 * 56, max_pixels = 14 * 14 * 4 * 1280, temporal_factor = 1) { + if (height < factor || width < factor) { + const scale = Math.max(factor / height, factor / width); + height = Math.round(height * scale); + width = Math.round(width * scale); + } + if (Math.max(height, width) / Math.min(height, width) > 200) { + throw new Error( + `absolute aspect ratio must be smaller than 200, got ${Math.max(height, width) / Math.min(height, width)}` + ); + } + let h_bar = Math.round(height / factor) * factor; + let w_bar = Math.round(width / factor) * factor; + if (temporal_factor * h_bar * w_bar > max_pixels) { + const beta = Math.sqrt(temporal_factor * height * width / max_pixels); + h_bar = Math.max(factor, Math.floor(height / beta / factor) * factor); + w_bar = Math.max(factor, Math.floor(width / beta / factor) * factor); + } else if (temporal_factor * h_bar * w_bar < min_pixels) { + const beta = Math.sqrt(min_pixels / (temporal_factor * height * width)); + h_bar = Math.ceil(height * beta / factor) * factor; + w_bar = Math.ceil(width * beta / factor) * factor; + } + return [w_bar, h_bar]; +} +function post_process_panoptic_segmentation(outputs, threshold = 0.5, mask_threshold = 0.5, overlap_mask_area_threshold = 0.8, label_ids_to_fuse = null, target_sizes = null) { + if (label_ids_to_fuse === null) { + logger.warn("`label_ids_to_fuse` unset. No instance will be fused."); + label_ids_to_fuse = /* @__PURE__ */ new Set(); + } + const class_queries_logits = outputs.class_queries_logits ?? outputs.logits; + const masks_queries_logits = outputs.masks_queries_logits ?? outputs.pred_masks; + const mask_probs = masks_queries_logits.sigmoid(); + let [batch_size, num_queries, num_labels] = class_queries_logits.dims; + num_labels -= 1; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + let toReturn = []; + for (let i = 0; i < batch_size; ++i) { + let target_size = target_sizes !== null ? target_sizes[i] : null; + let class_logits = class_queries_logits[i]; + let mask_logits = mask_probs[i]; + let [mask_probs_item, pred_scores_item, pred_labels_item] = remove_low_and_no_objects( + class_logits, + mask_logits, + threshold, + num_labels + ); + if (pred_labels_item.length === 0) { + let [height, width] = target_size ?? mask_logits.dims.slice(-2); + let segmentation2 = new Tensor3("int32", new Int32Array(height * width).fill(-1), [height, width]); + toReturn.push({ + segmentation: segmentation2, + segments_info: [] + }); + continue; + } + let [segmentation, segments] = compute_segments( + mask_probs_item, + pred_scores_item, + pred_labels_item, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse, + target_size + ); + toReturn.push({ + segmentation, + segments_info: segments + }); + } + return toReturn; +} +function post_process_instance_segmentation(outputs, threshold = 0.5, target_sizes = null) { + throw new Error("`post_process_instance_segmentation` is not yet implemented."); +} +var ImageProcessor = class extends Callable { + /** + * Create an image processor from a parsed `preprocessor_config.json`. + * @param {ImageProcessorConfig} config The configuration object. + */ + constructor(config) { + super(); + this.image_mean = config.image_mean ?? config.mean; + this.image_std = config.image_std ?? config.std; + this.resample = config.resample ?? 2; + this.do_rescale = config.do_rescale ?? true; + this.rescale_factor = config.rescale_factor ?? 1 / 255; + this.do_normalize = config.do_normalize; + this.do_thumbnail = config.do_thumbnail; + this.size = config.size ?? config.image_size; + this.do_resize = config.do_resize ?? this.size !== void 0; + this.size_divisibility = config.size_divisibility ?? config.size_divisor; + this.do_center_crop = config.do_center_crop; + this.crop_size = config.crop_size; + this.do_convert_rgb = config.do_convert_rgb ?? true; + this.do_crop_margin = config.do_crop_margin; + this.pad_size = config.pad_size; + this.do_pad = config.do_pad; + this.min_pixels = config.min_pixels; + this.max_pixels = config.max_pixels; + if (this.do_pad && !this.pad_size && !this.size_divisibility && this.size && this.size.width !== void 0 && this.size.height !== void 0) { + this.pad_size = this.size; + } + this.do_flip_channel_order = config.do_flip_channel_order ?? false; + this.config = config; + } + /** + * Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any + * corresponding dimension of the specified size. + * @param {RawImage} image The image to be resized. + * @param {{height:number, width:number}} size The size `{"height": h, "width": w}` to resize the image to. + * @param {string | 0 | 1 | 2 | 3 | 4 | 5} [resample=2] The resampling filter to use. + * @returns {Promise} The resized image. + */ + async thumbnail(image, size, resample = 2) { + const input_height = image.height; + const input_width = image.width; + const output_height = size.height; + const output_width = size.width; + let height = Math.min(input_height, output_height); + let width = Math.min(input_width, output_width); + if (height === input_height && width === input_width) { + return image; + } + if (input_height > input_width) { + width = Math.floor(input_width * height / input_height); + } else if (input_width > input_height) { + height = Math.floor(input_height * width / input_width); + } + return await image.resize(width, height, { resample }); + } + /** + * Crops the margin of the image. Gray pixels are considered margin (i.e., pixels with a value below the threshold). + * @param {RawImage} image The image to be cropped. + * @param {number} gray_threshold Value below which pixels are considered to be gray. + * @returns {Promise} The cropped image. + */ + async crop_margin(image, gray_threshold = 200) { + const gray_image = image.clone().grayscale(); + const minValue = min2(gray_image.data)[0]; + const maxValue = max(gray_image.data)[0]; + const diff = maxValue - minValue; + if (diff === 0) { + return image; + } + const threshold = gray_threshold / 255; + let x_min = gray_image.width, y_min = gray_image.height, x_max = 0, y_max = 0; + const gray_image_data = gray_image.data; + for (let j2 = 0; j2 < gray_image.height; ++j2) { + const row = j2 * gray_image.width; + for (let i = 0; i < gray_image.width; ++i) { + if ((gray_image_data[row + i] - minValue) / diff < threshold) { + x_min = Math.min(x_min, i); + y_min = Math.min(y_min, j2); + x_max = Math.max(x_max, i); + y_max = Math.max(y_max, j2); } - return batch.map(x => this.decode(x, decode_args)); + } } - - /** - * Decodes a sequence of token IDs back to a string. - * - * @param {number[]|bigint[]|Tensor} token_ids List/Tensor of token IDs to decode. - * @param {Object} [decode_args={}] - * @param {boolean} [decode_args.skip_special_tokens=false] If true, special tokens are removed from the output string. - * @param {boolean} [decode_args.clean_up_tokenization_spaces=true] If true, spaces before punctuations and abbreviated forms are removed. - * - * @returns {string} The decoded string. - * @throws {Error} If `token_ids` is not a non-empty array of integers. - */ - decode( - token_ids, - decode_args = {}, - ) { - if (token_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) { - token_ids = prepareTensorForDecode(token_ids); - } - - if (!Array.isArray(token_ids) || token_ids.length === 0 || !(0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.isIntegralNumber)(token_ids[0])) { - throw Error("token_ids must be a non-empty array of integers."); - } - - return this.decode_single(token_ids, decode_args) + image = await image.crop([x_min, y_min, x_max, y_max]); + return image; + } + /** + * Pad the image by a certain amount. + * @param {Float32Array} pixelData The pixel data to pad. + * @param {number[]} imgDims The dimensions of the image (height, width, channels). + * @param {{width:number; height:number}|number|'square'} padSize The dimensions of the padded image. + * @param {Object} options The options for padding. + * @param {'constant'|'symmetric'} [options.mode='constant'] The type of padding to add. + * @param {boolean} [options.center=false] Whether to center the image. + * @param {number|number[]} [options.constant_values=0] The constant value to use for padding. + * @returns {[Float32Array, number[]]} The padded pixel data and image dimensions. + */ + pad_image(pixelData, imgDims, padSize, { mode = "constant", center = false, constant_values = 0 } = {}) { + const [imageHeight, imageWidth, imageChannels] = imgDims; + let paddedImageWidth, paddedImageHeight; + if (typeof padSize === "number") { + paddedImageWidth = padSize; + paddedImageHeight = padSize; + } else if (padSize === "square") { + paddedImageWidth = paddedImageHeight = Math.max(imageHeight, imageWidth); + } else { + paddedImageWidth = padSize.width; + paddedImageHeight = padSize.height; } - - /** - * Decode a single list of token ids to a string. - * @param {number[]|bigint[]} token_ids List of token ids to decode - * @param {Object} decode_args Optional arguments for decoding - * @param {boolean} [decode_args.skip_special_tokens=false] Whether to skip special tokens during decoding - * @param {boolean} [decode_args.clean_up_tokenization_spaces=null] Whether to clean up tokenization spaces during decoding. - * If null, the value is set to `this.decoder.cleanup` if it exists, falling back to `this.clean_up_tokenization_spaces` if it exists, falling back to `true`. - * @returns {string} The decoded string - */ - decode_single( - token_ids, - { - skip_special_tokens = false, - clean_up_tokenization_spaces = null, + if (paddedImageWidth !== imageWidth || paddedImageHeight !== imageHeight) { + const paddedPixelData = new Float32Array(paddedImageWidth * paddedImageHeight * imageChannels); + if (Array.isArray(constant_values)) { + for (let i = 0; i < paddedPixelData.length; ++i) { + paddedPixelData[i] = constant_values[i % imageChannels]; } - ) { - let tokens = this.model.convert_ids_to_tokens(token_ids); - if (skip_special_tokens) { - tokens = tokens.filter(x => !this.special_tokens.includes(x)); + } else if (constant_values !== 0) { + paddedPixelData.fill(constant_values); + } + const [left, top] = center ? [Math.floor((paddedImageWidth - imageWidth) / 2), Math.floor((paddedImageHeight - imageHeight) / 2)] : [0, 0]; + for (let i = 0; i < imageHeight; ++i) { + const a = (i + top) * paddedImageWidth; + const b = i * imageWidth; + for (let j2 = 0; j2 < imageWidth; ++j2) { + const c = (a + j2 + left) * imageChannels; + const d = (b + j2) * imageChannels; + for (let k = 0; k < imageChannels; ++k) { + paddedPixelData[c + k] = pixelData[d + k]; + } } - - // If `this.decoder` is null, we just join tokens with a space: - // https://github.com/huggingface/tokenizers/blob/8edec536a737cb04494b454805be16c020abb14f/tokenizers/src/tokenizer/mod.rs#L835 - /** @type {string} */ - let decoded = this.decoder ? this.decoder(tokens) : tokens.join(' '); - - // Slight hack, but prevents having to pass `skip_special_tokens` to - // each call to `decode`, which would lead to code duplication. - if (this.decoder && this.decoder.end_of_word_suffix) { - decoded = decoded.replaceAll(this.decoder.end_of_word_suffix, ' '); - if (skip_special_tokens) { - decoded = decoded.trim(); + } + if (mode === "symmetric") { + if (center) { + throw new Error("`center` padding is not supported when `mode` is set to `symmetric`."); + } + const h1 = imageHeight - 1; + const w1 = imageWidth - 1; + for (let i = 0; i < paddedImageHeight; ++i) { + const a = i * paddedImageWidth; + const b = calculateReflectOffset(i, h1) * imageWidth; + for (let j2 = 0; j2 < paddedImageWidth; ++j2) { + if (i < imageHeight && j2 < imageWidth) continue; + const c = (a + j2) * imageChannels; + const d = (b + calculateReflectOffset(j2, w1)) * imageChannels; + for (let k = 0; k < imageChannels; ++k) { + paddedPixelData[c + k] = pixelData[d + k]; } + } } - - if (clean_up_tokenization_spaces ?? this.clean_up_tokenization_spaces) { - decoded = clean_up_tokenization(decoded); - } - - return decoded; + } + pixelData = paddedPixelData; + imgDims = [paddedImageHeight, paddedImageWidth, imageChannels]; } - - /** - * Retrieve the chat template string used for tokenizing chat messages. This template is used - * internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat - * template for better generation tracking. - * - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.chat_template=null] - * A Jinja template or the name of a template to use for this conversion. - * It is usually not necessary to pass anything to this argument, - * as the model's template will be used by default. - * @param {Object[]} [options.tools=null] - * A list of tools (callable functions) that will be accessible to the model. If the template does not - * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, - * giving the name, description and argument types for the tool. See our - * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) - * for more information. - * @returns {string} The chat template string. - */ - get_chat_template({ - chat_template = null, - tools = null, - } = {}) { - - // First, handle the cases when the model has a dict of multiple templates - if (this.chat_template && typeof this.chat_template === 'object') { - const template_dict = this.chat_template; - - if (chat_template !== null && Object.hasOwn(template_dict, chat_template)) { - // The user can pass the name of a template to the chat template argument instead of an entire template - chat_template = template_dict[chat_template]; - } else if (chat_template === null) { - if (tools !== null && 'tool_use' in template_dict) { - chat_template = template_dict['tool_use']; - } else if ('default' in template_dict) { - chat_template = template_dict['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(template_dict).sort()}.` - ) - } - } - } else if (chat_template === null) { - // These are the cases when the model has a single template - // priority: `chat_template` argument > `tokenizer.chat_template` - if (this.chat_template) { - chat_template = this.chat_template; - } else { - throw Error( - "Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template " + - "argument was passed! For information about writing templates and setting the " + - "tokenizer.chat_template attribute, please see the documentation at " + - "https://huggingface.co/docs/transformers/main/en/chat_templating" - ) - } - } - return chat_template; + return [pixelData, imgDims]; + } + /** + * Rescale the image pixel values by `this.rescale_factor`. + * @param {Float32Array} pixelData The pixel data to rescale. + * @returns {void} + */ + rescale(pixelData) { + for (let i = 0; i < pixelData.length; ++i) { + pixelData[i] = this.rescale_factor * pixelData[i]; } - - /** - * Converts a list of message objects with `"role"` and `"content"` keys to a list of token - * ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to - * determine the format and control tokens to use when converting. - * - * See [here](https://huggingface.co/docs/transformers/chat_templating) for more information. - * - * **Example:** Applying a chat template to a conversation. - * - * ```javascript - * import { AutoTokenizer } from "@huggingface/transformers"; - * - * const tokenizer = await AutoTokenizer.from_pretrained("Xenova/mistral-tokenizer-v1"); - * - * const chat = [ - * { "role": "user", "content": "Hello, how are you?" }, - * { "role": "assistant", "content": "I'm doing great. How can I help you today?" }, - * { "role": "user", "content": "I'd like to show off how chat templating works!" }, - * ] - * - * const text = tokenizer.apply_chat_template(chat, { tokenize: false }); - * // "[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today? [INST] I'd like to show off how chat templating works! [/INST]" - * - * const input_ids = tokenizer.apply_chat_template(chat, { tokenize: true, return_tensor: false }); - * // [1, 733, 16289, 28793, 22557, 28725, 910, 460, 368, 28804, 733, 28748, 16289, 28793, 28737, 28742, 28719, 2548, 1598, 28723, 1602, 541, 315, 1316, 368, 3154, 28804, 2, 28705, 733, 16289, 28793, 315, 28742, 28715, 737, 298, 1347, 805, 910, 10706, 5752, 1077, 3791, 28808, 733, 28748, 16289, 28793] - * ``` - * - * @param {Message[]} conversation A list of message objects with `"role"` and `"content"` keys, - * representing the chat history so far. - * @param {Object} options An optional object containing the following properties: - * @param {string} [options.chat_template=null] A Jinja template to use for this conversion. If - * this is not passed, the model's chat template will be used instead. - * @param {Object[]} [options.tools=null] - * A list of tools (callable functions) that will be accessible to the model. If the template does not - * support function calling, this argument will have no effect. Each tool should be passed as a JSON Schema, - * giving the name, description and argument types for the tool. See our - * [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#automated-function-conversion-for-tool-use) - * for more information. - * @param {Record[]} [options.documents=null] - * A list of dicts representing documents that will be accessible to the model if it is performing RAG - * (retrieval-augmented generation). If the template does not support RAG, this argument will have no - * effect. We recommend that each document should be a dict containing "title" and "text" keys. Please - * see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG) - * for examples of passing documents with chat templates. - * @param {boolean} [options.add_generation_prompt=false] Whether to end the prompt with the token(s) that indicate - * the start of an assistant message. This is useful when you want to generate a response from the model. - * Note that this argument will be passed to the chat template, and so it must be supported in the - * template for this argument to have any effect. - * @param {boolean} [options.tokenize=true] Whether to tokenize the output. If false, the output will be a string. - * @param {boolean} [options.padding=false] Whether to pad sequences to the maximum length. Has no effect if tokenize is false. - * @param {boolean} [options.truncation=false] Whether to truncate sequences to the maximum length. Has no effect if tokenize is false. - * @param {number} [options.max_length=null] Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is false. - * If not specified, the tokenizer's `max_length` attribute will be used as a default. - * @param {boolean} [options.return_tensor=true] Whether to return the output as a Tensor or an Array. Has no effect if tokenize is false. - * @param {boolean} [options.return_dict=true] Whether to return a dictionary with named outputs. Has no effect if tokenize is false. - * @param {Object} [options.tokenizer_kwargs={}] Additional options to pass to the tokenizer. - * @returns {string | Tensor | number[]| number[][]|BatchEncoding} The tokenized output. - */ - apply_chat_template(conversation, { - tools = null, - documents = null, - chat_template = null, - add_generation_prompt = false, - tokenize = true, - padding = false, - truncation = false, - max_length = null, - return_tensor = true, - return_dict = false, - tokenizer_kwargs = {}, - ...kwargs - } = {}) { - - chat_template = this.get_chat_template({ chat_template, tools }); - - if (typeof chat_template !== 'string') { - throw Error(`chat_template must be a string, but got ${typeof chat_template}`); - } - - // Compilation function uses a cache to avoid recompiling the same template - let compiledTemplate = this._compiled_template_cache.get(chat_template); - if (compiledTemplate === undefined) { - compiledTemplate = new _huggingface_jinja__WEBPACK_IMPORTED_MODULE_6__.Template(chat_template); - this._compiled_template_cache.set(chat_template, compiledTemplate); - } - - const special_tokens_map = Object.create(null); - for (const key of SPECIAL_TOKEN_ATTRIBUTES) { - const value = this.getToken(key); - if (value) { - special_tokens_map[key] = value; - } + } + /** + * Find the target (width, height) dimension of the output image after + * resizing given the input image and the desired size. + * @param {RawImage} image The image to resize. + * @param {any} size The size to use for resizing the image. + * @returns {[number, number]} The target (width, height) dimension of the output image after resizing. + */ + get_resize_output_image_size(image, size) { + const [srcWidth, srcHeight] = image.size; + let shortest_edge; + let longest_edge; + if (this.do_thumbnail) { + const { height, width } = size; + shortest_edge = Math.min(height, width); + } else if (Number.isInteger(size)) { + shortest_edge = size; + longest_edge = this.config.max_size ?? shortest_edge; + } else if (size !== void 0) { + shortest_edge = size.shortest_edge; + longest_edge = size.longest_edge; + } + if (shortest_edge !== void 0 || longest_edge !== void 0) { + const shortResizeFactor = shortest_edge === void 0 ? 1 : Math.max(shortest_edge / srcWidth, shortest_edge / srcHeight); + const newWidth = srcWidth * shortResizeFactor; + const newHeight = srcHeight * shortResizeFactor; + const longResizeFactor = longest_edge === void 0 ? 1 : Math.min(longest_edge / newWidth, longest_edge / newHeight); + let finalWidth = Math.floor(Number((newWidth * longResizeFactor).toFixed(2))); + let finalHeight = Math.floor(Number((newHeight * longResizeFactor).toFixed(2))); + if (this.size_divisibility !== void 0) { + [finalWidth, finalHeight] = enforce_size_divisibility( + [finalWidth, finalHeight], + this.size_divisibility + ); + } + return [finalWidth, finalHeight]; + } else if (size !== void 0 && size.width !== void 0 && size.height !== void 0) { + let newWidth = size.width; + let newHeight = size.height; + if (this.config.keep_aspect_ratio && this.config.ensure_multiple_of) { + let scale_height = newHeight / srcHeight; + let scale_width = newWidth / srcWidth; + if (Math.abs(1 - scale_width) < Math.abs(1 - scale_height)) { + scale_height = scale_width; + } else { + scale_width = scale_height; } - - const rendered = compiledTemplate.render({ - messages: conversation, - add_generation_prompt, - tools, - documents, - ...special_tokens_map, - ...kwargs, - }); - - if (tokenize) { - const out = this._call(rendered, { - add_special_tokens: false, - padding, - truncation, - max_length, - return_tensor, - ...tokenizer_kwargs, - }); - return return_dict ? out : out.input_ids; + newHeight = constraint_to_multiple_of(scale_height * srcHeight, this.config.ensure_multiple_of); + newWidth = constraint_to_multiple_of(scale_width * srcWidth, this.config.ensure_multiple_of); + } + return [newWidth, newHeight]; + } else if (this.size_divisibility !== void 0) { + return enforce_size_divisibility([srcWidth, srcHeight], this.size_divisibility); + } else { + throw new Error( + `Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(size)}` + ); + } + } + /** + * Resizes the image. + * @param {RawImage} image The image to resize. + * @returns {Promise} The resized image. + */ + async resize(image) { + const [newWidth, newHeight] = this.get_resize_output_image_size(image, this.size); + return await image.resize(newWidth, newHeight, { + // @ts-expect-error TS2322 + resample: this.resample + }); + } + /** + * @typedef {Object} PreprocessedImage + * @property {HeightWidth} original_size The original size of the image. + * @property {HeightWidth} reshaped_input_size The reshaped input size of the image. + * @property {Tensor} pixel_values The pixel values of the preprocessed image. + */ + /** + * Preprocesses the given image. + * + * @param {RawImage} image The image to preprocess. + * @param {Object} overrides The overrides for the preprocessing options. + * @returns {Promise} The preprocessed image. + */ + async preprocess(image, { + do_normalize = null, + do_pad = null, + do_convert_rgb = null, + do_convert_grayscale = null, + do_flip_channel_order = null + } = {}) { + if (this.do_crop_margin) { + image = await this.crop_margin(image); + } + const [srcWidth, srcHeight] = image.size; + if (do_convert_rgb ?? this.do_convert_rgb) { + image = image.rgb(); + } else if (do_convert_grayscale) { + image = image.grayscale(); + } + if (this.do_resize) { + image = await this.resize(image); + } + if (this.do_thumbnail) { + image = await this.thumbnail(image, this.size, this.resample); + } + if (this.do_center_crop) { + let crop_width; + let crop_height; + if (Number.isInteger(this.crop_size)) { + crop_width = this.crop_size; + crop_height = this.crop_size; + } else { + crop_width = this.crop_size.width; + crop_height = this.crop_size.height; + } + image = await image.center_crop(crop_width, crop_height); + } + const reshaped_input_size = [image.height, image.width]; + let pixelData = Float32Array.from(image.data); + let imgDims = [image.height, image.width, image.channels]; + if (this.do_rescale) { + this.rescale(pixelData); + } + if (do_normalize ?? this.do_normalize) { + let image_mean = this.image_mean; + if (!Array.isArray(this.image_mean)) { + image_mean = new Array(image.channels).fill(image_mean); + } + let image_std = this.image_std; + if (!Array.isArray(this.image_std)) { + image_std = new Array(image.channels).fill(image_std); + } + if (image_mean.length !== image.channels || image_std.length !== image.channels) { + throw new Error( + `When set to arrays, the length of \`image_mean\` (${image_mean.length}) and \`image_std\` (${image_std.length}) must match the number of channels in the image (${image.channels}).` + ); + } + for (let i = 0; i < pixelData.length; i += image.channels) { + for (let j2 = 0; j2 < image.channels; ++j2) { + pixelData[i + j2] = (pixelData[i + j2] - image_mean[j2]) / image_std[j2]; } - - return rendered; + } } -} - -/** - * BertTokenizer is a class used to tokenize text for BERT models. - * @extends PreTrainedTokenizer - */ -class BertTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -/** - * Albert tokenizer - * @extends PreTrainedTokenizer - */ -class AlbertTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class MobileBertTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class SqueezeBertTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class DebertaTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class DebertaV2Tokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class HerbertTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class ConvBertTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class RoFormerTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} -class DistilBertTokenizer extends PreTrainedTokenizer { } -class CamembertTokenizer extends PreTrainedTokenizer { } -class XLMTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; - - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.') + if (do_pad ?? this.do_pad) { + if (this.pad_size) { + const padded = this.pad_image(pixelData, [image.height, image.width, image.channels], this.pad_size); + [pixelData, imgDims] = padded; + } else if (this.size_divisibility) { + const paddedWidth = Math.ceil(imgDims[1] / this.size_divisibility) * this.size_divisibility; + const paddedHeight = Math.ceil(imgDims[0] / this.size_divisibility) * this.size_divisibility; + [pixelData, imgDims] = this.pad_image(pixelData, imgDims, { width: paddedWidth, height: paddedHeight }); + } } -} -class ElectraTokenizer extends PreTrainedTokenizer { - return_token_type_ids = true; -} - -class T5Tokenizer extends PreTrainedTokenizer { } -class GPT2Tokenizer extends PreTrainedTokenizer { } -class BartTokenizer extends PreTrainedTokenizer { } -class MBartTokenizer extends PreTrainedTokenizer { - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - - this.languageRegex = /^[a-z]{2}_[A-Z]{2}$/; - this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x)); - this.lang_to_token = x => x; // Identity function + if (do_flip_channel_order ?? this.do_flip_channel_order) { + if (imgDims[2] !== 3) { + throw new Error("Flipping channel order is only supported for RGB images."); + } + for (let i = 0; i < pixelData.length; i += 3) { + const temp = pixelData[i]; + pixelData[i] = pixelData[i + 2]; + pixelData[i + 2] = temp; + } } - - /** - * Helper function to build translation inputs for an `MBartTokenizer`. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - */ - _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { - return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + const pixel_values = new Tensor3("float32", pixelData, imgDims).permute(2, 0, 1); + return { + original_size: [srcHeight, srcWidth], + reshaped_input_size, + pixel_values + }; + } + /** + * Preprocess one or more images and batch the result into `pixel_values`. + * @param {RawImage|RawImage[]} images The image or images to preprocess. + * @param {...any} args Additional arguments. + * @returns {Promise} An object containing the concatenated pixel values (and other metadata) of the preprocessed images. + */ + async _call(images, ...args) { + if (!Array.isArray(images)) { + images = [images]; } -} -class MBart50Tokenizer extends MBartTokenizer { } // NOTE: extends MBartTokenizer + const imageData = await Promise.all(images.map((x) => this.preprocess(x))); + const pixel_values = stack( + imageData.map((x) => x.pixel_values), + 0 + ); + return { + pixel_values, + // Original sizes of images + original_sizes: imageData.map((x) => x.original_size), + // Reshaped sizes of images, before padding or cropping + reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size) + }; + } + /** + * Instantiate one of the processor classes of the library from a pretrained model. + * + * The processor class to instantiate is selected based on the `image_processor_type` (or `feature_extractor_type`; legacy) + * property of the config object (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model id* of a pretrained processor hosted inside a model repo on huggingface.co. + * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing processor files, e.g., `./my_model_directory/`. + * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the processor. + * + * @returns {Promise} A new image processor instance. + */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await getModelJSON( + pretrained_model_name_or_path, + IMAGE_PROCESSOR_NAME, + true, + options + ); + return new this(preprocessorConfig); + } +}; -class RobertaTokenizer extends PreTrainedTokenizer { } +// src/models/image_processors.js +var image_processors_exports = {}; +__export(image_processors_exports, { + BeitFeatureExtractor: () => BeitFeatureExtractor, + BitImageProcessor: () => BitImageProcessor, + CHMv2ImageProcessor: () => CHMv2ImageProcessor, + CLIPFeatureExtractor: () => CLIPFeatureExtractor, + CLIPImageProcessor: () => CLIPImageProcessor, + ChineseCLIPFeatureExtractor: () => ChineseCLIPFeatureExtractor, + ConvNextFeatureExtractor: () => ConvNextFeatureExtractor, + ConvNextImageProcessor: () => ConvNextImageProcessor, + DINOv3ViTImageProcessor: () => DINOv3ViTImageProcessor, + DPTFeatureExtractor: () => DPTFeatureExtractor, + DPTImageProcessor: () => DPTImageProcessor, + DeiTFeatureExtractor: () => DeiTFeatureExtractor, + DeiTImageProcessor: () => DeiTImageProcessor, + DetrFeatureExtractor: () => DetrFeatureExtractor, + DetrImageProcessor: () => DetrImageProcessor, + DonutFeatureExtractor: () => DonutFeatureExtractor, + DonutImageProcessor: () => DonutImageProcessor, + EfficientNetImageProcessor: () => EfficientNetImageProcessor, + GLPNFeatureExtractor: () => GLPNFeatureExtractor, + Gemma3ImageProcessor: () => Gemma3ImageProcessor, + Gemma4ImageProcessor: () => Gemma4ImageProcessor, + Glm46VImageProcessor: () => Glm46VImageProcessor, + GroundingDinoImageProcessor: () => GroundingDinoImageProcessor, + Idefics3ImageProcessor: () => Idefics3ImageProcessor, + ImageFeatureExtractor: () => ImageProcessor, + ImageProcessor: () => ImageProcessor, + JinaCLIPImageProcessor: () => JinaCLIPImageProcessor, + Lfm2VlImageProcessor: () => Lfm2VlImageProcessor, + Lfm3VlImageProcessor: () => Lfm3VlImageProcessor, + LlavaOnevisionImageProcessor: () => LlavaOnevisionImageProcessor, + Mask2FormerImageProcessor: () => Mask2FormerImageProcessor, + MaskFormerFeatureExtractor: () => MaskFormerFeatureExtractor, + MaskFormerImageProcessor: () => MaskFormerImageProcessor, + MobileNetV1FeatureExtractor: () => MobileNetV1FeatureExtractor, + MobileNetV1ImageProcessor: () => MobileNetV1ImageProcessor, + MobileNetV2FeatureExtractor: () => MobileNetV2FeatureExtractor, + MobileNetV2ImageProcessor: () => MobileNetV2ImageProcessor, + MobileNetV3FeatureExtractor: () => MobileNetV3FeatureExtractor, + MobileNetV3ImageProcessor: () => MobileNetV3ImageProcessor, + MobileNetV4FeatureExtractor: () => MobileNetV4FeatureExtractor, + MobileNetV4ImageProcessor: () => MobileNetV4ImageProcessor, + MobileViTFeatureExtractor: () => MobileViTFeatureExtractor, + MobileViTImageProcessor: () => MobileViTImageProcessor, + NougatImageProcessor: () => NougatImageProcessor, + OwlViTFeatureExtractor: () => OwlViTFeatureExtractor, + OwlViTImageProcessor: () => OwlViTImageProcessor, + Owlv2ImageProcessor: () => Owlv2ImageProcessor, + Phi3VImageProcessor: () => Phi3VImageProcessor, + PixtralImageProcessor: () => PixtralImageProcessor, + PvtImageProcessor: () => PvtImageProcessor, + Qwen2VLImageProcessor: () => Qwen2VLImageProcessor, + RTDetrImageProcessor: () => RTDetrImageProcessor, + Sam2ImageProcessor: () => SamImageProcessor, + Sam3ImageProcessor: () => SamImageProcessor, + SamImageProcessor: () => SamImageProcessor, + SapiensFeatureExtractor: () => SapiensFeatureExtractor, + SapiensImageProcessor: () => SapiensImageProcessor, + SegformerFeatureExtractor: () => SegformerFeatureExtractor, + SegformerImageProcessor: () => SegformerImageProcessor, + SiglipImageProcessor: () => SiglipImageProcessor, + SmolVLMImageProcessor: () => Idefics3ImageProcessor, + Swin2SRImageProcessor: () => Swin2SRImageProcessor, + VLMImageProcessor: () => VLMImageProcessor, + ViTFeatureExtractor: () => ViTFeatureExtractor, + ViTImageProcessor: () => ViTImageProcessor, + VitMatteImageProcessor: () => VitMatteImageProcessor, + VitPoseImageProcessor: () => VitPoseImageProcessor, + YolosFeatureExtractor: () => YolosFeatureExtractor, + YolosImageProcessor: () => YolosImageProcessor +}); -class BloomTokenizer extends PreTrainedTokenizer { } +// src/models/beit/image_processing_beit.js +var BeitFeatureExtractor = class extends ImageProcessor { +}; -const SPIECE_UNDERLINE = "▁"; +// src/models/bit/image_processing_bit.js +var BitImageProcessor = class extends ImageProcessor { +}; -class LlamaTokenizer extends PreTrainedTokenizer { +// src/models/chinese_clip/image_processing_chinese_clip.js +var ChineseCLIPFeatureExtractor = class extends ImageProcessor { +}; - padding_side = 'left'; +// src/models/chmv2/image_processing_chmv2.js +var CHMv2ImageProcessor = class extends ImageProcessor { +}; - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); +// src/models/clip/image_processing_clip.js +var CLIPImageProcessor = class extends ImageProcessor { +}; +var CLIPFeatureExtractor = class extends CLIPImageProcessor { +}; - this.legacy = tokenizerConfig.legacy ?? true; - if (!this.legacy) { - // See https://github.com/huggingface/transformers/pull/24565 for more information - this.normalizer = null; - this.pre_tokenizer = new MetaspacePreTokenizer({ - replacement: SPIECE_UNDERLINE, - add_prefix_space: true, - prepend_scheme: "first", - }); - } +// src/models/convnext/image_processing_convnext.js +var ConvNextImageProcessor = class extends ImageProcessor { + constructor(config) { + super(config); + this.crop_pct = this.config.crop_pct ?? 224 / 256; + } + async resize(image) { + const shortest_edge = this.size?.shortest_edge; + if (shortest_edge === void 0) { + throw new Error(`Size dictionary must contain 'shortest_edge' key.`); + } + if (shortest_edge < 384) { + const resize_shortest_edge = Math.floor(shortest_edge / this.crop_pct); + const [newWidth, newHeight] = this.get_resize_output_image_size(image, { + shortest_edge: resize_shortest_edge + }); + image = await image.resize(newWidth, newHeight, { + resample: this.resample + }); + image = await image.center_crop(shortest_edge, shortest_edge); + } else { + image = await image.resize(shortest_edge, shortest_edge, { + resample: this.resample + }); } + return image; + } +}; +var ConvNextFeatureExtractor = class extends ConvNextImageProcessor { +}; - /** - * Helper function to handle legacy encoding of SPM tokenizers. - * Adapted from https://github.com/huggingface/transformers/blob/e6dcf8abd6f65bb4b6dfc1831b20d9ba49ce00e2/src/transformers/models/t5/tokenization_t5.py#L374-L387 - * @param {string} text The text to encode. - * @returns {string[]} The encoded tokens. - */ - _encode_text(text) { - if (text === null) return null; +// src/models/deit/image_processing_deit.js +var DeiTImageProcessor = class extends ImageProcessor { +}; +var DeiTFeatureExtractor = class extends DeiTImageProcessor { +}; - if (this.legacy || text.length === 0) { - return super._encode_text(text); - } +// src/models/detr/image_processing_detr.js +var DetrImageProcessor = class extends ImageProcessor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images) { + const result = await super._call(images); + const maskSize = [result.pixel_values.dims[0], 64, 64]; + const pixel_mask = full(maskSize, 1n); + return { ...result, pixel_mask }; + } + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } + /** @type {typeof post_process_panoptic_segmentation} */ + post_process_panoptic_segmentation(...args) { + return post_process_panoptic_segmentation(...args); + } + /** @type {typeof post_process_instance_segmentation} */ + post_process_instance_segmentation(...args) { + return post_process_instance_segmentation(...args); + } +}; +var DetrFeatureExtractor = class extends DetrImageProcessor { +}; - let tokens = super._encode_text(SPIECE_UNDERLINE + text.replaceAll(SPIECE_UNDERLINE, " ")); - if (tokens.length > 1 && tokens[0] === SPIECE_UNDERLINE && this.special_tokens.includes(tokens[1])) { - tokens = tokens.slice(1); - } - return tokens; - } -} -class CodeLlamaTokenizer extends PreTrainedTokenizer { } +// src/models/dinov3_vit/image_processing_dinov3_vit.js +var DINOv3ViTImageProcessor = class extends ImageProcessor { +}; + +// src/models/donut/image_processing_donut.js +var DonutImageProcessor = class extends ImageProcessor { + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageHeight, imageWidth, imageChannels] = imgDims; + let image_mean = this.image_mean; + if (!Array.isArray(this.image_mean)) { + image_mean = new Array(imageChannels).fill(image_mean); + } + let image_std = this.image_std; + if (!Array.isArray(image_std)) { + image_std = new Array(imageChannels).fill(image_mean); + } + const constant_values = image_mean.map((x, i) => -x / image_std[i]); + return super.pad_image(pixelData, imgDims, padSize, { + center: true, + // Since normalization is done after padding, we need to use certain constant values to ensure the same behaviour is observed. + // For more information, see https://github.com/huggingface/transformers/blob/main/src/transformers/models/donut/image_processing_donut.py#L433-L451 + constant_values, + ...options + }); + } +}; +var DonutFeatureExtractor = class extends DonutImageProcessor { +}; -class XLMRobertaTokenizer extends PreTrainedTokenizer { } -class MPNetTokenizer extends PreTrainedTokenizer { } +// src/models/dpt/image_processing_dpt.js +var DPTImageProcessor = class extends ImageProcessor { +}; +var DPTFeatureExtractor = class extends DPTImageProcessor { +}; -class FalconTokenizer extends PreTrainedTokenizer { } +// src/models/efficientnet/image_processing_efficientnet.js +var EfficientNetImageProcessor = class extends ImageProcessor { + constructor(config) { + super(config); + this.include_top = this.config.include_top ?? true; + if (this.include_top) { + this.image_std = this.image_std.map((x) => x * x); + } + } +}; -class GPTNeoXTokenizer extends PreTrainedTokenizer { } +// src/models/gemma3/image_processing_gemma3.js +var Gemma3ImageProcessor = class extends ImageProcessor { +}; -class EsmTokenizer extends PreTrainedTokenizer { } +// src/models/qwen2_vl/image_processing_qwen2_vl.js +var Qwen2VLImageProcessor = class extends ImageProcessor { + constructor(config) { + super(config); + this.min_pixels = config.min_pixels ?? config.size?.shortest_edge; + this.max_pixels = config.max_pixels ?? config.size?.longest_edge; + this.patch_size = config.patch_size; + this.merge_size = config.merge_size; + } + /** @type {ImageProcessor['get_resize_output_image_size']} */ + get_resize_output_image_size(image, size) { + const factor = this.patch_size * this.merge_size; + return smart_resize(image.height, image.width, factor, this.min_pixels, this.max_pixels); + } + async _call(images, ...args) { + const { pixel_values, original_sizes, reshaped_input_sizes } = await super._call(images, ...args); + let patches = pixel_values; + const { temporal_patch_size, merge_size, patch_size } = this.config; + if (patches.dims[0] === 1) { + patches = cat( + Array.from({ length: temporal_patch_size }, () => patches), + 0 + ); + } + const grid_t = patches.dims[0] / temporal_patch_size; + const channel = patches.dims[1]; + const grid_h = Math.floor(patches.dims[2] / patch_size); + const grid_w = Math.floor(patches.dims[3] / patch_size); + const flatten_patches = patches.view( + grid_t, + temporal_patch_size, + channel, + Math.floor(grid_h / merge_size), + merge_size, + patch_size, + Math.floor(grid_w / merge_size), + merge_size, + patch_size + ).permute(0, 3, 6, 4, 7, 2, 1, 5, 8).view(grid_t * grid_h * grid_w, channel * temporal_patch_size * patch_size * patch_size); + const image_grid_thw = new Tensor3("int64", [grid_t, grid_h, grid_w], [1, 3]); + return { + pixel_values: flatten_patches, + image_grid_thw, + original_sizes, + reshaped_input_sizes + }; + } +}; -class Qwen2Tokenizer extends PreTrainedTokenizer { } +// src/models/glm46v/image_processing_glm46v.js +var Glm46VImageProcessor = class extends Qwen2VLImageProcessor { + /** @type {Qwen2VLImageProcessor['get_resize_output_image_size']} */ + get_resize_output_image_size(image, size) { + const factor = this.patch_size * this.merge_size; + const temporal_factor = this.config.temporal_patch_size ?? 2; + return smart_resize(image.height, image.width, factor, this.min_pixels, this.max_pixels, temporal_factor); + } +}; -class GemmaTokenizer extends PreTrainedTokenizer { } +// src/models/glpn/image_processing_glpn.js +var GLPNFeatureExtractor = class extends ImageProcessor { +}; -class Grok1Tokenizer extends PreTrainedTokenizer { } +// src/models/grounding_dino/image_processing_grounding_dino.js +var GroundingDinoImageProcessor = class extends ImageProcessor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {import('../../utils/image.js').RawImage[]} images The image(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images) { + const result = await super._call(images); + const dims = result.pixel_values.dims; + const pixel_mask = ones([dims[0], dims[2], dims[3]]); + return { ...result, pixel_mask }; + } +}; -/** - * Helper function to build translation inputs for an `NllbTokenizer` or `M2M100Tokenizer`. - * @param {PreTrainedTokenizer} self The tokenizer instance. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - * @private - */ -function _build_translation_inputs(self, raw_inputs, tokenizer_options, generate_kwargs) { - if (!('language_codes' in self) || !Array.isArray(self.language_codes)) { - throw new Error('Tokenizer must have `language_codes` attribute set and it should be an array of language ids.') - } - if (!('languageRegex' in self) || !(self.languageRegex instanceof RegExp)) { - throw new Error('Tokenizer must have `languageRegex` attribute set and it should be a regular expression.') - } - if (!('lang_to_token' in self) || typeof self.lang_to_token !== 'function') { - throw new Error('Tokenizer must have `lang_to_token` attribute set and it should be a function.') +// src/models/idefics3/image_processing_idefics3.js +var Idefics3ImageProcessor = class extends ImageProcessor { + constructor(config) { + super(config); + this.do_image_splitting = config.do_image_splitting ?? true; + this.max_image_size = config.max_image_size; + } + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + * @typedef {import('../../utils/tensor.js').Tensor} Tensor + */ + /** + * Calculate size to resize images to, to be multiples of `vision_encoder_max_size` while preserving the aspect ratio. + * @param {Tensor} pixel_values Tensor of the image to resize. + * @param {number} vision_encoder_max_size Maximum size of the output image. If the image is larger than this size, + * it will be split into patches of this size, and the original image will be concatenated with the patches, resized to max_size. + */ + get_resize_for_vision_encoder(pixel_values, vision_encoder_max_size) { + let [height, width] = pixel_values.dims.slice(-2); + const aspect_ratio = width / height; + if (width >= height) { + width = Math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size; + height = Math.floor(width / aspect_ratio); + height = Math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size; + } else { + height = Math.ceil(height / vision_encoder_max_size) * vision_encoder_max_size; + width = Math.floor(height * aspect_ratio); + width = Math.ceil(width / vision_encoder_max_size) * vision_encoder_max_size; } - const src_lang_token = generate_kwargs.src_lang; - const tgt_lang_token = generate_kwargs.tgt_lang; - - // Check that the target language is valid: - if (!self.language_codes.includes(tgt_lang_token)) { - throw new Error(`Target language code "${tgt_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`); + return { height, width }; + } + /** @param {RawImage|RawImage[]|RawImage[][]} images */ + async _call(images, { do_image_splitting = null, return_row_col_info = false } = {}) { + let batched_2d_images; + if (!Array.isArray(images)) { + batched_2d_images = [[images]]; + } else { + if (images.length === 0 || !images[0]) { + throw new Error("No images provided."); + } + if (!Array.isArray(images[0])) { + batched_2d_images = [ + /** @type {RawImage[]} */ + images + ]; + } else { + batched_2d_images = /** @type {RawImage[][]} */ + images; + } } - - // Allow `src_lang` to be optional. If not set, we'll use the tokenizer's default. - if (src_lang_token !== undefined) { - // Check that the source language is valid: - if (!self.language_codes.includes(src_lang_token)) { - throw new Error(`Source language code "${src_lang_token}" is not valid. Must be one of: {${self.language_codes.join(', ')}}`); + let all_pixel_values = []; + let images_list_rows = []; + let images_list_cols = []; + const original_sizes = []; + const reshaped_input_sizes = []; + for (const image_batch of batched_2d_images) { + let images_list = await Promise.all(image_batch.map((x) => this.preprocess(x))); + original_sizes.push(...images_list.map((x) => x.original_size)); + reshaped_input_sizes.push(...images_list.map((x) => x.reshaped_input_size)); + images_list.forEach((x) => x.pixel_values.unsqueeze_(0)); + const { longest_edge } = this.max_image_size; + let images_tensor; + if (do_image_splitting ?? this.do_image_splitting) { + let image_rows = new Array(images_list.length); + let image_cols = new Array(images_list.length); + images_tensor = await Promise.all( + images_list.map(async (x, i) => { + const new_size = this.get_resize_for_vision_encoder(x.pixel_values, longest_edge); + const resized = await interpolate_4d(x.pixel_values, { + size: [new_size.height, new_size.width] + }); + const { frames, num_splits_h, num_splits_w } = await this.split_image( + resized, + this.max_image_size + ); + image_rows[i] = num_splits_h; + image_cols[i] = num_splits_w; + return cat(frames, 0); + }) + ); + images_list_rows.push(image_rows); + images_list_cols.push(image_cols); + } else { + const size = [longest_edge, longest_edge]; + images_tensor = await Promise.all(images_list.map((x) => interpolate_4d(x.pixel_values, { size }))); + images_list_rows.push(new Array(images_list.length).fill(0)); + images_list_cols.push(new Array(images_list.length).fill(0)); + } + all_pixel_values.push(cat(images_tensor, 0)); + } + const batch_size = all_pixel_values.length; + const [n, c, h, w] = all_pixel_values[0].dims; + let pixel_values; + let pixel_attention_mask; + if (batch_size === 1) { + pixel_values = all_pixel_values[0].unsqueeze_(0); + pixel_attention_mask = full([batch_size, n, h, w], true); + } else { + const max_num_patches = Math.max(...all_pixel_values.map((x) => x.dims.at(0))); + pixel_attention_mask = full([batch_size, max_num_patches, h, w], true); + const pixel_attention_mask_data = pixel_attention_mask.data; + const pixel_attention_mask_stride = max_num_patches * h * w; + for (let i = 0; i < batch_size; ++i) { + const num_patches = all_pixel_values[i].dims[0]; + if (num_patches < max_num_patches) { + all_pixel_values[i] = cat( + [all_pixel_values[i], full([max_num_patches - num_patches, c, h, w], 0)], + 0 + ); + const start_offset = i * pixel_attention_mask_stride + num_patches * h * w; + const end_offset = (i + 1) * pixel_attention_mask_stride; + pixel_attention_mask_data.fill(false, start_offset, end_offset); } - - // In the same way as the Python library, we override the post-processor - // to force the source language to be first: - for (const item of self.post_processor.config.single) { - if ('SpecialToken' in item && self.languageRegex.test(item.SpecialToken.id)) { - item.SpecialToken.id = self.lang_to_token(src_lang_token); - break; - } + } + pixel_values = stack(all_pixel_values, 0); + } + return { + pixel_values, + pixel_attention_mask, + original_sizes, + reshaped_input_sizes, + ...return_row_col_info ? { rows: images_list_rows, cols: images_list_cols } : {} + }; + } + async split_image(pixel_values, { longest_edge }) { + const max_height = longest_edge; + const max_width = longest_edge; + const frames = []; + const [height, width] = pixel_values.dims.slice(-2); + let num_splits_h = 0, num_splits_w = 0; + if (height > max_height || width > max_width) { + num_splits_h = Math.ceil(height / max_height); + num_splits_w = Math.ceil(width / max_width); + const optimal_height = Math.ceil(height / num_splits_h); + const optimal_width = Math.ceil(width / num_splits_w); + for (let r = 0; r < num_splits_h; ++r) { + for (let c = 0; c < num_splits_w; ++c) { + let start_x, start_y, end_x, end_y; + if (r === num_splits_h - 1) { + start_y = height - optimal_height; + end_y = height; + } else { + start_y = r * optimal_height; + end_y = (r + 1) * optimal_height; + } + if (c === num_splits_w - 1) { + start_x = width - optimal_width; + end_x = width; + } else { + start_x = c * optimal_width; + end_x = (c + 1) * optimal_width; + } + const starts = [start_y, start_x]; + const ends = [end_y, end_x]; + const patch = await slice2(pixel_values, starts, ends, [2, 3]); + frames.push(patch); } - // TODO: Do the same for pair? + } + const global_image_height = max_height; + const global_image_width = max_width; + if (height !== global_image_height || width !== global_image_width) { + pixel_values = await interpolate_4d(pixel_values, { + size: [global_image_height, global_image_width] + }); + } } + frames.push(pixel_values); + return { frames, num_splits_h, num_splits_w }; + } +}; - // Override the `forced_bos_token_id` to force the correct language - generate_kwargs.forced_bos_token_id = self.model.convert_tokens_to_ids([self.lang_to_token(tgt_lang_token)])[0]; - - return self._call(raw_inputs, tokenizer_options); -} - -/** - * The NllbTokenizer class is used to tokenize text for NLLB ("No Language Left Behind") models. - * - * No Language Left Behind (NLLB) is a first-of-its-kind, AI breakthrough project - * that open-sources models capable of delivering high-quality translations directly - * between any pair of 200+ languages — including low-resource languages like Asturian, - * Luganda, Urdu and more. It aims to help people communicate with anyone, anywhere, - * regardless of their language preferences. For more information, check out their - * [paper](https://huggingface.co/papers/2207.04672). - * - * For a list of supported languages (along with their language codes), - * @see {@link https://github.com/facebookresearch/flores/blob/main/flores200/README.md#languages-in-flores-200} - */ -class NllbTokenizer extends PreTrainedTokenizer { +// src/models/janus/image_processing_janus.js +var VLMImageProcessor = class extends ImageProcessor { + constructor(config) { + super({ + do_pad: true, + pad_size: { + width: config.image_size, + height: config.image_size + }, + ...config + }); + this.constant_values = this.config.background_color.map((x) => x * this.rescale_factor); + } + pad_image(pixelData, imgDims, padSize, options) { + return super.pad_image(pixelData, imgDims, padSize, { + constant_values: this.constant_values, + center: true, + ...options + }); + } +}; - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); +// src/models/jina_clip/image_processing_jina_clip.js +var JinaCLIPImageProcessor = class extends ImageProcessor { + constructor(config) { + const { resize_mode, fill_color, interpolation, size, ...other } = config; + const new_size = resize_mode === "squash" ? { width: size, height: size } : resize_mode === "shortest" ? { shortest_edge: size } : { longest_edge: size }; + const resample = interpolation === "bicubic" ? 3 : 2; + super({ + ...other, + size: new_size, + resample, + do_center_crop: true, + crop_size: size, + do_normalize: true + }); + } +}; - this.languageRegex = /^[a-z]{3}_[A-Z][a-z]{3}$/; - this.language_codes = this.special_tokens.filter(x => this.languageRegex.test(x)); - this.lang_to_token = x => x; // Identity function +// src/models/lfm2_vl/image_processing_lfm2_vl.js +function round_by_factor(number, factor) { + return Math.round(number / factor) * factor; +} +function find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size) { + let best_ratio_diff = Infinity; + let best_ratio = [1, 1]; + const area = width * height; + for (const ratio of target_ratios) { + const ratio_diff = Math.abs(aspect_ratio - ratio[0] / ratio[1]); + if (ratio_diff < best_ratio_diff) { + best_ratio_diff = ratio_diff; + best_ratio = ratio; + } else if (ratio_diff === best_ratio_diff && area > 0.5 * image_size * image_size * ratio[0] * ratio[1]) { + best_ratio = ratio; } - - /** - * Helper function to build translation inputs for an `NllbTokenizer`. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - */ - _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { - return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } + return best_ratio; +} +function get_target_ratios(min_tiles, max_tiles) { + const ratios = []; + const seen = /* @__PURE__ */ new Set(); + for (let n = min_tiles; n <= max_tiles; ++n) { + for (let w = 1; w <= n; ++w) { + for (let h = 1; h <= n; ++h) { + const product2 = w * h; + if (product2 >= min_tiles && product2 <= max_tiles) { + const key = w << 16 | h; + if (!seen.has(key)) { + seen.add(key); + ratios.push([w, h]); + } + } + } } + } + return ratios.sort((a, b) => a[0] * a[1] - b[0] * b[1]); } - -/** - * The M2M100Tokenizer class is used to tokenize text for M2M100 ("Many-to-Many") models. - * - * M2M100 is a multilingual encoder-decoder (seq-to-seq) model trained for Many-to-Many - * multilingual translation. It was introduced in this [paper](https://huggingface.co/papers/2010.11125) - * and first released in [this](https://github.com/pytorch/fairseq/tree/master/examples/m2m_100) repository. - * - * For a list of supported languages (along with their language codes), - * @see {@link https://huggingface.co/facebook/m2m100_418M#languages-covered} - */ -class M2M100Tokenizer extends PreTrainedTokenizer { - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - - this.languageRegex = /^__[a-z]{2,3}__$/; - this.language_codes = this.special_tokens - .filter(x => this.languageRegex.test(x)) - .map(x => x.slice(2, -2)); - this.lang_to_token = x => `__${x}__`; +function convert_image_to_patches(images, patch_size) { + const [B, C, H, W] = images.dims; + const ph = Math.floor(H / patch_size), pw = Math.floor(W / patch_size); + const patch_dim = patch_size * patch_size * C; + const data = ( + /** @type {Float32Array} */ + images.data + ); + const result = new Float32Array(B * ph * pw * patch_dim); + const ch_stride = H * W; + for (let b = 0; b < B; ++b) { + const b_src = b * C * ch_stride; + const b_dst = b * ph * pw * patch_dim; + for (let py = 0; py < ph; ++py) { + for (let px = 0; px < pw; ++px) { + let off = b_dst + (py * pw + px) * patch_dim; + for (let dy = 0; dy < patch_size; ++dy) { + const row = (py * patch_size + dy) * W + px * patch_size; + for (let dx = 0; dx < patch_size; ++dx) { + const pixel = row + dx; + for (let c = 0; c < C; ++c) { + result[off++] = data[b_src + c * ch_stride + pixel]; + } + } + } + } } - - /** - * Helper function to build translation inputs for an `M2M100Tokenizer`. - * @param {string|string[]} raw_inputs The text to tokenize. - * @param {Object} tokenizer_options Options to be sent to the tokenizer - * @param {Object} generate_kwargs Generation options. - * @returns {Object} Object to be passed to the model. - */ - _build_translation_inputs(raw_inputs, tokenizer_options, generate_kwargs) { - return _build_translation_inputs(this, raw_inputs, tokenizer_options, generate_kwargs); + } + return new Tensor3("float32", result, [B, ph * pw, patch_dim]); +} +function pad_along_first_dim(patches, target_length) { + const [, len2, dim] = patches.dims; + const mask_data = new BigInt64Array(target_length); + mask_data.fill(1n, 0, len2); + let padded = patches; + if (len2 < target_length) { + const padded_data = new Float32Array(target_length * dim); + padded_data.set( + /** @type {Float32Array} */ + patches.data + ); + padded = new Tensor3("float32", padded_data, [1, target_length, dim]); + } + return { padded, mask: new Tensor3("int64", mask_data, [target_length]) }; +} +var Lfm2VlImageProcessor = class extends ImageProcessor { + constructor(config) { + super(config); + this.downsample_factor = config.downsample_factor ?? 2; + this.do_image_splitting = config.do_image_splitting ?? true; + this.min_tiles = config.min_tiles ?? 2; + this.max_tiles = config.max_tiles ?? 10; + this.use_thumbnail = config.use_thumbnail ?? true; + this.min_image_tokens = config.min_image_tokens ?? 64; + this.max_image_tokens = config.max_image_tokens ?? 256; + this.encoder_patch_size = config.encoder_patch_size ?? config.patch_size ?? 16; + this.tile_size = config.tile_size ?? 512; + this.max_pixels_tolerance = config.max_pixels_tolerance ?? 2; + this.return_row_col_info = config.return_row_col_info ?? false; + const max_thumbnail_patches = this.max_image_tokens * this.downsample_factor ** 2; + const tile_size_patches = this.do_image_splitting ? (this.tile_size / this.encoder_patch_size) ** 2 : 0; + this.max_num_patches = Math.max(max_thumbnail_patches, tile_size_patches); + } + /** + * Check if the image is too large to be processed as a single tile. + * @param {number} height + * @param {number} width + * @returns {boolean} + */ + _is_image_too_large(height, width) { + const total_factor = this.encoder_patch_size * this.downsample_factor; + const h_bar = Math.max(this.encoder_patch_size, round_by_factor(height, total_factor)); + const w_bar = Math.max(this.encoder_patch_size, round_by_factor(width, total_factor)); + return h_bar * w_bar > this.max_image_tokens * (this.encoder_patch_size * this.downsample_factor) ** 2 * this.max_pixels_tolerance; + } + /** + * Get the grid layout for tiling a large image. + * @param {number} height + * @param {number} width + * @returns {{ grid_width: number, grid_height: number, target_width: number, target_height: number }} + */ + _get_grid_layout(height, width) { + const target_ratios = get_target_ratios(this.min_tiles, this.max_tiles); + const [grid_width, grid_height] = find_closest_aspect_ratio( + width / height, + target_ratios, + width, + height, + this.tile_size + ); + return { + grid_width, + grid_height, + target_width: this.tile_size * grid_width, + target_height: this.tile_size * grid_height + }; + } + /** @param {RawImage|RawImage[]|RawImage[][]} images */ + // @ts-expect-error + async _call(images, { return_row_col_info = null } = {}) { + let batched_images; + if (!Array.isArray(images)) { + batched_images = [[images]]; + } else if (!Array.isArray(images[0])) { + batched_images = [ + /** @type {RawImage[]} */ + images + ]; + } else { + batched_images = /** @type {RawImage[][]} */ + images; + } + const all_pixel_values = []; + const all_pixel_masks = []; + const all_spatial_shapes = []; + const all_rows = []; + const all_cols = []; + const all_image_sizes = []; + for (const image_batch of batched_images) { + const preprocessed = await Promise.all(image_batch.map((x) => this.preprocess(x, { do_pad: false }))); + for (const { pixel_values } of preprocessed) { + const [, height, width] = pixel_values.dims; + const img = pixel_values.unsqueeze_(0); + const total_factor = this.encoder_patch_size * this.downsample_factor; + const f2 = total_factor ** 2; + const [new_width, new_height] = smart_resize( + Math.max(total_factor, height), + Math.max(total_factor, width), + total_factor, + this.min_image_tokens * f2, + this.max_image_tokens * f2 + ).map((x) => Math.max(total_factor, x)); + let tiles; + let num_rows = 1, num_cols = 1; + const is_large = this._is_image_too_large(height, width); + const do_splitting = this.do_image_splitting && !(this.min_tiles === 1 && this.max_tiles === 1); + if (is_large && do_splitting) { + const { grid_width, grid_height, target_width, target_height } = this._get_grid_layout( + height, + width + ); + num_rows = grid_height; + num_cols = grid_width; + const resized = await interpolate_4d(img, { + size: [target_height, target_width] + }); + tiles = []; + for (let r = 0; r < grid_height; ++r) { + for (let c = 0; c < grid_width; ++c) { + const y = r * this.tile_size; + const x = c * this.tile_size; + tiles.push(resized.slice(null, null, [y, y + this.tile_size], [x, x + this.tile_size])); + } + } + if (this.use_thumbnail && grid_width * grid_height !== 1) { + tiles.push(await interpolate_4d(img, { size: [new_height, new_width] })); + } + } else { + tiles = [await interpolate_4d(img, { size: [new_height, new_width] })]; + } + for (const tile of tiles) { + const [, , th, tw] = tile.dims; + const patches = convert_image_to_patches(tile, this.encoder_patch_size); + const { padded, mask } = pad_along_first_dim(patches, this.max_num_patches); + all_pixel_values.push(padded); + all_pixel_masks.push(mask); + all_spatial_shapes.push([ + Math.floor(th / this.encoder_patch_size), + Math.floor(tw / this.encoder_patch_size) + ]); + } + all_rows.push(num_rows); + all_cols.push(num_cols); + all_image_sizes.push([new_height, new_width]); + } } -} - -/** - * WhisperTokenizer tokenizer - * @extends PreTrainedTokenizer - */ -class WhisperTokenizer extends PreTrainedTokenizer { - - get timestamp_begin() { - return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0] + 1; + const result = { + pixel_values: cat(all_pixel_values, 0), + pixel_attention_mask: stack(all_pixel_masks, 0), + spatial_shapes: new Tensor3("int64", BigInt64Array.from(all_spatial_shapes.flat(), BigInt), [ + all_spatial_shapes.length, + 2 + ]) + }; + if (return_row_col_info ?? this.return_row_col_info) { + result.image_rows = all_rows; + result.image_cols = all_cols; + result.image_sizes = all_image_sizes; } + return result; + } +}; - /** - * Decodes automatic speech recognition (ASR) sequences. - * @param {Array<{tokens: bigint[], token_timestamps?: number[], stride: number[]}>} sequences The sequences to decode. - * @param {Object} options The options to use for decoding. - * @returns {Array, text: string}>}>} The decoded sequences. - */ - _decode_asr(sequences, { - return_timestamps = false, - return_language = false, - time_precision = null, - force_full_sequences = true - } = {}) { - // Set force_full_sequences=false if you want streaming - // TODO add support for `return_language` - - // Internal method meant to only be used by asr pipeline. - // Handles all the little quirks specific to whisper to handle - // the various options not allowed in other seq2seq models - - // =========== Overview ============ - // - iterate over all outputs - // - all tokens within output - // - Each token can be - // - language token - // - special token - // - timestamp token - // - text token - // - We accumulate the text tokens. - // - We split on end timestamps - // - Lots of complexity comes from stride and timestamps - - if (time_precision === null) { - throw Error("Must specify time_precision") - } - let last_language = null; - - const returnWordTimestamps = return_timestamps === "word"; - - function new_chunk() { - return { "language": last_language, "timestamp": [null, null], "text": "" }; - } - - // Welcome to the state machine! - const chunks = []; - let chunk = new_chunk(); - let time_offset = 0.0; - const timestamp_begin = this.timestamp_begin; - // Whisper timestamp tokens start from 0.00 and go to timestamp 30.00 in 0.02 increments. - // We can calculate the last time stamp token as timestamp_begin plus the number of tokens - // tokens from 0.00 to 30.00 which is 1500. - const total_timestamp_tokens = 1500; // (30.00 - 0.00) / 0.02 - const timestamp_end = timestamp_begin + total_timestamp_tokens; - - let previous_tokens = []; - let previous_token_timestamps = []; - - let skip = false; - let right_stride_start = null; - - - const all_special_ids = new Set(this.all_special_ids); - - for (const output of sequences) { - // NOTE: python version has batches, so it uses [0] - const token_ids = output.tokens; - const token_timestamps = returnWordTimestamps ? output.token_timestamps : null; - - // These keep track of timestamps within strides, which need - // to be skipped and resolve all tokens in a single chunk. - let last_timestamp = null; - let first_timestamp = timestamp_begin; - - if ("stride" in output) { - const [chunk_len, stride_left, stride_right] = output.stride; - - // Offset the timings to account for the other `model_outputs`. - time_offset -= stride_left; - right_stride_start = chunk_len - stride_right; - - // Keeping track of timestamps within strides - // We're going to NOT split on those, and delay until we're - // out of BOTH stride. Otherwise lots of issues occur and - // corner cases - if (stride_left) { - first_timestamp = stride_left / time_precision + timestamp_begin; - } - - if (stride_right) { - for (let i = token_ids.length - 1; i >= 0; --i) { - const token = Number(token_ids[i]); - if (token >= timestamp_begin) { - // There can be several token in the right stride - // But the last one is ALWAYS going to be skipped - if (last_timestamp !== null && (token - timestamp_begin) * time_precision < right_stride_start) { - break; - } - last_timestamp = token; - } - } - } - } +// src/models/lfm3_vl/image_processing_lfm3_vl.js +var Lfm3VlImageProcessor = class extends Qwen2VLImageProcessor { + async _call(images, ...args) { + if (!Array.isArray(images)) images = [images]; + const inputs = await Promise.all(images.map((image) => super._call(image, ...args))); + return { + pixel_values: cat( + inputs.map((x) => x.pixel_values), + 0 + ), + image_grid_thw: cat( + inputs.map((x) => x.image_grid_thw), + 0 + ), + original_sizes: inputs.flatMap((x) => x.original_sizes), + reshaped_input_sizes: inputs.flatMap((x) => x.reshaped_input_sizes) + }; + } +}; - let current_tokens = []; - let current_token_timestamps = []; - - // - all tokens within output - for (let i = 0; i < token_ids.length; ++i) { - const token = Number(token_ids[i]); - // 4 possible states for each token - // - 1/ Language code - // - 2/ all other special tokens (which we ignore) - // - 3/ Timestamp - // - 4/ Regular text - - if (all_special_ids.has(token)) { - const text = this.decode([token]); - const language = _models_whisper_common_whisper_js__WEBPACK_IMPORTED_MODULE_7__.WHISPER_LANGUAGE_MAPPING.get(text.slice(2, -2)); - - if (language !== undefined) { - // 1/ Indeed some language - // TODO Handle when language is different from the previous - // one, and we cannot use timestamped tokens to create chunks - if (last_language !== null && language !== last_language && !return_timestamps) { - previous_tokens.push(current_tokens); - const resolved_tokens = this.findLongestCommonSequence(previous_tokens)[0]; - const resolved_text = this.decode(resolved_tokens); - chunk.text = resolved_text; - chunks.push(chunk); - - // Flush all our temporary context - previous_tokens = []; - current_tokens = []; - chunk = new_chunk(); - } - - last_language = chunk.language = language; - } else { - // 2/ This is a regular special token, ignoring it - } - } else if (token >= timestamp_begin && token <= timestamp_end) { - // 3/ Timestamp token - const time = (token - timestamp_begin) * time_precision + time_offset; - const rounded_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(time, 2); - - if (last_timestamp !== null && token >= last_timestamp) { - // Whisper outputted a timestamp token, but it falls within - // our stride, so we're going to skip it for the time being - // and resolve this later - // Skip is necessary because timestamp tokens always come - // by pair, so we need to skip the next one too (which would mark the start of another chunk). - skip = true; - } else if (skip || (previous_tokens.length > 0 && token < first_timestamp)) { - skip = false; - } else if (chunk.timestamp[0] === null) { - chunk.timestamp[0] = rounded_time; - } else { - // This is the end of the timestamp chunk - if (rounded_time === chunk.timestamp[0]) { - // This is a bug in timestamp token output - // where we're taking the duplicate token - // as a stop where it should be a start. - // This is an issue in the underlying model output - // Let's just skip it so it becomes de-factor a start agin - } else { - chunk.timestamp[1] = rounded_time; - - // Handling merges - previous_tokens.push(current_tokens) - - if (returnWordTimestamps) { - previous_token_timestamps.push(current_token_timestamps); - } - const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence( - previous_tokens, previous_token_timestamps - ) - - const resolved_text = this.decode(resolved_tokens) - chunk.text = resolved_text - - if (returnWordTimestamps) { - chunk.words = this.collateWordTimestamps( - resolved_tokens, resolved_token_timestamps, last_language, - ) - } - - chunks.push(chunk) - - // Flush all our temporary context - previous_tokens = [] - current_tokens = [] - previous_token_timestamps = [] - current_token_timestamps = [] - chunk = new_chunk() - } - } +// src/models/llava_onevision/image_processing_llava_onevision.js +var LlavaOnevisionImageProcessor = class extends ImageProcessor { +}; - } else { - // 4/ Regular token - // We just append to the list of all tokens so we can handle - // merges later and decode into text. - current_tokens.push(token) - - if (returnWordTimestamps) { - let start_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(token_timestamps[i] + time_offset, 2); - - let end_time; - if (i + 1 < token_timestamps.length) { - end_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(token_timestamps[i + 1] + time_offset, 2); - - // Do not allow punctuation-only tokens to have a duration. - // This prevents long pauses from messing up the timestamps. - const decoded_text = this.decode([token]); - if (PUNCTUATION_ONLY_REGEX.test(decoded_text)) { - // Add `time_precision` to avoid overlapping timestamps - end_time = (0,_utils_maths_js__WEBPACK_IMPORTED_MODULE_3__.round)(Math.min(start_time + time_precision, end_time), 2); - } - } else { - // should never happen - end_time = null; - } - current_token_timestamps.push([start_time, end_time]); - } +// src/models/maskformer/image_processing_maskformer.js +var MaskFormerImageProcessor = class extends ImageProcessor { + /** @type {typeof post_process_panoptic_segmentation} */ + post_process_panoptic_segmentation(...args) { + return post_process_panoptic_segmentation(...args); + } + /** @type {typeof post_process_instance_segmentation} */ + post_process_instance_segmentation(...args) { + return post_process_instance_segmentation(...args); + } +}; +var MaskFormerFeatureExtractor = class extends MaskFormerImageProcessor { +}; - } - } +// src/models/mask2former/image_processing_mask2former.js +var Mask2FormerImageProcessor = class extends MaskFormerImageProcessor { +}; - if ('stride' in output) { - const [chunk_len, stride_left, stride_right] = output.stride; - time_offset += chunk_len - stride_right - } +// src/models/mobilenet_v1/image_processing_mobilenet_v1.js +var MobileNetV1ImageProcessor = class extends ImageProcessor { +}; +var MobileNetV1FeatureExtractor = class extends MobileNetV1ImageProcessor { +}; - // Leftover tokens - if (current_tokens.length > 0) { - previous_tokens.push(current_tokens) - if (returnWordTimestamps) { - previous_token_timestamps.push(current_token_timestamps); - } - } else if (previous_tokens.every(p => p.length === 0)) { - // Flushing previous tokens (END)" - chunk = new_chunk() - previous_tokens = [] - current_tokens = [] - previous_token_timestamps = []; - current_token_timestamps = []; - } +// src/models/mobilenet_v2/image_processing_mobilenet_v2.js +var MobileNetV2ImageProcessor = class extends ImageProcessor { +}; +var MobileNetV2FeatureExtractor = class extends MobileNetV2ImageProcessor { +}; - } +// src/models/mobilenet_v3/image_processing_mobilenet_v3.js +var MobileNetV3ImageProcessor = class extends ImageProcessor { +}; +var MobileNetV3FeatureExtractor = class extends MobileNetV3ImageProcessor { +}; - if (previous_tokens.length > 0) { - if (force_full_sequences && return_timestamps) { - // Last token should always be timestamps, so there shouldn't be - // leftover - 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." - ); - } +// src/models/mobilenet_v4/image_processing_mobilenet_v4.js +var MobileNetV4ImageProcessor = class extends ImageProcessor { +}; +var MobileNetV4FeatureExtractor = class extends MobileNetV4ImageProcessor { +}; - // Happens when we don't use timestamps - const [resolved_tokens, resolved_token_timestamps] = this.findLongestCommonSequence(previous_tokens, previous_token_timestamps); +// src/models/mobilevit/image_processing_mobilevit.js +var MobileViTImageProcessor = class extends ImageProcessor { +}; +var MobileViTFeatureExtractor = class extends MobileViTImageProcessor { +}; - // Flushing previous tokens (FINAL) - const resolved_text = this.decode(resolved_tokens); - chunk.text = resolved_text; - if (returnWordTimestamps) { - chunk.words = this.collateWordTimestamps( - resolved_tokens, resolved_token_timestamps, last_language, - ) - } - chunks.push(chunk); - } +// src/models/nougat/image_processing_nougat.js +var NougatImageProcessor = class extends DonutImageProcessor { +}; - let optional = Object.create(null); +// src/models/owlvit/image_processing_owlvit.js +var OwlViTImageProcessor = class extends ImageProcessor { + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } +}; +var OwlViTFeatureExtractor = class extends OwlViTImageProcessor { +}; - // Preparing and cleaning up the pipeline output - const full_text = chunks.map(chunk => chunk.text).join(''); - if (return_timestamps || return_language) { - for (let i = 0; i < chunks.length; ++i) { - const chunk = chunks[i]; - if (!return_timestamps) { - delete chunk["timestamp"]; - } +// src/models/owlv2/image_processing_owlv2.js +var Owlv2ImageProcessor = class extends OwlViTImageProcessor { +}; - if (!return_language) { - delete chunk["language"]; - } +// src/models/phi3_v/image_processing_phi3_v.js +var IMAGE_SIZE = 336; +var SLICE_AXES = [2, 3]; +var { ceil, floor, sqrt } = Math; +var Phi3VImageProcessor = class extends ImageProcessor { + constructor(config) { + super({ + ...config, + do_normalize: true, + do_pad: true, + pad_size: "custom", + do_convert_rgb: true, + do_resize: true + // Smart resizing "hd_transform" + }); + this._num_crops = config.num_crops; + } + calc_num_image_tokens_from_image_size(width, height) { + const { num_img_tokens } = this.config; + return floor( + (floor(height / IMAGE_SIZE) * floor(width / IMAGE_SIZE) + 1) * num_img_tokens + 1 + (floor(height / IMAGE_SIZE) + 1) * sqrt(num_img_tokens) + ); + } + /** @type {ImageProcessor['get_resize_output_image_size']} */ + get_resize_output_image_size(image, size) { + const hd_num = this._num_crops; + const [width, height] = image.size; + let ratio = width / height; + let scale = 1; + while (scale * Math.ceil(scale / ratio) <= hd_num) { + scale += 1; + } + scale -= 1; + const new_w = Math.floor(scale * 336); + const new_h = Math.floor(new_w / ratio); + return [new_w, new_h]; + } + /** @type {ImageProcessor['pad_image']} */ + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageHeight, imageWidth] = imgDims; + const height = IMAGE_SIZE * ceil(imageHeight / IMAGE_SIZE); + const width = IMAGE_SIZE * ceil(imageWidth / IMAGE_SIZE); + const constant_values = [1, 1, 1].map((x, i) => (x - this.image_mean[i]) / this.image_std[i]); + return super.pad_image( + pixelData, + imgDims, + { width, height }, + { + center: true, + constant_values, + ...options + } + ); + } + async _call(images, { num_crops = null } = {}) { + this._num_crops = num_crops ??= this.config.num_crops; + if (num_crops < 4 || sqrt(num_crops) % 1 !== 0) { + throw new Error("num_crops must be a square number >= 4"); + } + if (!Array.isArray(images)) { + images = [images]; + } + const num_images = images.length; + const imageData = await Promise.all(images.map((x) => this.preprocess(x))); + const original_sizes = imageData.map((x) => x.original_size); + const reshaped_input_sizes = imageData.map((x) => x.reshaped_input_size); + const all_pixel_values = []; + for (const { pixel_values: pixel_values2 } of imageData) { + pixel_values2.unsqueeze_(0); + const [height, width] = pixel_values2.dims.slice(-2); + const batch_pixel_values = await interpolate_4d(pixel_values2, { + size: [IMAGE_SIZE, IMAGE_SIZE], + mode: "bicubic" + }); + if (num_crops > 0) { + const patches = []; + const sqrt_patches = sqrt(num_crops); + const patch_width = floor(width / sqrt_patches); + const patch_height = floor(height / sqrt_patches); + for (let y = 0; y < sqrt_patches; ++y) { + for (let x = 0; x < sqrt_patches; ++x) { + let start_x, start_y, end_x, end_y; + if (y === sqrt_patches - 1) { + start_y = height - patch_height; + end_y = height; + } else { + start_y = y * patch_height; + end_y = (y + 1) * patch_height; } - if (returnWordTimestamps) { - const new_chunks = []; - for (const chunk of chunks) { - for (const word of chunk.words) { - new_chunks.push(word); - } - } - optional = { "chunks": new_chunks }; + if (x === sqrt_patches - 1) { + start_x = width - patch_width; + end_x = width; } else { - optional = { "chunks": chunks }; + start_x = x * patch_width; + end_x = (x + 1) * patch_width; } + const starts = [start_y, start_x]; + const ends = [end_y, end_x]; + const patch = await slice2(pixel_values2, starts, ends, SLICE_AXES); + patches.push(patch); + } } - return [full_text, optional]; - + const resized_tensors = await interpolate_4d(cat(patches, 0), { + size: [IMAGE_SIZE, IMAGE_SIZE], + mode: "bicubic" + }); + all_pixel_values.push(cat([batch_pixel_values, resized_tensors], 0)); + } else { + all_pixel_values.push(batch_pixel_values); + } } + const pixel_values = stack(all_pixel_values, 0); + const sizes = reshaped_input_sizes.map((x) => x.map((y) => IMAGE_SIZE * ceil(y / IMAGE_SIZE))); + const image_sizes = new Tensor3("int64", sizes.flat(), [num_images, 2]); + const num_img_tokens = sizes.map( + ([height, width]) => this.calc_num_image_tokens_from_image_size(width, height) + ); + return { pixel_values, original_sizes, reshaped_input_sizes, image_sizes, num_img_tokens }; + } +}; - /** - * Finds the longest common sequence among the provided sequences. - * @param {number[][]} sequences An array of sequences of token ids to compare. - * @returns {number[][]} The longest common sequence found. - * @throws {Error} If there is a bug within the function. - * @private - */ - findLongestCommonSequence(sequences, token_timestamp_sequences = null) { - // It would be much harder to do O(n) because of fault tolerance. - // We actually have a really good property which is that the total sequence - // MUST be those subsequences in order. - // If token_timestamp_sequences is provided, will split those sequences in - // exactly the same way. - let leftSequence = sequences[0]; - let leftLength = leftSequence.length; - let totalSequence = []; - - const use_token_timestamp_sequences = Array.isArray(token_timestamp_sequences) && token_timestamp_sequences.length > 0; - let total_token_timestamp_sequence = use_token_timestamp_sequences ? [] : null; - let left_token_timestamp_sequence = use_token_timestamp_sequences ? token_timestamp_sequences[0] : null; - for (let i = 1; i < sequences.length; ++i) { - const rightSequence = sequences[i]; - let max = 0.0; - let maxIndices = [leftLength, leftLength, 0, 0]; - // Here we're sliding matches - // [a, b, c, d] - // [c, d, f] - // = [c] == [d] - - // [a, b, c, d] - // [c, d, f] - // = [c, d] == [c, d] - - - // [a, b, c, d] - // [c, d, f] - - // = [b, c, d] == [c, d, f] - - // [a, b, c, d] - // [c, d, f] - - // [a, b, c] == [c, d, f] - - // [a, b, c, d] - // [d, f] - - // [a, b] == [d, f] - - // [a, b, c, d] - // [f] - - // [a] == [f] - - const rightLength = rightSequence.length; - for (let j = 1; j < leftLength + rightLength; ++j) { - // Slightly convoluted because we don't want out of bound indices - // This will be necessary for a small conflict resolution optimization - // later - const leftStart = Math.max(0, leftLength - j); - const leftStop = Math.min(leftLength, leftLength + rightLength - j); - const left = leftSequence.slice(leftStart, leftStop); - const rightStart = Math.max(0, j - leftLength); - const rightStop = Math.min(rightLength, j); - const right = rightSequence.slice(rightStart, rightStop); - if (left.length !== right.length) { - throw new Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."); - } +// src/models/pixtral/image_processing_pixtral.js +var PixtralImageProcessor = class extends ImageProcessor { + /** @type {ImageProcessor['get_resize_output_image_size']} */ + get_resize_output_image_size(image, size) { + const { longest_edge } = size; + if (longest_edge === void 0) { + throw new Error("size must contain 'longest_edge'"); + } + const [srcWidth, srcHeight] = image.size; + const ratio = Math.max(srcWidth, srcHeight) / longest_edge; + let newWidth = srcWidth; + let newHeight = srcHeight; + if (ratio > 1) { + newWidth = Math.floor(srcWidth / ratio); + newHeight = Math.floor(srcHeight / ratio); + } + const { patch_size, spatial_merge_size } = this.config; + if (!spatial_merge_size) { + throw new Error("config must contain 'spatial_merge_size'"); + } + const real_patch_size = patch_size * spatial_merge_size; + const num_width_tokens = Math.floor((newWidth - 1) / real_patch_size) + 1; + const num_height_tokens = Math.floor((newHeight - 1) / real_patch_size) + 1; + return [num_width_tokens * real_patch_size, num_height_tokens * real_patch_size]; + } +}; - let matches; - if (use_token_timestamp_sequences) { - // Get length of longest subsequence of tokens that match - // and have timestamps that are in order - matches = left.filter((elem, idx) => ( - elem === right[idx] - && left_token_timestamp_sequence[leftStart + idx] <= token_timestamp_sequences[i][rightStart + idx] - )).length; - } else { - matches = left.filter((elem, idx) => elem === right[idx]).length; - } +// src/models/pvt/image_processing_pvt.js +var PvtImageProcessor = class extends ImageProcessor { +}; - // epsilon to favor long perfect matches - const eps = j / 10000.0; - const matching = matches / j + eps; - if (matches > 1 && matching > max) { - max = matching; - maxIndices = [leftStart, leftStop, rightStart, rightStop]; - } - } - const [leftStart, leftStop, rightStart, rightStop] = maxIndices; - const leftMid = Math.floor((leftStop + leftStart) / 2); - const rightMid = Math.floor((rightStop + rightStart) / 2); - totalSequence.push(...leftSequence.slice(0, leftMid)); - leftSequence = rightSequence.slice(rightMid); - leftLength = leftSequence.length; - - if (use_token_timestamp_sequences) { - total_token_timestamp_sequence.push(...left_token_timestamp_sequence.slice(0, leftMid)); - left_token_timestamp_sequence = token_timestamp_sequences[i].slice(rightMid); - } - } - totalSequence.push(...leftSequence); +// src/models/rt_detr/image_processing_rt_detr.js +var RTDetrImageProcessor = class extends ImageProcessor { + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } +}; - if (use_token_timestamp_sequences) { - total_token_timestamp_sequence.push(...left_token_timestamp_sequence); - return [totalSequence, total_token_timestamp_sequence]; - } else { - return [totalSequence, []]; +// src/models/sam/image_processing_sam.js +var SamImageProcessor = class extends ImageProcessor { + /** + * + * @param {any} input_points + * @param {import("../../image_processors_utils.js").HeightWidth[]} original_sizes + * @param {import("../../image_processors_utils.js").HeightWidth[]} reshaped_input_sizes + * @returns {Tensor} + */ + reshape_input_points(input_points, original_sizes, reshaped_input_sizes, is_bounding_box = false) { + input_points = structuredClone(input_points); + let shape = calculateDimensions(input_points); + if (shape.length === 3) { + if (!is_bounding_box) { + shape = [1, ...shape]; + } + input_points = [input_points]; + } else if (shape.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 i = 0; i < input_points.length; ++i) { + const [originalHeight, originalWidth] = original_sizes[i]; + const [reshapedHeight, reshapedWidth] = reshaped_input_sizes[i]; + const resizeFactors = [reshapedWidth / originalWidth, reshapedHeight / originalHeight]; + for (let j2 = 0; j2 < input_points[i].length; ++j2) { + for (let k = 0; k < input_points[i][j2].length; ++k) { + for (let w = 0; w < input_points[i][j2][k].length; ++w) { + input_points[i][j2][k][w] *= resizeFactors[w % 2]; + } + } + } + } + return new Tensor3("float32", Float32Array.from(input_points.flat(Infinity)), shape); + } + /** + * + * @param {any} input_labels + * @param {Tensor} input_points + * @returns {Tensor} + */ + add_input_labels(input_labels, input_points) { + let shape = calculateDimensions(input_labels); + if (shape.length === 2) { + shape = [1, ...shape]; + input_labels = [input_labels]; + } else if (shape.length !== 3) { + throw Error( + "The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`." + ); + } + if (shape.some((x, i) => x !== input_points.dims[i])) { + throw Error(`The first ${shape.length} dimensions of 'input_points' and 'input_labels' must be the same.`); + } + return new Tensor3("int64", input_labels.flat(Infinity).map(BigInt), shape); + } + /** + * @param {any[]} images The URL(s) of the image(s) to extract features from. + * @param {Object} [options] Additional options for the processor. + * @param {any} [options.input_points=null] A 3D or 4D array, representing the input points provided by the user. + * - 3D: `[point_batch_size, nb_points_per_image, 2]`. In this case, `batch_size` is assumed to be 1. + * - 4D: `[batch_size, point_batch_size, nb_points_per_image, 2]`. + * @param {any} [options.input_labels=null] A 2D or 3D array, representing the input labels for the points, used by the prompt encoder to encode the prompt. + * - 2D: `[point_batch_size, nb_points_per_image]`. In this case, `batch_size` is assumed to be 1. + * - 3D: `[batch_size, point_batch_size, nb_points_per_image]`. + * @param {number[][][]} [options.input_boxes=null] A 3D array of shape `(batch_size, num_boxes, 4)`, representing the input boxes provided by the user. + * This is used by the prompt encoder to encode the prompt. Generally yields to much better generated masks. + * The processor will generate a tensor, with each dimension corresponding respectively to the image batch size, + * the number of boxes per image and the coordinates of the top left and botton right point of the box. + * In the order (`x1`, `y1`, `x2`, `y2`): + * - `x1`: the x coordinate of the top left point of the input box + * - `y1`: the y coordinate of the top left point of the input box + * - `x2`: the x coordinate of the bottom right point of the input box + * - `y2`: the y coordinate of the bottom right point of the input box + * @returns {Promise} + */ + async _call(images, { input_points = null, input_labels = null, input_boxes = null } = {}) { + const processed = await super._call(images); + if (input_points) { + processed.input_points = this.reshape_input_points( + input_points, + processed.original_sizes, + processed.reshaped_input_sizes + ); + } + if (input_labels) { + if (!processed.input_points) { + throw Error("`input_points` must be provided if `input_labels` are provided."); + } + processed.input_labels = this.add_input_labels(input_labels, processed.input_points); + } + if (input_boxes) { + processed.input_boxes = this.reshape_input_points( + input_boxes, + processed.original_sizes, + processed.reshaped_input_sizes, + true + ); + } + return processed; + } + /** + * Remove padding and upscale masks to the original image size. + * @param {Tensor} masks Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format. + * @param {[number, number][]} original_sizes The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format. + * @param {[number, number][]} reshaped_input_sizes The size of each image as it is fed to the model, in (height, width) format. Used to remove padding. + * @param {Object} options Optional parameters for post-processing. + * @param {number} [options.mask_threshold] The threshold to use for binarizing the masks. + * @param {boolean} [options.binarize] Whether to binarize the masks. + * @param {Object} [options.pad_size] The target size the images were padded to before being passed to the model. If `null`, the target size is assumed to be the processor's `pad_size`. + * @param {number} [options.pad_size.height] The height the images were padded to. + * @param {number} [options.pad_size.width] The width the images were padded to. + * @returns {Promise} Batched masks in batch_size, num_channels, height, width) format, where (height, width) is given by original_size. + */ + async post_process_masks(masks, original_sizes, reshaped_input_sizes, { mask_threshold = 0, binarize = true, pad_size = null } = {}) { + const output_masks = []; + pad_size = pad_size ?? this.pad_size ?? this.size; + const target_image_size = [pad_size.height, pad_size.width]; + for (let i = 0; i < original_sizes.length; ++i) { + const original_size = original_sizes[i]; + const reshaped_input_size = reshaped_input_sizes[i]; + let interpolated_mask = await interpolate_4d(masks[i], { mode: "bilinear", size: target_image_size }); + interpolated_mask = interpolated_mask.slice( + null, + null, + [0, reshaped_input_size[0]], + [0, reshaped_input_size[1]] + ); + interpolated_mask = await interpolate_4d(interpolated_mask, { mode: "bilinear", size: original_size }); + if (binarize) { + const data = interpolated_mask.data; + const binarizedMaskData = new Uint8Array(data.length); + for (let i2 = 0; i2 < data.length; ++i2) { + if (data[i2] > mask_threshold) { + binarizedMaskData[i2] = 1; + } } + interpolated_mask = new Tensor3("bool", binarizedMaskData, interpolated_mask.dims); + } + output_masks.push(interpolated_mask); } + return output_masks; + } + /** + * Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer. + * @param {import("../../utils/image.js").RawImage} image Input original image + * @param {number} target_size Target size of the resized image + * @param {Object} options Options for generating crop boxes + * @param {number} [options.crop_n_layers] If >0, mask prediction will be run again on crops of the image. + * Sets the number of layers to run, where each layer has 2**i_layer number of image crops. + * @param {number} [options.overlap_ratio] Sets the degree to which crops overlap. In the first crop layer, + * crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. + * @param {number} [options.points_per_crop] Number of points to sample from each crop. + * @param {number} [options.crop_n_points_downscale_factor] The number of points-per-side sampled in layer n is + * scaled down by crop_n_points_downscale_factor**n. + * @returns {Object} An object containing the crop boxes, number of points per crop, cropped images, and input labels. + */ + generate_crop_boxes(image, target_size, { + crop_n_layers = 0, + overlap_ratio = 512 / 1500, + points_per_crop = 32, + crop_n_points_downscale_factor = 1 + } = {}) { + } +}; + +// src/models/sapiens/image_processing_sapiens.js +var SapiensImageProcessor = class extends ImageProcessor { + /** @type {typeof post_process_semantic_segmentation} */ + post_process_semantic_segmentation(...args) { + return post_process_semantic_segmentation(...args); + } +}; +var SapiensFeatureExtractor = class extends SapiensImageProcessor { +}; - /** @private */ - collateWordTimestamps(tokens, token_timestamps, language) { +// src/models/segformer/image_processing_segformer.js +var SegformerImageProcessor = class extends ImageProcessor { + /** @type {typeof post_process_semantic_segmentation} */ + post_process_semantic_segmentation(...args) { + return post_process_semantic_segmentation(...args); + } +}; +var SegformerFeatureExtractor = class extends SegformerImageProcessor { +}; - const [words, _, token_indices] = this.combineTokensIntoWords(tokens, language); +// src/models/siglip/image_processing_siglip.js +var SiglipImageProcessor = class extends ImageProcessor { +}; - const timings = []; - for (let i = 0; i < words.length; ++i) { - const indices = token_indices[i]; - timings.push({ - text: words[i], - timestamp: [ - token_timestamps[indices.at(0)][0], - token_timestamps[indices.at(-1)][1], - ], - }); - } - return timings; +// src/models/swin2sr/image_processing_swin2sr.js +var Swin2SRImageProcessor = class extends ImageProcessor { + pad_image(pixelData, imgDims, padSize, options = {}) { + const [imageHeight, imageWidth, imageChannels] = imgDims; + return super.pad_image( + pixelData, + imgDims, + { + // NOTE: For Swin2SR models, the original python implementation adds padding even when the image's width/height is already + // a multiple of `pad_size`. However, this is most likely a bug (PR: https://github.com/mv-lab/swin2sr/pull/19). + // For this reason, we only add padding when the image's width/height is not a multiple of `pad_size`. + width: imageWidth + (padSize - imageWidth % padSize) % padSize, + height: imageHeight + (padSize - imageHeight % padSize) % padSize + }, + { + mode: "symmetric", + center: false, + constant_values: -1, + ...options + } + ); + } +}; + +// src/models/vit/image_processing_vit.js +var ViTImageProcessor = class extends ImageProcessor { +}; +var ViTFeatureExtractor = class extends ViTImageProcessor { +}; + +// src/models/vitmatte/image_processing_vitmatte.js +var VitMatteImageProcessor = class extends ImageProcessor { + /** + * Calls the feature extraction process on an array of images, preprocesses + * each image, and concatenates the resulting features into a single Tensor. + * @param {import("../../utils/image.js").RawImage[]} images The image(s) to extract features from. + * @param {import("../../utils/image.js").RawImage[]} trimaps The trimaps(s) to extract features from. + * @returns {Promise} An object containing the concatenated pixel values of the preprocessed images. + */ + async _call(images, trimaps) { + if (!Array.isArray(images)) { + images = [images]; + } + if (!Array.isArray(trimaps)) { + trimaps = [trimaps]; + } + const imageData = await Promise.all(images.map((x) => this.preprocess(x))); + const trimapData = await Promise.all( + trimaps.map( + (x) => this.preprocess(x, { + do_normalize: false, + do_convert_rgb: false, + do_convert_grayscale: true + }) + ) + ); + const pixel_values = stack( + imageData.map( + // Concatenate images and trimaps + (x, i) => cat([x.pixel_values, trimapData[i].pixel_values], 0) + ), + 0 + ); + return { + pixel_values, + // Original sizes of images + original_sizes: imageData.map((x) => x.original_size), + // Reshaped sizes of images, before padding or cropping + reshaped_input_sizes: imageData.map((x) => x.reshaped_input_size) + }; + } +}; + +// src/models/vitpose/image_processing_vitpose.js +var VitPoseImageProcessor = class extends ImageProcessor { + /** + * Transform the heatmaps into keypoint predictions and transform them back to the image. + * NOTE: This is a naive implementation and does not include advanced post-processing techniques, + * so the results may not be as accurate as the original implementation. + * @param {import('../../utils/tensor.js').Tensor} outputs The model outputs. + * @param {[number, number, number, number][][]} boxes List or array of bounding boxes for each image. + * Each box should be a list of 4 floats representing the bounding box coordinates in COCO format (top_left_x, top_left_y, width, height). + * @returns {{ + * bbox: [number, number, number, number], + * scores: number[], + * labels: number[], + * keypoints: [number, number][] + * }[][]} List of keypoints predictions for each image. + */ + post_process_pose_estimation(outputs, boxes, { + threshold = null + // TODO: + // kernel_size = 11, + // target_sizes = null, + } = {}) { + const heatmaps = outputs.tolist(); + const [batch_size, num_classes, height, width] = outputs.dims; + const results = []; + for (let b = 0; b < batch_size; ++b) { + const heatmap = heatmaps[b]; + const bboxes = boxes[b]; + const batch_results = []; + for (let n = 0; n < bboxes.length; ++n) { + const bbox = bboxes[n]; + const keypoints = []; + const scores = []; + const labels = []; + const xScale = bbox.at(-2) / width; + const yScale = bbox.at(-1) / height; + for (let c = 0; c < heatmap.length; ++c) { + let [xWeightedSum, yWeightedSum] = [0, 0]; + let sum = 0; + let score = -Infinity; + const row = heatmap[c]; + for (let y = 0; y < row.length; ++y) { + const col = row[y]; + for (let x = 0; x < col.length; ++x) { + const value = col[x]; + sum += value; + score = Math.max(score, value); + xWeightedSum += (x + 0.5) * value; + yWeightedSum += y * value; + } + } + if (threshold != null && score < threshold) continue; + const keypoint = [xScale * xWeightedSum / sum, yScale * yWeightedSum / sum]; + keypoints.push(keypoint); + labels.push(c); + scores.push(score); + } + batch_results.push({ + bbox, + scores, + labels, + keypoints + }); + } + results.push(batch_results); } + return results; + } +}; - /** - * Groups tokens by word. Returns a tuple containing a list of strings with the words, - * and a list of `token_id` sequences with the tokens making up each word. - * @param {number[]} tokens - * @param {string} [language] - * @param {string} prepend_punctionations - * @param {string} append_punctuations - * - * @private - */ - combineTokensIntoWords(tokens, language, prepend_punctionations = "\"'“¡¿([{-", append_punctuations = "\"'.。,,!!??::”)]}、") { - language = language ?? 'english'; +// src/models/yolos/image_processing_yolos.js +var YolosImageProcessor = class extends ImageProcessor { + /** @type {typeof post_process_object_detection} */ + post_process_object_detection(...args) { + return post_process_object_detection(...args); + } +}; +var YolosFeatureExtractor = class extends YolosImageProcessor { +}; - let words, word_tokens, token_indices; +// src/models/auto/image_processing_auto.js +var AutoImageProcessor = class { + /** @type {typeof ImageProcessor.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await getModelJSON( + pretrained_model_name_or_path, + IMAGE_PROCESSOR_NAME, + true, + options + ); + const key = preprocessorConfig.image_processor_type ?? preprocessorConfig.feature_extractor_type; + let image_processor_class = image_processors_exports[key?.replace(/Fast$/, "")]; + if (!image_processor_class) { + if (key !== void 0) { + logger.warn( + `Image processor type '${key}' not found, assuming base ImageProcessor. Please report this at ${GITHUB_ISSUE_URL}.` + ); + } + image_processor_class = ImageProcessor; + } + return new image_processor_class(preprocessorConfig); + } +}; - if (["chinese", "japanese", "thai", "lao", "myanmar"].includes(language)) { - // These languages don't typically use spaces. - [words, word_tokens, token_indices] = this.splitTokensOnUnicode(tokens) - } else { - [words, word_tokens, token_indices] = this.splitTokensOnSpaces(tokens) +// src/models/florence2/processing_florence2.js +var Florence2Processor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + constructor(config, components, chat_template) { + super(config, components, chat_template); + const { + // @ts-expect-error TS2339 + tasks_answer_post_processing_type, + // @ts-expect-error TS2339 + task_prompts_without_inputs, + // @ts-expect-error TS2339 + task_prompts_with_input + } = this.image_processor.config; + this.tasks_answer_post_processing_type = new Map(Object.entries(tasks_answer_post_processing_type ?? {})); + this.task_prompts_without_inputs = new Map(Object.entries(task_prompts_without_inputs ?? {})); + this.task_prompts_with_input = new Map(Object.entries(task_prompts_with_input ?? {})); + this.regexes = { + quad_boxes: /(.+?)/gm, + bboxes: /([^<]+)?/gm + }; + this.size_per_bin = 1e3; + } + /** + * Helper function to construct prompts from input texts + * @param {string|string[]} text + * @returns {string[]} + */ + construct_prompts(text) { + if (typeof text === "string") { + text = [text]; + } + const prompts = []; + for (const t of text) { + if (this.task_prompts_without_inputs.has(t)) { + prompts.push(this.task_prompts_without_inputs.get(t)); + } else { + for (const [task, prompt] of this.task_prompts_with_input) { + if (t.includes(task)) { + prompts.push(prompt.replaceAll("{input}", t).replaceAll(task, "")); + break; + } } - - return this.mergePunctuations(words, word_tokens, token_indices, prepend_punctionations, append_punctuations); - } - - /** @type {PreTrainedTokenizer['decode']} */ - decode( - token_ids, - decode_args, - ) { - let text; - // @ts-ignore - if (decode_args?.decode_with_timestamps) { - if (token_ids instanceof _utils_tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor) { - token_ids = prepareTensorForDecode(token_ids); - } - text = this.decodeWithTimestamps(token_ids, decode_args); - } else { - text = super.decode(token_ids, decode_args); + if (prompts.length !== text.length) { + prompts.push(t); } - // TODO: implement offsets - // if (decode_args.output_offsets) { - // let offsets = this.computeOffsets - // } - return text; + } } - - /** - * @param {number[]|bigint[]} token_ids List of token IDs to decode. - * @param {Object} decode_args Optional arguments for decoding - * @private - */ - decodeWithTimestamps(token_ids, decode_args) { - const time_precision = decode_args?.time_precision ?? 0.02; - - const timestamp_begin = Array.from(this.all_special_ids).at(-1) + 1; - /**@type {Array} */ - let outputs = [[]]; - for (let token of token_ids) { - token = Number(token); - if (token >= timestamp_begin) { - const timestamp = ((token - timestamp_begin) * time_precision).toFixed(2); - outputs.push(`<|${timestamp}|>`); - outputs.push([]); - } else { - outputs[outputs.length - 1].push(token); - } + return prompts; + } + /** + * Post-process the output of the model to each of the task outputs. + * @param {string} text The text to post-process. + * @param {string} task The task to post-process the text for. + * @param {[number, number]} image_size The size of the image. height x width. + */ + post_process_generation(text, task, image_size) { + const task_answer_post_processing_type = this.tasks_answer_post_processing_type.get(task) ?? "pure_text"; + text = text.replaceAll("", "").replaceAll("", ""); + let final_answer; + switch (task_answer_post_processing_type) { + case "pure_text": + final_answer = text; + break; + case "description_with_bboxes": + case "bboxes": + case "phrase_grounding": + case "ocr": + const key = task_answer_post_processing_type === "ocr" ? "quad_boxes" : "bboxes"; + const matches = text.matchAll(this.regexes[key]); + const labels = []; + const items = []; + for (const [_, label, ...locations] of matches) { + labels.push(label ? label.trim() : labels.at(-1) ?? ""); + items.push( + locations.map( + (x, i) => ( + // NOTE: Add 0.5 to use the center position of the bin as the coordinate. + (Number(x) + 0.5) / this.size_per_bin * image_size[i % 2] + ) + ) + ); } - outputs = outputs.map( - s => typeof s === 'string' ? s : super.decode(s, decode_args) - ) - - return outputs.join(''); + final_answer = { labels, [key]: items }; + break; + default: + throw new Error(`Task "${task}" (of type "${task_answer_post_processing_type}") not yet implemented.`); } + return { [task]: final_answer }; + } + // NOTE: images and text are switched from the python version + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + if (!images && !text) { + throw new Error("Either text or images must be provided"); + } + const image_inputs = await this.image_processor(images, kwargs); + const text_inputs = text ? this.tokenizer(this.construct_prompts(text), kwargs) : {}; + return { + ...image_inputs, + ...text_inputs + }; + } +}; - /** - * Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points. - * @param {number[]} tokens - * @returns {*} - * @private - */ - splitTokensOnUnicode(tokens) { - const decoded_full = this.decode(tokens, { - // @ts-ignore - decode_with_timestamps: true, - }); - const replacement_char = '\uFFFD'; - - const words = [] - const word_tokens = [] - const token_indices = [] - let current_tokens = [] - let current_indices = [] - let unicode_offset = 0 - - for (let token_idx = 0; token_idx < tokens.length; ++token_idx) { - const token = tokens[token_idx]; - - current_tokens.push(token); - current_indices.push(token_idx); - - const decoded = this.decode(current_tokens, { - // @ts-ignore - decode_with_timestamps: true, - }); - - if (!decoded.includes(replacement_char) || decoded_full[unicode_offset + decoded.indexOf(replacement_char)] === replacement_char) { - words.push(decoded) - word_tokens.push(current_tokens) - token_indices.push(current_indices) - current_tokens = [] - current_indices = [] - unicode_offset += decoded.length; - } - - } - - return [words, word_tokens, token_indices] +// src/models/gemma3/processing_gemma3.js +var Gemma3Processor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + static uses_processor_config = true; + static uses_chat_template_file = true; + constructor(config, components, chat_template) { + super(config, components, chat_template); + this.image_seq_length = this.config.image_seq_length; + const { boi_token, image_token, eoi_token } = this.tokenizer.config; + this.boi_token = boi_token; + this.image_token = image_token; + this.eoi_token = eoi_token; + const image_tokens_expanded = image_token.repeat(this.image_seq_length); + this.full_image_sequence = ` + +${boi_token}${image_tokens_expanded}${eoi_token} + +`; + } + /** + * @param {string|string[]} text + * @param {import('../../utils/image.js').RawImage|import('../../utils/image.js').RawImage[]} [images] + * @param {Object} [options] + */ + async _call(text, images = null, options = {}) { + if (typeof text === "string") { + text = [text]; } + let image_inputs; + if (images) { + image_inputs = await this.image_processor(images, options); + text = text.map((prompt) => prompt.replaceAll(this.boi_token, this.full_image_sequence)); + } + const text_inputs = this.tokenizer(text, options); + return { + ...text_inputs, + ...image_inputs + }; + } +}; - /** - * Combine tokens into words by splitting at whitespace and punctuation tokens. - * @param {number[]} tokens - * @private - */ - splitTokensOnSpaces(tokens) { - - const [subwords, subword_tokens_list, subword_indices_list] = this.splitTokensOnUnicode(tokens); - - const words = [] - const word_tokens = [] - const token_indices = [] - - const punctuationRegex = new RegExp(`^[${PUNCTUATION_REGEX}]$`, 'gu'); - - for (let i = 0; i < subwords.length; ++i) { - - const subword = subwords[i]; - const subword_tokens = subword_tokens_list[i]; - const subword_indices = subword_indices_list[i]; - - // @ts-ignore - const special = subword_tokens[0] >= this.model.tokens_to_ids.get('<|endoftext|>'); - const with_space = subword.startsWith(' '); - const trimmed = subword.trim(); - const punctuation = punctuationRegex.test(trimmed); +// src/models/gemma3n/processing_gemma3n.js +var Gemma3nProcessor = class extends Processor { + static image_processor_class = AutoImageProcessor; + static feature_extractor_class = AutoFeatureExtractor; + static tokenizer_class = AutoTokenizer; + static uses_processor_config = true; + static uses_chat_template_file = true; + constructor(config, components, chat_template) { + super(config, components, chat_template); + this.audio_seq_length = this.config.audio_seq_length; + this.image_seq_length = this.config.image_seq_length; + const { + // Audio tokens + audio_token_id, + boa_token, + audio_token, + eoa_token, + // Image tokens + image_token_id, + boi_token, + image_token, + eoi_token + } = this.tokenizer.config; + this.audio_token_id = audio_token_id; + this.boa_token = boa_token; + this.audio_token = audio_token; + const audio_tokens_expanded = audio_token.repeat(this.audio_seq_length); + this.full_audio_sequence = ` + +${boa_token}${audio_tokens_expanded}${eoa_token} + +`; + this.image_token_id = image_token_id; + this.boi_token = boi_token; + this.image_token = image_token; + const image_tokens_expanded = image_token.repeat(this.image_seq_length); + this.full_image_sequence = ` + +${boi_token}${image_tokens_expanded}${eoi_token} + +`; + } + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]|RawImage[][]} images + * @param {RawAudio|RawAudio[]|RawAudio[][]} audio + * @returns {Promise} + */ + async _call(text, images = null, audio = null, options = {}) { + if (typeof text === "string") { + text = [text]; + } + let audio_inputs; + if (audio) { + audio_inputs = await this.feature_extractor(audio, options); + text = text.map((prompt) => prompt.replaceAll(this.audio_token, this.full_audio_sequence)); + } + let image_inputs; + if (images) { + image_inputs = await this.image_processor(images, options); + text = text.map((prompt) => prompt.replaceAll(this.image_token, this.full_image_sequence)); + } + let text_inputs = this.tokenizer(text, options); + return { + ...text_inputs, + ...image_inputs, + ...audio_inputs + }; + } +}; - if (special || with_space || punctuation || words.length === 0) { - words.push(subword); - word_tokens.push(subword_tokens); - token_indices.push(subword_indices); - } else { - const ix = words.length - 1; - words[ix] += subword; - word_tokens[ix].push(...subword_tokens); - token_indices[ix].push(...subword_indices); - } +// src/models/qwen2_vl/processing_qwen2_vl.js +var Qwen2VLProcessor = class extends Processor { + static image_processor_class = AutoImageProcessor; + static tokenizer_class = AutoTokenizer; + static image_token = "<|image_pad|>"; + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]} images + * @param {...any} args + * @returns {Promise} + */ + async _call(text, images = null, ...args) { + if (!Array.isArray(text)) { + text = [text]; + } + let image_inputs, image_grid_thw; + if (images) { + image_inputs = await this.image_processor(images); + image_grid_thw = image_inputs.image_grid_thw; + } + if (image_grid_thw) { + let merge_length = this.image_processor.config.merge_size ** 2; + let index = 0; + const image_token = ( + /** @type {typeof Qwen2VLProcessor} */ + this.constructor.image_token + ); + const image_grid_thw_list = image_grid_thw.tolist(); + text = text.map((t) => { + while (t.includes(image_token)) { + const prod = Number(image_grid_thw_list[index++].reduce((a, b) => a * b, 1n)); + t = t.replace(image_token, "<|placeholder|>".repeat(Math.floor(prod / merge_length))); } - - return [words, word_tokens, token_indices]; - + return t.replaceAll("<|placeholder|>", image_token); + }); } + const text_inputs = this.tokenizer(text); + return { + ...text_inputs, + ...image_inputs + }; + } +}; - /** - * Merges punctuation tokens with neighboring words. - * @param {string[]} words - * @param {number[][]} tokens - * @param {number[][]} indices - * @param {string} prepended - * @param {string} appended - * @private - */ - mergePunctuations(words, tokens, indices, prepended, appended) { - - const newWords = structuredClone(words); - const newTokens = structuredClone(tokens); - const newIndices = structuredClone(indices); - +// src/models/glm46v/processing_glm46v.js +var Glm46VProcessor = class extends Qwen2VLProcessor { + static image_token = "<|image|>"; +}; - // prepend punctuations - let i = newWords.length - 2; - let j = newWords.length - 1; +// src/models/granite_speech/processing_granite_speech.js +var GraniteSpeechProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + static uses_processor_config = true; + /** + * Compute the number of audio tokens for a given raw audio length. + * @param {number} audioLength Raw audio sample count. + * @returns {number} Number of projector output tokens. + */ + _get_num_audio_features(audioLength) { + const { hop_length } = this.feature_extractor.config.melspec_kwargs; + const { projector_window_size, projector_downsample_rate } = this.feature_extractor.config; + const effective_window_size = Math.floor(projector_window_size / projector_downsample_rate); + const mel_length = Math.floor(audioLength / hop_length) + 1; + const encoder_length = Math.floor(mel_length / 2); + const nblocks = Math.ceil(encoder_length / projector_window_size); + return nblocks * effective_window_size; + } + /** + * @param {string} text The text input to process. + * @param {Float32Array} audio The audio input to process. + */ + async _call(text, audio = null, kwargs = {}) { + if (Array.isArray(text)) { + throw new Error("Batched inputs are not supported yet."); + } + let audio_inputs = {}; + if (audio) { + const { input_features } = await this.feature_extractor(audio); + audio_inputs["input_features"] = input_features; + const audio_embed_size = this._get_num_audio_features(audio.length); + const mask_data = new Uint8Array(audio_embed_size).fill(1); + audio_inputs["input_features_mask"] = new Tensor3("bool", mask_data, [1, audio_embed_size]); + const audio_token = this.config.audio_token ?? "<|audio|>"; + if (!text.includes(audio_token)) { + throw new Error(`The input text does not contain the audio token ${audio_token}.`); + } + text = text.replaceAll(audio_token, audio_token.repeat(audio_embed_size)); + } + const text_inputs = this.tokenizer(text, { + add_special_tokens: false, + ...kwargs + }); + return { + ...text_inputs, + ...audio_inputs + }; + } +}; - while (i >= 0) { - if (newWords[i].startsWith(' ') && prepended.includes(newWords[i].trim())) { - newWords[j] = newWords[i] + newWords[j]; - newTokens[j] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newTokens[i], newTokens[j]); - newIndices[j] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newIndices[i], newIndices[j]); - newWords[i] = ''; - newTokens[i] = []; - newIndices[i] = []; - } else { - j = i; - } - --i; - } - - // append punctuations - i = 0; - j = 1; - while (j < newWords.length) { - if (!newWords[i].endsWith(' ') && appended.includes(newWords[j])) { - newWords[i] += newWords[j]; - newTokens[i] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newTokens[i], newTokens[j]); - newIndices[i] = (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)(newIndices[i], newIndices[j]); - newWords[j] = ''; - newTokens[j] = []; - newIndices[j] = []; - } else { - i = j; - } - ++j; +// src/models/grounding_dino/processing_grounding_dino.js +function get_phrases_from_posmap(posmaps, input_ids) { + const left_idx = 0; + const right_idx = posmaps.dims.at(-1) - 1; + const posmaps_list = posmaps.tolist(); + posmaps_list.fill(false, 0, left_idx + 1); + posmaps_list.fill(false, right_idx); + const input_ids_list = input_ids.tolist(); + return posmaps_list.map((val, idx) => val ? idx : null).filter((idx) => idx !== null).map((i) => input_ids_list[i]); +} +var GroundingDinoProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + /** + * + * @param {RawImage|RawImage[]|RawImage[][]} images + * @param {string|string[]} text + * @returns {Promise} + */ + async _call(images, text, options = {}) { + const image_inputs = images ? await this.image_processor(images, options) : {}; + const text_inputs = text ? this.tokenizer(text, options) : {}; + return { + ...text_inputs, + ...image_inputs + }; + } + post_process_grounded_object_detection(outputs, input_ids, { box_threshold = 0.25, text_threshold = 0.25, target_sizes = null } = {}) { + const { logits, pred_boxes } = outputs; + const batch_size = logits.dims[0]; + if (target_sizes !== null && target_sizes.length !== batch_size) { + throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits"); + } + const num_queries = logits.dims.at(1); + const probs = logits.sigmoid(); + const scores = probs.max(-1).tolist(); + const boxes = pred_boxes.tolist().map((batch) => batch.map((box) => center_to_corners_format(box))); + const results = []; + for (let i = 0; i < batch_size; ++i) { + const target_size = target_sizes !== null ? target_sizes[i] : null; + if (target_size !== null) { + boxes[i] = boxes[i].map((box) => box.map((x, j2) => x * target_size[(j2 + 1) % 2])); + } + const batch_scores = scores[i]; + const final_scores = []; + const final_phrases = []; + const final_boxes = []; + for (let j2 = 0; j2 < num_queries; ++j2) { + const score = batch_scores[j2]; + if (score <= box_threshold) { + continue; } + const box = boxes[i][j2]; + const prob = probs[i][j2]; + final_scores.push(score); + final_boxes.push(box); + const phrases = get_phrases_from_posmap(prob.gt(text_threshold), input_ids[i]); + final_phrases.push(phrases); + } + results.push({ scores: final_scores, boxes: final_boxes, labels: this.batch_decode(final_phrases) }); + } + return results; + } +}; - return [ - newWords.filter(x => x), - newTokens.filter(x => x.length > 0), - newIndices.filter(x => x.length > 0), - ] +// src/models/idefics3/processing_idefics3.js +function _prompt_split_image(image_seq_len, image_rows, image_cols, fake_token_around_image, image_token, global_img_token) { + let text_split_images = ""; + for (let n_h = 0; n_h < image_rows; ++n_h) { + for (let n_w = 0; n_w < image_cols; ++n_w) { + text_split_images += fake_token_around_image + `` + image_token.repeat(image_seq_len); } + text_split_images += "\n"; + } + text_split_images += ` +${fake_token_around_image}${global_img_token}` + image_token.repeat(image_seq_len) + `${fake_token_around_image}`; + return text_split_images; } -class CodeGenTokenizer extends PreTrainedTokenizer { } -class CLIPTokenizer extends PreTrainedTokenizer { } -class SiglipTokenizer extends PreTrainedTokenizer { } - -/** - * @todo This model is not yet supported by Hugging Face's "fast" tokenizers library (https://github.com/huggingface/tokenizers). - * Therefore, this implementation (which is based on fast tokenizers) may produce slightly inaccurate results. - */ -class MarianTokenizer extends PreTrainedTokenizer { - /** - * Create a new MarianTokenizer instance. - * @param {Object} tokenizerJSON The JSON of the tokenizer. - * @param {Object} tokenizerConfig The config of the tokenizer. - */ - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - - this.languageRegex = /^(>>\w+<<)\s*/g; - - this.supported_language_codes = this.model.vocab.filter( - x => this.languageRegex.test(x) - ); - - console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.') +function _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token) { + return `${fake_token_around_image}${global_img_token}` + image_token.repeat(image_seq_len) + `${fake_token_around_image}`; +} +function get_image_prompt_string(image_rows, image_cols, image_seq_len, fake_token_around_image, image_token, global_img_token) { + if (image_rows === 0 && image_cols === 0) { + return _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token); + } + return _prompt_split_image( + image_seq_len, + image_rows, + image_cols, + fake_token_around_image, + image_token, + global_img_token + ); +} +var Idefics3Processor = class extends Processor { + static image_processor_class = AutoImageProcessor; + static tokenizer_class = AutoTokenizer; + static uses_processor_config = true; + fake_image_token = ""; + image_token = ""; + global_img_token = ""; + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]|RawImage[][]} images + * @returns {Promise} + */ + async _call(text, images = null, options = {}) { + options.return_row_col_info ??= true; + let image_inputs; + if (images) { + image_inputs = await this.image_processor(images, options); + } + if (!Array.isArray(text)) { + text = [text]; + } + const image_rows = image_inputs.rows ?? [new Array(text.length).fill(0)]; + const image_cols = image_inputs.cols ?? [new Array(text.length).fill(0)]; + const image_seq_len = this.config.image_seq_len; + const n_images_in_text = []; + const prompt_strings = []; + for (let i = 0; i < text.length; ++i) { + const sample = text[i]; + const sample_rows = image_rows[i]; + const sample_cols = image_cols[i]; + n_images_in_text.push(count(sample, this.image_token)); + const image_prompt_strings = sample_rows.map( + (n_rows, j2) => get_image_prompt_string( + n_rows, + sample_cols[j2], + image_seq_len, + this.fake_image_token, + this.image_token, + this.global_img_token + ) + ); + const split_sample = sample.split(this.image_token); + if (split_sample.length === 0) { + throw new Error("The image token should be present in the text."); + } + let new_sample = split_sample[0]; + for (let j2 = 0; j2 < image_prompt_strings.length; ++j2) { + new_sample += image_prompt_strings[j2] + split_sample[j2 + 1]; + } + prompt_strings.push(new_sample); } + const text_inputs = this.tokenizer(prompt_strings); + return { + ...text_inputs, + ...image_inputs + }; + } +}; - /** - * Encodes a single text. Overriding this method is necessary since the language codes - * must be removed before encoding with sentencepiece model. - * @see https://github.com/huggingface/transformers/blob/12d51db243a00726a548a43cc333390ebae731e3/src/transformers/models/marian/tokenization_marian.py#L204-L213 - * - * @param {string|null} text The text to encode. - * @returns {Array} The encoded tokens. - */ - _encode_text(text) { - if (text === null) return null; - - // Check if text starts with language code: - const [matchInfo, ...remainder] = text.trim().split(this.languageRegex); - - if (remainder.length === 0) { - // No language code, encode normally - return super._encode_text(matchInfo); - - } else if (remainder.length === 2) { - // Text starts with language code, so we do not encode it with sentencepiece. - const [language, text] = remainder; +// src/models/janus/processing_janus.js +var VLChatProcessor = class extends Processor { + static image_processor_class = AutoImageProcessor; + static tokenizer_class = AutoTokenizer; + static uses_processor_config = true; + constructor(config, components, chat_template) { + super(config, components, chat_template); + 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; + } + /** + * @typedef {Object} MultimodalMessageProperties Additional properties for multimodal messages. + * @property {(RawImage | string | URL)[]} [images] The images in the message. + * @typedef {(import('../../tokenization_utils.js').Message & MultimodalMessageProperties)[]} MultimodalConversation The conversation possibly containing multimodal inputs. + */ + /** + * @typedef {Object} VLCChatProcessorResult The processed input. + * @property {Tensor} input_ids The input IDs. + * @property {Tensor} attention_mask The attention mask. + * @property {Tensor} images_seq_mask The image sequence mask. + * @property {Tensor} images_emb_mask The image embedding mask. + */ + /** + * @param {MultimodalConversation} conversation The chat messages to process. + * @param {Object} options Additional options for processing. + * @param {RawImage|RawImage[]} [options.images] The images to process, if not set in the conversation. + * @param {string} [options.chat_template="default"] The chat template to use. + * @returns {Promise} The processed input. + */ + async _call(conversation, { images = null, chat_template = "default" } = {}) { + if (!images) { + images = await Promise.all( + conversation.filter((msg) => msg.images).flatMap((msg) => msg.images).map((img) => RawImage.read(img)) + ); + } else if (!Array.isArray(images)) { + images = [images]; + } + const tokenizer = this.tokenizer; + const result = tokenizer.apply_chat_template(conversation, { + tokenize: false, + add_generation_prompt: true, + chat_template + }); + const encode = (text) => tokenizer.encode(text, { add_special_tokens: false }); + const parts = ( + /** @type {string} */ + result.split(this.image_tag) + ); + const num_images = parts.length - 1; + if (images.length !== num_images) { + throw new Error( + `Number of images provided (${images.length}) does not match number of "${this.image_tag}" image tags (${num_images})` + ); + } + const [image_placeholder_tag_id, image_start_tag_id, image_end_tag_id] = tokenizer.convert_tokens_to_ids([ + this.image_tag, + this.image_start_tag, + this.image_end_tag + ]); + let input_ids = encode(parts[0]); + let images_seq_mask = new Array(input_ids.length).fill(false); + for (let i = 1; i < parts.length; ++i) { + const placeholder_image_tokens = new Array(this.num_image_tokens).fill(image_placeholder_tag_id); + const tokens = encode(parts[i]); + input_ids = mergeArrays( + input_ids, + [image_start_tag_id], + placeholder_image_tokens, + [image_end_tag_id], + tokens + ); + const image_mask = new Array(this.num_image_tokens).fill(true); + images_seq_mask = mergeArrays( + images_seq_mask, + [false], + image_mask, + [false], + new Array(tokens.length).fill(false) + ); + } + const dims = [1, input_ids.length]; + const final = { + input_ids: new Tensor3("int64", input_ids, dims), + attention_mask: new Tensor3("int64", new Array(input_ids.length).fill(1), dims), + images_seq_mask: new Tensor3("bool", images_seq_mask, dims), + images_emb_mask: new Tensor3("bool", new Array(num_images * this.num_image_tokens).fill(true), [ + 1, + num_images, + this.num_image_tokens + ]) + }; + if (images && images.length > 0) { + const image_inputs = await this.image_processor(images); + image_inputs.pixel_values.unsqueeze_(0); + return { ...final, ...image_inputs }; + } + return final; + } +}; - if (!this.supported_language_codes.includes(language)) { - console.warn(`Unsupported language code "${language}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`) - } - return (0,_utils_core_js__WEBPACK_IMPORTED_MODULE_1__.mergeArrays)([language], super._encode_text(text)); - } - } - -} - -class Wav2Vec2CTCTokenizer extends PreTrainedTokenizer { } - -class BlenderbotTokenizer extends PreTrainedTokenizer { } -class BlenderbotSmallTokenizer extends PreTrainedTokenizer { } - -class SpeechT5Tokenizer extends PreTrainedTokenizer { } - -class NougatTokenizer extends PreTrainedTokenizer { } - -class VitsTokenizer extends PreTrainedTokenizer { - - constructor(tokenizerJSON, tokenizerConfig) { - super(tokenizerJSON, tokenizerConfig); - - // Custom decoder function - this.decoder = new VitsDecoder({}); - } -} - -class CohereTokenizer extends PreTrainedTokenizer { } - -class MgpstrTokenizer extends PreTrainedTokenizer { } - -class Ernie4_5_Tokenizer extends PreTrainedTokenizer { } - -/** - * Helper class which is used to instantiate pretrained tokenizers with the `from_pretrained` function. - * The chosen tokenizer class is determined by the type specified in the tokenizer config. - * - * @example - * const tokenizer = await AutoTokenizer.from_pretrained('Xenova/bert-base-uncased'); - */ -class AutoTokenizer { - static TOKENIZER_CLASS_MAPPING = { - T5Tokenizer, - DistilBertTokenizer, - CamembertTokenizer, - DebertaTokenizer, - DebertaV2Tokenizer, - BertTokenizer, - HerbertTokenizer, - ConvBertTokenizer, - RoFormerTokenizer, - XLMTokenizer, - ElectraTokenizer, - MobileBertTokenizer, - SqueezeBertTokenizer, - AlbertTokenizer, - GPT2Tokenizer, - BartTokenizer, - MBartTokenizer, - MBart50Tokenizer, - RobertaTokenizer, - WhisperTokenizer, - CodeGenTokenizer, - CLIPTokenizer, - SiglipTokenizer, - MarianTokenizer, - BloomTokenizer, - NllbTokenizer, - M2M100Tokenizer, - LlamaTokenizer, - CodeLlamaTokenizer, - XLMRobertaTokenizer, - MPNetTokenizer, - FalconTokenizer, - GPTNeoXTokenizer, - EsmTokenizer, - Wav2Vec2CTCTokenizer, - BlenderbotTokenizer, - BlenderbotSmallTokenizer, - SpeechT5Tokenizer, - NougatTokenizer, - VitsTokenizer, - Qwen2Tokenizer, - GemmaTokenizer, - Grok1Tokenizer, - CohereTokenizer, - MgpstrTokenizer, - Ernie4_5_Tokenizer, - - // Base case: - PreTrainedTokenizer, +// src/models/jina_clip/processing_jina_clip.js +var JinaCLIPProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + async _call(text = null, images = null, kwargs = {}) { + if (!text && !images) { + throw new Error("Either text or images must be provided"); } + const text_inputs = text ? this.tokenizer(text, kwargs) : {}; + const image_inputs = images ? await this.image_processor(images, kwargs) : {}; + return { + ...text_inputs, + ...image_inputs + }; + } +}; +// src/models/lfm2_vl/processing_lfm2_vl.js +var Lfm2VlProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + /** + * @param {RawImage|RawImage[]} images + * @param {string|string[]|null} [text] + * @param {Record} [kwargs] + */ + async _call(images, text = null, kwargs = {}) { + const { image_rows, image_cols, image_sizes, ...image_inputs } = await this.image_processor(images, { + ...kwargs, + return_row_col_info: true + }); + if (text) { + const image_token = this.config.image_token ?? ""; + const { + tile_size = 512, + downsample_factor = 2, + encoder_patch_size = 16, + use_thumbnail = true + } = ( + /** @type {Record} */ + this.image_processor.config + ); + const ds2 = (s) => Math.ceil(Math.floor(s / encoder_patch_size) / downsample_factor); + const tokens_per_tile = ds2(tile_size) ** 2; + const image_start = this.config.image_start_token ?? "<|image_start|>"; + const image_end = this.config.image_end_token ?? "<|image_end|>"; + const thumbnail_token = this.config.image_thumbnail ?? "<|img_thumbnail|>"; + if (!Array.isArray(text)) text = [text]; + let image_idx = 0; + text = text.map((sample) => { + const parts = sample.split(image_token); + return parts[0] + parts.slice(1).map((part) => { + const idx = image_idx++; + const [h, w] = image_sizes[idx]; + const rows = image_rows[idx], cols = image_cols[idx]; + const tokens_for_image = ds2(h) * ds2(w); + let expanded = image_start; + if (rows > 1 || cols > 1) { + const tile_str = image_token.repeat(tokens_per_tile); + for (let r = 0; r < rows; ++r) + for (let c = 0; c < cols; ++c) + expanded += `<|img_row_${r + 1}_col_${c + 1}|>` + tile_str; + if (use_thumbnail) expanded += thumbnail_token + image_token.repeat(tokens_for_image); + } else { + expanded += image_token.repeat(tokens_for_image); + } + return expanded + image_end + part; + }).join(""); + }); + } + return { + ...image_inputs, + ...text ? this.tokenizer(text, kwargs) : {} + }; + } +}; - /** - * Instantiate one of the tokenizer classes of the library from a pretrained model. - * - * The tokenizer class to instantiate is selected based on the `tokenizer_class` property of the config object - * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) - * - * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: - * - A string, the *model id* of a pretrained tokenizer hosted inside a model repo on huggingface.co. - * Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a - * user or organization name, like `dbmdz/bert-base-german-cased`. - * - A path to a *directory* containing tokenizer files, e.g., `./my_model_directory/`. - * @param {PretrainedTokenizerOptions} options Additional options for loading the tokenizer. - * - * @returns {Promise} A new instance of the PreTrainedTokenizer class. - */ - static async from_pretrained(pretrained_model_name_or_path, { - progress_callback = null, - config = null, - cache_dir = null, - local_files_only = false, - revision = 'main', - legacy = null, - } = {}) { - - const [tokenizerJSON, tokenizerConfig] = await loadTokenizer(pretrained_model_name_or_path, { - progress_callback, - config, - cache_dir, - local_files_only, - revision, - legacy, +// src/models/lfm3_vl/processing_lfm3_vl.js +var Lfm3VlProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + /** + * @param {import('../../utils/image.js').RawImage|import('../../utils/image.js').RawImage[]|null} images + * @param {string|string[]|null} [text] + * @param {Record} [kwargs] + */ + async _call(images, text = null, kwargs = {}) { + const image_inputs = images ? await this.image_processor(images, kwargs) : {}; + if (text !== null) { + if (!Array.isArray(text)) text = [text]; + const image_token = this.tokenizer.config.image_token ?? "<|image|>"; + const grids = image_inputs.image_grid_thw?.tolist() ?? []; + const num_placeholders = text.reduce((count2, sample) => count2 + sample.split(image_token).length - 1, 0); + if (num_placeholders !== grids.length) { + throw new Error( + `Found ${num_placeholders} ${image_token} tokens in the text but received ${grids.length} images.` + ); + } + const merge_size = ( + /** @type {Record} */ + this.image_processor.config.merge_size + ); + let index = 0; + text = text.map( + (sample) => sample.replaceAll(image_token, () => { + const num_patches = Number(grids[index++].reduce((a, b) => a * b, 1n)); + return image_token.repeat(num_patches / merge_size ** 2); }) + ); + } + return { + ...image_inputs, + ...text !== null ? this.tokenizer(text, kwargs) : {} + }; + } +}; - // Some tokenizers are saved with the "Fast" suffix, so we remove that if present. - const tokenizerName = tokenizerConfig.tokenizer_class?.replace(/Fast$/, '') ?? 'PreTrainedTokenizer'; +// src/models/llava/processing_llava.js +var LlavaProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + static uses_processor_config = true; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + const image_inputs = await this.image_processor(images, kwargs); + if (text) { + const [height, width] = image_inputs.pixel_values.dims.slice(-2); + const { image_token, patch_size, num_additional_image_tokens } = this.config; + const num_image_tokens = Math.floor(height / patch_size) * Math.floor(width / patch_size) + num_additional_image_tokens; + text = structuredClone(text); + if (!Array.isArray(text)) { + text = [text]; + } + for (let i = 0; i < text.length; ++i) { + text[i] = text[i].replace(image_token, image_token.repeat(num_image_tokens)); + } + } + const text_inputs = text ? this.tokenizer(text, kwargs) : {}; + return { + ...image_inputs, + ...text_inputs + }; + } +}; - let cls = this.TOKENIZER_CLASS_MAPPING[tokenizerName]; - if (!cls) { - console.warn(`Unknown tokenizer class "${tokenizerName}", attempting to construct from base class.`); - cls = PreTrainedTokenizer; +// src/models/mgp_str/processing_mgp_str.js +var DECODE_TYPE_MAPPING = { + char: ["char_decode", 1], + bpe: ["bpe_decode", 2], + wp: ["wp_decode", 102] +}; +var MgpstrProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + /** + * @returns {import('./tokenization_mgp_str.js').MgpstrTokenizer} The character tokenizer. + */ + get char_tokenizer() { + return this.components.char_tokenizer; + } + /** + * @returns {import('../gpt2/tokenization_gpt2.js').GPT2Tokenizer} The BPE tokenizer. + */ + get bpe_tokenizer() { + return this.components.bpe_tokenizer; + } + /** + * @returns {import('../bert/tokenization_bert.js').BertTokenizer} The WordPiece tokenizer. + */ + get wp_tokenizer() { + return this.components.wp_tokenizer; + } + /** + * Helper function to decode the model prediction logits. + * @param {import('../../utils/tensor.js').Tensor} pred_logits Model prediction logits. + * @param {string} format Type of model prediction. Must be one of ['char', 'bpe', 'wp']. + * @returns {[string[], number[]]} The decoded sentences and their confidence scores. + */ + _decode_helper(pred_logits, format2) { + if (!DECODE_TYPE_MAPPING.hasOwnProperty(format2)) { + throw new Error(`Format ${format2} is not supported.`); + } + const [decoder_name, eos_token] = DECODE_TYPE_MAPPING[format2]; + const decoder = this[decoder_name].bind(this); + const [batch_size, batch_max_length] = pred_logits.dims; + const conf_scores = []; + const all_ids = []; + const pred_logits_list = pred_logits.tolist(); + for (let i = 0; i < batch_size; ++i) { + const logits = pred_logits_list[i]; + const ids = []; + const scores = []; + for (let j2 = 1; j2 < batch_max_length; ++j2) { + const [max_prob, max_prob_index] = max(softmax(logits[j2])); + scores.push(max_prob); + if (max_prob_index == eos_token) { + break; } - return new cls(tokenizerJSON, tokenizerConfig); + ids.push(max_prob_index); + } + const confidence_score = scores.length > 0 ? scores.reduce((a, b) => a * b, 1) : 0; + all_ids.push(ids); + conf_scores.push(confidence_score); } -} + const decoded = decoder(all_ids); + return [decoded, conf_scores]; + } + /** + * Convert a list of lists of char token ids into a list of strings by calling char tokenizer. + * @param {number[][]} sequences List of tokenized input ids. + * @returns {string[]} The list of char decoded sentences. + */ + char_decode(sequences) { + return this.char_tokenizer.batch_decode(sequences).map((str) => str.replaceAll(" ", "")); + } + /** + * Convert a list of lists of BPE token ids into a list of strings by calling BPE tokenizer. + * @param {number[][]} sequences List of tokenized input ids. + * @returns {string[]} The list of BPE decoded sentences. + */ + bpe_decode(sequences) { + return this.bpe_tokenizer.batch_decode(sequences); + } + /** + * Convert a list of lists of word piece token ids into a list of strings by calling word piece tokenizer. + * @param {number[][]} sequences List of tokenized input ids. + * @returns {string[]} The list of wp decoded sentences. + */ + wp_decode(sequences) { + return this.wp_tokenizer.batch_decode(sequences).map((str) => str.replaceAll(" ", "")); + } + /** + * Convert a list of lists of token ids into a list of strings by calling decode. + * @param {[import('../../utils/tensor.js').Tensor, import('../../utils/tensor.js').Tensor, import('../../utils/tensor.js').Tensor]} sequences List of tokenized input ids. + * @returns {{generated_text: string[], scores: number[], char_preds: string[], bpe_preds: string[], wp_preds: string[]}} + * Dictionary of all the outputs of the decoded results. + * - generated_text: The final results after fusion of char, bpe, and wp. + * - scores: The final scores after fusion of char, bpe, and wp. + * - char_preds: The list of character decoded sentences. + * - bpe_preds: The list of BPE decoded sentences. + * - wp_preds: The list of wp decoded sentences. + */ + // @ts-expect-error The type of this method is not compatible with the one in the base class. + batch_decode([char_logits, bpe_logits, wp_logits]) { + const [char_preds, char_scores] = this._decode_helper(char_logits, "char"); + const [bpe_preds, bpe_scores] = this._decode_helper(bpe_logits, "bpe"); + const [wp_preds, wp_scores] = this._decode_helper(wp_logits, "wp"); + const generated_text = []; + const scores = []; + for (let i = 0; i < char_preds.length; ++i) { + const [max_score, max_score_index] = max([char_scores[i], bpe_scores[i], wp_scores[i]]); + generated_text.push([char_preds[i], bpe_preds[i], wp_preds[i]][max_score_index]); + scores.push(max_score); + } + return { + generated_text, + scores, + char_preds, + bpe_preds, + wp_preds + }; + } + /** @type {typeof Processor.from_pretrained} */ + static async from_pretrained(...args) { + const base = await super.from_pretrained(...args); + const bpe_tokenizer = await AutoTokenizer.from_pretrained("Xenova/gpt2"); + const wp_tokenizer = await AutoTokenizer.from_pretrained("Xenova/bert-base-uncased"); + base.components = { + image_processor: base.image_processor, + char_tokenizer: base.tokenizer, + bpe_tokenizer, + wp_tokenizer + }; + return base; + } + async _call(images, text = null) { + const result = await this.image_processor(images); + if (text) { + result.labels = this.tokenizer(text).input_ids; + } + return result; + } +}; +// src/models/moonshine/processing_moonshine.js +var MoonshineProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } +}; -/***/ }), +// src/models/owlvit/processing_owlvit.js +var OwlViTProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; +}; -/***/ "./src/utils/audio.js": -/*!****************************!*\ - !*** ./src/utils/audio.js ***! - \****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { +// src/models/paligemma/processing_paligemma.js +var IMAGE_TOKEN = ""; +function build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images) { + return `${image_token.repeat(image_seq_len * num_images)}${bos_token}${prompt} +`; +} +var PaliGemmaProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + static uses_processor_config = false; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + if (!text) { + logger.warn( + "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model." + ); + text = ""; + } + if (!Array.isArray(images)) { + images = [images]; + } + if (!Array.isArray(text)) { + text = [text]; + } + const bos_token = this.tokenizer.bos_token; + const image_seq_length = this.image_processor.config.image_seq_length; + let input_strings; + if (text.some((t) => t.includes(IMAGE_TOKEN))) { + input_strings = text.map((sample) => { + const expanded_sample = sample.replaceAll(IMAGE_TOKEN, IMAGE_TOKEN.repeat(image_seq_length)); + const bos_rfind_index = expanded_sample.lastIndexOf(IMAGE_TOKEN); + const bos_index = bos_rfind_index === -1 ? 0 : bos_rfind_index + IMAGE_TOKEN.length; + return expanded_sample.slice(0, bos_index) + bos_token + expanded_sample.slice(bos_index) + "\n"; + }); + } else { + logger.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." + ); + input_strings = text.map( + (sample) => build_string_from_input(sample, bos_token, image_seq_length, IMAGE_TOKEN, images.length) + ); + } + const text_inputs = this.tokenizer(input_strings, kwargs); + const image_inputs = await this.image_processor(images, kwargs); + return { + ...image_inputs, + ...text_inputs + }; + } +}; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ RawAudio: () => (/* binding */ RawAudio), -/* harmony export */ hamming: () => (/* binding */ hamming), -/* harmony export */ hanning: () => (/* binding */ hanning), -/* harmony export */ mel_filter_bank: () => (/* binding */ mel_filter_bank), -/* harmony export */ read_audio: () => (/* binding */ read_audio), -/* harmony export */ spectrogram: () => (/* binding */ spectrogram), -/* harmony export */ window_function: () => (/* binding */ window_function) -/* harmony export */ }); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _maths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./core.js */ "./src/utils/core.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); -/* harmony import */ var _tensor_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! node:fs */ "?7992"); -/** - * @file Helper module for audio processing. - * - * These functions and classes are only used internally, - * meaning an end-user shouldn't need to access anything here. - * - * @module utils/audio - */ +// src/models/phi3_v/processing_phi3_v.js +var IMAGE_TOKEN2 = "<|image|>"; +var IMAGE_TOKEN_PATTERN = /<\|image_\d+\|>/g; +var Phi3VProcessor = class extends Processor { + static image_processor_class = AutoImageProcessor; + static tokenizer_class = AutoTokenizer; + /** + * + * @param {string|string[]} text + * @param {RawImage|RawImage[]} images + * @param { { padding?: boolean, truncation?: boolean, num_crops?: number } | undefined } options + * @returns {Promise} + */ + async _call(text, images = null, { padding = true, truncation = true, num_crops = null } = {}) { + if (!Array.isArray(text)) { + text = [text]; + } + let text_inputs, image_inputs; + if (images) { + image_inputs = await this.image_processor(images, { num_crops }); + const { num_img_tokens } = image_inputs; + const prompt_chunks = text.map( + (t, i) => t.split(IMAGE_TOKEN_PATTERN).join(IMAGE_TOKEN2.repeat(num_img_tokens[i])) + ); + text_inputs = this.tokenizer(prompt_chunks, { padding, truncation }); + const image_token_id = this.tokenizer._tokenizer.token_to_id(IMAGE_TOKEN2); + text_inputs.input_ids.map_((id) => id == image_token_id ? -id : id); + } else { + text_inputs = this.tokenizer(text); + } + return { + ...text_inputs, + ...image_inputs + }; + } +}; +// src/models/pixtral/processing_pixtral.js +var PixtralProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static image_processor_class = AutoImageProcessor; + static uses_processor_config = true; + /** + * @typedef {import('../../utils/image.js').RawImage} RawImage + */ + // `images` is required, `text` is optional + async _call(images, text = null, kwargs = {}) { + const image_inputs = await this.image_processor(images, kwargs); + if (text) { + const [height, width] = image_inputs.pixel_values.dims.slice(-2); + const { image_token, image_break_token, image_end_token, patch_size, spatial_merge_size } = this.config; + const real_patch_size = patch_size * spatial_merge_size; + const num_height_tokens = Math.floor(height / real_patch_size); + const num_width_tokens = Math.floor(width / real_patch_size); + text = structuredClone(text); + if (!Array.isArray(text)) { + text = [text]; + } + for (let i = 0; i < text.length; ++i) { + const width_tokens = image_token.repeat(num_width_tokens); + const row = width_tokens + image_break_token; + const finalRow = width_tokens + image_end_token; + const full2 = row.repeat(num_height_tokens - 1) + finalRow; + text[i] = text[i].replace(image_token, full2); + } + } + const text_inputs = text ? this.tokenizer(text, kwargs) : {}; + return { + ...image_inputs, + ...text_inputs + }; + } +}; +// src/models/pyannote/processing_pyannote.js +var PyAnnoteProcessor = class extends Processor { + static feature_extractor_class = PyAnnoteFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } + /** @type {PyAnnoteFeatureExtractor['post_process_speaker_diarization']} */ + post_process_speaker_diarization(...args) { + return ( + /** @type {PyAnnoteFeatureExtractor} */ + this.feature_extractor.post_process_speaker_diarization( + ...args + ) + ); + } + get sampling_rate() { + return this.feature_extractor.config.sampling_rate; + } +}; +// src/models/qwen2_5_vl/processing_qwen2_5_vl.js +var Qwen2_5_VLProcessor = class extends Qwen2VLProcessor { +}; +// src/models/qwen3_vl/processing_qwen3_vl.js +var Qwen3VLProcessor = class extends Qwen2_5_VLProcessor { +}; +// src/models/sam/processing_sam.js +var SamProcessor = class extends Processor { + static image_processor_class = AutoImageProcessor; + async _call(...args) { + return await this.image_processor(...args); + } + post_process_masks(...args) { + return this.image_processor.post_process_masks(...args); + } + reshape_input_points(...args) { + return this.image_processor.reshape_input_points(...args); + } +}; +// src/models/sam2/processing_sam2.js +var Sam2Processor = class extends SamProcessor { +}; +var Sam2VideoProcessor = class extends Sam2Processor { +}; +// src/models/speecht5/processing_speecht5.js +var SpeechT5Processor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given input. + * @param {any} input The input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(input) { + return await this.feature_extractor(input); + } +}; -/** - * Helper function to read audio from a path/URL. - * @param {string|URL} url The path/URL to load the audio from. - * @param {number} sampling_rate The sampling rate to use when decoding the audio. - * @returns {Promise} The decoded audio as a `Float32Array`. - */ -async function read_audio(url, sampling_rate) { - if (typeof AudioContext === 'undefined') { - // Running in node or an environment without AudioContext - 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." - ) +// src/models/ultravox/processing_ultravox.js +var UltravoxProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + static uses_processor_config = true; + /** + * @param {string} text The text input to process. + * @param {Float32Array} audio The audio input to process. + */ + async _call(text, audio = null, kwargs = {}) { + if (Array.isArray(text)) { + throw new Error("Batched inputs are not supported yet."); + } + let audio_inputs = {}; + if (audio) { + const audio_len = audio.length; + const { input_features } = await this.feature_extractor(audio, { + ...kwargs, + max_length: audio_len + }); + const nb_encoder_frames = Math.round(audio_len / this.config.encoder_ds_factor + 1e-4); + const audio_embed_frames = 1 + Math.ceil(nb_encoder_frames / this.config.stack_factor); + audio_inputs["audio_token_len"] = [audio_embed_frames]; + audio_inputs["audio_values"] = input_features; + const image_token = this.config.audio_placeholder; + if (!text.includes(image_token)) { + throw new Error(`The input text does not contain the image token ${image_token}.`); + } + text = text.replaceAll(image_token, image_token.repeat(audio_embed_frames)); } + const text_inputs = this.tokenizer(text, { + add_special_tokens: false, + ...kwargs + }); + return { + ...text_inputs, + ...audio_inputs + }; + } +}; - const response = await (await (0,_hub_js__WEBPACK_IMPORTED_MODULE_0__.getFile)(url)).arrayBuffer(); - const audioCTX = new AudioContext({ sampleRate: sampling_rate }); - if (typeof sampling_rate === 'undefined') { - console.warn(`No sampling rate provided, using default of ${audioCTX.sampleRate}Hz.`) +// src/models/voxtral/processing_voxtral.js +var AUDIO_TOKEN = "[AUDIO]"; +var BEGIN_AUDIO_TOKEN = "[BEGIN_AUDIO]"; +var NUM_AUDIO_TOKENS = 375; +function chunk(audio, n_samples) { + const chunks = []; + for (let i = 0; i < audio.length; i += n_samples) { + chunks.push(audio.subarray(i, Math.min(i + n_samples, audio.length))); + } + return chunks; +} +var VoxtralProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + static uses_processor_config = false; + /** + * @param {string} text The text input to process. + * @param {Float32Array|Float32Array[]} audio The audio input(s) to process. + */ + async _call(text, audio = null, kwargs = {}) { + if (Array.isArray(text)) { + throw new Error("Batched inputs are not supported yet."); + } + const audio_inputs = {}; + if (audio) { + if (!text.includes(AUDIO_TOKEN)) { + throw new Error(`The input text does not contain the audio token ${AUDIO_TOKEN}.`); + } + if (!Array.isArray(audio)) { + audio = [audio]; + } + const text_parts = text.split(AUDIO_TOKEN); + const num_audio_tokens = text_parts.length - 1; + if (num_audio_tokens !== audio.length) { + throw new Error( + `The number of audio inputs (${audio.length}) does not match the number of audio tokens in the text (${num_audio_tokens}).` + ); + } + const n_samples = this.feature_extractor.config.n_samples; + const audio_chunks = audio.map((a) => chunk(a, n_samples)); + const chunk_counts = audio_chunks.map((chunks) => chunks.length); + const all_chunks = audio_chunks.flat(); + const features = (await Promise.all(all_chunks.map((audio_input) => this.feature_extractor(audio_input, kwargs)))).map((x) => x.input_features); + audio_inputs["audio_values"] = features.length > 1 ? cat(features, 0) : features[0]; + let new_text = text_parts[0]; + for (let i = 0; i < chunk_counts.length; ++i) { + new_text += BEGIN_AUDIO_TOKEN; + for (let j2 = 0; j2 < chunk_counts[i]; ++j2) { + new_text += AUDIO_TOKEN.repeat(NUM_AUDIO_TOKENS); + } + new_text += text_parts[i + 1]; + } + text = new_text; } - const decoded = await audioCTX.decodeAudioData(response); - - /** @type {Float32Array} */ - let audio; + const text_inputs = this.tokenizer(text, { + add_special_tokens: false, + ...kwargs + }); + return { + ...text_inputs, + ...audio_inputs + }; + } +}; - // We now replicate HuggingFace's `ffmpeg_read` method: - if (decoded.numberOfChannels === 2) { - // When downmixing a stereo audio file to mono using the -ac 1 option in FFmpeg, - // the audio signal is summed across both channels to create a single mono channel. - // However, if the audio is at full scale (i.e. the highest possible volume level), - // the summing of the two channels can cause the audio signal to clip or distort. +// src/models/voxtral_realtime/processing_voxtral_realtime.js +var NUM_LEFT_PAD_TOKENS = 32; +var NUM_DELAY_TOKENS = 6; +var AUDIO_LENGTH_PER_TOK = 8; +var OFFLINE_STREAMING_BUFFER_TOKENS = 10; +var STREAMING_PAD_TOKEN_ID = 32; +var VoxtralRealtimeProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + static uses_processor_config = false; + /** Number of mel frames in the first audio chunk. */ + get num_mel_frames_first_audio_chunk() { + return (NUM_DELAY_TOKENS + 1) * AUDIO_LENGTH_PER_TOK; + } + /** Number of raw audio samples in the first audio chunk. */ + get num_samples_first_audio_chunk() { + const { hop_length, n_fft } = this.feature_extractor.config; + return (this.num_mel_frames_first_audio_chunk - 1) * hop_length + Math.floor(n_fft / 2); + } + /** Number of raw audio samples per subsequent audio chunk. */ + get num_samples_per_audio_chunk() { + const { hop_length, n_fft } = this.feature_extractor.config; + return AUDIO_LENGTH_PER_TOK * hop_length + n_fft; + } + /** Number of right-pad tokens for non-streaming mode. */ + get num_right_pad_tokens() { + return NUM_DELAY_TOKENS + 1 + OFFLINE_STREAMING_BUFFER_TOKENS; + } + /** Number of mel frames per text token. */ + get audio_length_per_tok() { + return AUDIO_LENGTH_PER_TOK; + } + /** Number of raw audio samples per token. */ + get raw_audio_length_per_tok() { + return AUDIO_LENGTH_PER_TOK * this.feature_extractor.config.hop_length; + } + /** + * Process audio input for VoxtralRealtime. + * + * In streaming mode with `is_first_audio_chunk=true`, the audio is left-padded + * with silence and mel features are extracted with `center=true`. + * Returns `{ input_ids, input_features }`. + * + * In streaming mode with `is_first_audio_chunk=false`, the audio chunk is + * processed with `center=false` and only `{ input_features }` is returned. + * + * In non-streaming mode, the audio is right-padded to ensure the model + * transcribes the full audio, then processed with `center=true`. + * Returns `{ input_features }`. + * + * @param {Float32Array|Float64Array} audio The audio waveform. + * @param {Object} [options] + * @param {boolean} [options.is_streaming=false] Whether processing in streaming mode. + * @param {boolean} [options.is_first_audio_chunk=true] Whether this is the first audio chunk. + * @returns {Promise} + */ + async _call(audio, { is_streaming = false, is_first_audio_chunk = true } = {}) { + validate_audio_inputs(audio, "VoxtralRealtimeProcessor"); + if (!is_streaming && !is_first_audio_chunk) { + throw new Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`."); + } + if (is_first_audio_chunk) { + if (is_streaming) { + const num_left_pad_samples = NUM_LEFT_PAD_TOKENS * this.raw_audio_length_per_tok; + const padded_audio = new Float32Array(num_left_pad_samples + audio.length); + padded_audio.set(audio, num_left_pad_samples); + const audio_encoding = await this.feature_extractor(padded_audio, { center: true }); + const num_pad_tokens = NUM_LEFT_PAD_TOKENS + NUM_DELAY_TOKENS; + const num_input_tokens = 1 + num_pad_tokens; + const input_ids_data = new BigInt64Array(num_input_tokens).fill(BigInt(STREAMING_PAD_TOKEN_ID)); + input_ids_data[0] = 1n; + const input_ids = new Tensor3("int64", input_ids_data, [1, num_input_tokens]); + return { + input_ids, + ...audio_encoding + }; + } else { + const right_pad_samples = this.num_right_pad_tokens * this.raw_audio_length_per_tok; + const padded_audio = new Float32Array(audio.length + right_pad_samples); + padded_audio.set(audio); + return await this.feature_extractor(padded_audio, { center: true }); + } + } else { + return await this.feature_extractor(audio, { center: false }); + } + } +}; - // To prevent this clipping, FFmpeg applies a scaling factor of 1/sqrt(2) (~ 0.707) - // to the audio signal before summing the two channels. This scaling factor ensures - // that the combined audio signal will not exceed the maximum possible level, even - // if both channels are at full scale. +// src/models/wav2vec2/processing_wav2vec2.js +var Wav2Vec2Processor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } +}; - // After applying this scaling factor, the audio signal from both channels is summed - // to create a single mono channel. It's worth noting that this scaling factor is - // only applied when downmixing stereo audio to mono using the -ac 1 option in FFmpeg. - // If you're using a different downmixing method, or if you're not downmixing the - // audio at all, this scaling factor may not be needed. - const SCALING_FACTOR = Math.sqrt(2); +// src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js +var Wav2Vec2ProcessorWithLM = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } +}; - const left = decoded.getChannelData(0); - const right = decoded.getChannelData(1); +// src/models/whisper/processing_whisper.js +var WhisperProcessor = class extends Processor { + static tokenizer_class = AutoTokenizer; + static feature_extractor_class = AutoFeatureExtractor; + /** + * Calls the feature_extractor function with the given audio input. + * @param {any} audio The audio input to extract features from. + * @returns {Promise} A Promise that resolves with the extracted features. + */ + async _call(audio) { + return await this.feature_extractor(audio); + } +}; - audio = new Float32Array(left.length); - for (let i = 0; i < decoded.length; ++i) { - audio[i] = SCALING_FACTOR * (left[i] + right[i]) / 2; +// src/models/auto/processing_auto.js +var AutoProcessor = class { + /** @type {typeof Processor.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + const preprocessorConfig = await getModelJSON( + pretrained_model_name_or_path, + IMAGE_PROCESSOR_NAME, + true, + options + ); + const { image_processor_type, feature_extractor_type, processor_class } = preprocessorConfig; + if (processor_class && processors_exports[processor_class]) { + return processors_exports[processor_class].from_pretrained(pretrained_model_name_or_path, options); + } + if (!image_processor_type && !feature_extractor_type) { + throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config."); + } + const components = {}; + if (image_processor_type) { + const image_processor_class = image_processors_exports[image_processor_type.replace(/Fast$/, "")]; + if (!image_processor_class) { + throw new Error(`Unknown image_processor_type: '${image_processor_type}'.`); + } + components.image_processor = new image_processor_class(preprocessorConfig); + } + if (feature_extractor_type) { + const image_processor_class = image_processors_exports[feature_extractor_type]; + if (image_processor_class) { + components.image_processor = new image_processor_class(preprocessorConfig); + } else { + const feature_extractor_class = feature_extractors_exports[feature_extractor_type]; + if (!feature_extractor_class) { + throw new Error(`Unknown feature_extractor_type: '${feature_extractor_type}'.`); } - - } else { - // If the audio is not stereo, we can just use the first channel: - audio = decoded.getChannelData(0); + components.feature_extractor = new feature_extractor_class(preprocessorConfig); + } } + const config = {}; + return new Processor(config, components, null); + } +}; - return audio; +// src/configs.js +async function loadConfig(pretrained_model_name_or_path, options) { + return await getModelJSON(pretrained_model_name_or_path, "config.json", true, options); } - -/** - * Helper function to generate windows that are special cases of the generalized cosine window. - * See https://www.mathworks.com/help/signal/ug/generalized-cosine-windows.html for more information. - * @param {number} M Number of points in the output window. If zero or less, an empty array is returned. - * @param {number} a_0 Offset for the generalized cosine window. - * @returns {Float64Array} The generated window. - */ -function generalized_cosine_window(M, a_0) { - if (M < 1) { - return new Float64Array(); +function getNormalizedConfig(config) { + const mapping = {}; + let init_normalized_config = {}; + switch (config.model_type) { + // Sub-configs + case "llava": + case "paligemma": + case "gemma3": + case "florence2": + case "llava_onevision": + case "idefics3": + case "granite_speech": + case "ultravox": + case "voxtral": + case "voxtral_realtime": + case "smolvlm": + case "gemma3n": + case "gemma4": + case "lfm2_vl": + case "lfm3_vl": + case "chatterbox": + case "lighton_ocr": + case "glm_ocr": + case "mistral3": + case "qwen2_5_vl": + case "qwen3_vl": + case "qwen3_vl_moe": + init_normalized_config = getNormalizedConfig(config.text_config); + break; + case "moondream1": + init_normalized_config = getNormalizedConfig(config.phi_config); + break; + case "musicgen": + init_normalized_config = getNormalizedConfig(config.decoder); + break; + case "multi_modality": + init_normalized_config = getNormalizedConfig(config.language_config); + break; + // Decoder-only models + case "gpt2": + case "gptj": + case "jais": + case "codegen": + case "gpt_bigcode": + mapping["num_heads"] = "n_head"; + mapping["num_layers"] = "n_layer"; + mapping["hidden_size"] = "n_embd"; + break; + case "gpt_neox": + case "stablelm": + case "opt": + case "falcon": + case "modernbert-decoder": + mapping["num_heads"] = "num_attention_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["hidden_size"] = "hidden_size"; + break; + case "gpt_oss": + case "llama": + case "llama4_text": + case "nanochat": + case "apertus": + case "arcee": + case "afmoe": + case "lfm2": + case "lfm2_moe": + case "lfm3": + case "smollm3": + case "olmo": + case "olmo2": + case "olmo3": + case "mobilellm": + case "granite": + case "granitemoehybrid": + case "cohere": + case "cohere2": + case "mistral": + case "voxtral_realtime_text": + case "voxtral_realtime_encoder": + case "starcoder2": + case "qwen2": + case "qwen2_moe": + case "qwen2_vl": + case "qwen2_vl_text": + case "qwen2_5_vl_text": + case "qwen3_moe": + case "qwen3_vl_text": + case "qwen3_vl_moe_text": + case "phi": + case "phi3": + case "phi3_v": + case "llava_qwen2": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["hidden_size"] = "hidden_size"; + mapping["num_attention_heads"] = "num_attention_heads"; + mapping["dim_kv"] = "head_dim"; + break; + case "qwen3": + case "solar_open": + case "glm_ocr_text": + case "gemma": + case "gemma2": + case "vaultgemma": + case "gemma3_text": + case "gemma3n_text": + case "gemma4_text": + case "glm": + case "helium": + case "ernie4_5": + case "hunyuan_v1_dense": + case "falcon_h1": + case "nemotron_h": + case "ministral": + case "ministral3": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["dim_kv"] = "head_dim"; + break; + case "openelm": + mapping["num_heads"] = "num_kv_heads"; + mapping["num_layers"] = "num_transformer_layers"; + mapping["dim_kv"] = "head_dim"; + break; + case "gpt_neo": + case "donut-swin": + mapping["num_heads"] = "num_heads"; + mapping["num_layers"] = "num_layers"; + mapping["hidden_size"] = "hidden_size"; + break; + case "bloom": + mapping["num_heads"] = "n_head"; + mapping["num_layers"] = "n_layer"; + mapping["hidden_size"] = "hidden_size"; + break; + case "mpt": + mapping["num_heads"] = "n_heads"; + mapping["num_layers"] = "n_layers"; + mapping["hidden_size"] = "d_model"; + break; + case "exaone": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_layers"; + mapping["dim_kv"] = "head_dim"; + mapping["num_attention_heads"] = "num_attention_heads"; + break; + case "youtu": + case "deepseek_v3": + case "deepseek_v4": + case "glm_moe_dsa": + case "mistral4": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["dim_kv"] = config.model_type === "deepseek_v4" ? "head_dim" : "qk_head_dim"; + mapping["num_attention_heads"] = "num_attention_heads"; + break; + case "zaya": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["hidden_size"] = "hidden_size"; + mapping["dim_kv"] = "head_dim"; + mapping["num_attention_heads"] = "num_attention_heads"; + break; + case "hrm_text": + mapping["num_heads"] = "num_key_value_heads"; + mapping["num_layers"] = "num_hidden_layers"; + mapping["hidden_size"] = "hidden_size"; + mapping["dim_kv"] = "head_dim"; + mapping["num_attention_heads"] = "num_attention_heads"; + break; + // Encoder-decoder models + case "t5": + case "mt5": + case "longt5": + mapping["num_decoder_layers"] = "num_decoder_layers"; + mapping["num_decoder_heads"] = "num_heads"; + mapping["decoder_dim_kv"] = "d_kv"; + mapping["num_encoder_layers"] = "num_layers"; + mapping["num_encoder_heads"] = "num_heads"; + mapping["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": + mapping["num_decoder_layers"] = "decoder_layers"; + mapping["num_decoder_heads"] = "decoder_attention_heads"; + mapping["decoder_hidden_size"] = "d_model"; + mapping["num_encoder_layers"] = "encoder_layers"; + mapping["num_encoder_heads"] = "encoder_attention_heads"; + mapping["encoder_hidden_size"] = "d_model"; + break; + case "speecht5": + mapping["num_decoder_layers"] = "decoder_layers"; + mapping["num_decoder_heads"] = "decoder_attention_heads"; + mapping["decoder_hidden_size"] = "hidden_size"; + mapping["num_encoder_layers"] = "encoder_layers"; + mapping["num_encoder_heads"] = "encoder_attention_heads"; + mapping["encoder_hidden_size"] = "hidden_size"; + break; + case "trocr": + mapping["num_encoder_layers"] = mapping["num_decoder_layers"] = "decoder_layers"; + mapping["num_encoder_heads"] = mapping["num_decoder_heads"] = "decoder_attention_heads"; + mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "d_model"; + break; + case "musicgen_decoder": + mapping["num_encoder_layers"] = mapping["num_decoder_layers"] = "num_hidden_layers"; + mapping["num_encoder_heads"] = mapping["num_decoder_heads"] = "num_attention_heads"; + mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "hidden_size"; + break; + case "moonshine": + mapping["num_decoder_layers"] = "decoder_num_hidden_layers"; + mapping["num_decoder_heads"] = "decoder_num_key_value_heads"; + mapping["num_encoder_layers"] = "encoder_num_hidden_layers"; + mapping["num_encoder_heads"] = "encoder_num_key_value_heads"; + mapping["encoder_hidden_size"] = mapping["decoder_hidden_size"] = "hidden_size"; + break; + case "cohere_asr": + mapping["num_decoder_layers"] = "num_hidden_layers"; + mapping["num_decoder_heads"] = "num_key_value_heads"; + mapping["decoder_hidden_size"] = "hidden_size"; + mapping["decoder_dim_kv"] = "head_dim"; + const { + num_hidden_layers: num_encoder_layers, + num_attention_heads: num_encoder_heads, + hidden_size: encoder_hidden_size + } = ( + /** @type {any} */ + config.encoder_config + ); + init_normalized_config = { + num_encoder_layers, + num_encoder_heads, + encoder_hidden_size, + // @ts-expect-error TS2339 + encoder_dim_kv: config.head_dim + }; + break; + case "vision-encoder-decoder": + const decoderConfig = getNormalizedConfig(config.decoder); + const add_encoder_pkv = "num_decoder_layers" in decoderConfig; + const result = pick(config, ["model_type", "is_encoder_decoder"]); + if (add_encoder_pkv) { + result.num_decoder_layers = decoderConfig.num_decoder_layers; + result.num_decoder_heads = decoderConfig.num_decoder_heads; + result.decoder_hidden_size = decoderConfig.decoder_hidden_size; + result.num_encoder_layers = decoderConfig.num_encoder_layers; + result.num_encoder_heads = decoderConfig.num_encoder_heads; + result.encoder_hidden_size = decoderConfig.encoder_hidden_size; + } else { + result.num_layers = decoderConfig.num_layers; + result.num_heads = decoderConfig.num_heads; + result.hidden_size = decoderConfig.hidden_size; + } + return result; + } + const normalized_config = { + ...init_normalized_config, + ...pick(config, ["model_type", "multi_query", "is_encoder_decoder"]) + }; + for (const key in mapping) { + normalized_config[key] = config[mapping[key]]; + } + return normalized_config; +} +function getCacheNames(config, options) { + if (!(config instanceof PretrainedConfig)) { + config = new PretrainedConfig(config); + } + const pkv_prefix = options?.prefix ?? "past_key_values"; + const cache_prefix = pkv_prefix === "present" ? "present" : "past"; + const names = /* @__PURE__ */ new Set(); + if (["lfm2", "lfm2_moe", "lfm3"].includes(config.model_type)) { + const { layer_types } = ( + /** @type {any} */ + config + ); + for (let i = 0; i < layer_types.length; ++i) { + if (layer_types[i] === "full_attention" || layer_types[i] === "sliding_attention") { + names.add(`${pkv_prefix}.${i}.key`); + names.add(`${pkv_prefix}.${i}.value`); + } else if (layer_types[i] === "conv") { + names.add(`${cache_prefix}_conv.${i}`); + } else { + throw new Error(`Unsupported layer type: ${layer_types[i]}`); + } } - if (M === 1) { - return new Float64Array([1]); + return names; + } else if (["granitemoehybrid", "falcon_h1", "nemotron_h"].includes(config.model_type)) { + const c = ( + /** @type {any} */ + config + ); + const layer_types = c.layer_types ?? c.layers_block_type; + const num_layers = c.num_hidden_layers ?? layer_types?.length; + for (let i = 0; i < num_layers; ++i) { + if (!layer_types || layer_types[i] === "mamba") { + names.add(`${cache_prefix}_conv.${i}`); + names.add(`${cache_prefix}_ssm.${i}`); + } + if (!layer_types || layer_types[i] === "attention") { + names.add(`${pkv_prefix}.${i}.key`); + names.add(`${pkv_prefix}.${i}.value`); + } } - - const a_1 = 1 - a_0; - const factor = 2 * Math.PI / (M - 1); - - const cos_vals = new Float64Array(M); - for (let i = 0; i < M; ++i) { - cos_vals[i] = a_0 - a_1 * Math.cos(i * factor); + return names; + } else if (["qwen3_next", "qwen3_5_text", "qwen3_5_moe_text", "olmo_hybrid"].includes(config.model_type)) { + const { layer_types } = ( + /** @type {any} */ + config + ); + for (let i = 0; i < layer_types.length; ++i) { + if (layer_types[i] === "full_attention") { + names.add(`${pkv_prefix}.${i}.key`); + names.add(`${pkv_prefix}.${i}.value`); + } else if (layer_types[i] === "linear_attention") { + if (config.model_type === "olmo_hybrid") { + names.add(`${cache_prefix}_conv.${i}.key`); + names.add(`${cache_prefix}_conv.${i}.value`); + names.add(`${cache_prefix}_conv.${i}.query`); + } else { + names.add(`${cache_prefix}_conv.${i}`); + } + names.add(`${cache_prefix}_recurrent.${i}`); + } else { + throw new Error(`Unsupported layer type: ${layer_types[i]}`); + } } - return cos_vals; -} + return names; + } else if (["gemma4", "gemma4_text"].includes(config.model_type)) { + const c = ( + /** @type {any} */ + config.model_type === "gemma4" ? ( + /** @type {any} */ + config.text_config + ) : config + ); + const num_hidden_layers = c.num_hidden_layers; + const num_kv_shared_layers = c.num_kv_shared_layers ?? 0; + const num_kv_layers = num_hidden_layers - num_kv_shared_layers; + for (let i = 0; i < num_kv_layers; ++i) { + names.add(`${pkv_prefix}.${i}.key`); + names.add(`${pkv_prefix}.${i}.value`); + } + return names; + } else if (config.model_type === "deepseek_v4") { + const { layer_types, num_hidden_layers } = ( + /** @type {any} */ + config + ); + for (let i = 0; i < num_hidden_layers; ++i) { + names.add(`${pkv_prefix}.${i}.key`); + names.add(`${pkv_prefix}.${i}.value`); + const layer_type = layer_types[i]; + if (layer_type === "compressed_sparse_attention") { + names.add(`${cache_prefix}_compressor.${i}.kv`); + names.add(`${cache_prefix}_compressor.${i}.gate`); + names.add(`${cache_prefix}_indexer.${i}.kv`); + names.add(`${cache_prefix}_indexer.${i}.gate`); + } else if (layer_type === "heavily_compressed_attention") { + names.add(`${cache_prefix}_compressor.${i}.kv`); + names.add(`${cache_prefix}_compressor.${i}.gate`); + } else if (layer_type && layer_type !== "sliding_attention") { + throw new Error(`Unsupported layer type: ${layer_type}`); + } + } + return names; + } else if (config.model_type === "zaya") { + const { num_hidden_layers, cca_time1 } = ( + /** @type {any} */ + config + ); + const stride = cca_time1 ?? 1; + for (let i = 0; i < num_hidden_layers; i += stride) { + names.add(`${pkv_prefix}.${i}.key`); + names.add(`${pkv_prefix}.${i}.value`); + names.add(`${pkv_prefix}.${i}.conv_state`); + names.add(`${pkv_prefix}.${i}.shift_state`); + } + return names; + } else if (["lfm2_vl", "lfm3_vl", "qwen3_5", "qwen3_5_moe", "voxtral_realtime"].includes(config.model_type)) { + let subConfig; + if (config.model_type === "voxtral_realtime" && options?.session_name === "audio_encoder") { + subConfig = /** @type {any} */ + config.audio_config; + } else { + subConfig = /** @type {any} */ + config.text_config; + } + return getCacheNames(subConfig, options); + } + return getKeyValueNames(config, { prefix: pkv_prefix }); +} +function getKeyValueNames(config, { prefix = "past_key_values" } = {}) { + const names = /* @__PURE__ */ new Set(); + const normalized_config = config.normalized_config; + if (normalized_config.is_encoder_decoder && "num_encoder_heads" in normalized_config && "num_decoder_heads" in normalized_config) { + for (let i = 0; i < normalized_config.num_decoder_layers; ++i) { + names.add(`${prefix}.${i}.encoder.key`); + names.add(`${prefix}.${i}.encoder.value`); + names.add(`${prefix}.${i}.decoder.key`); + names.add(`${prefix}.${i}.decoder.value`); + } + } else if (normalized_config.multi_query) { + for (let i = 0; i < normalized_config.num_layers; ++i) { + names.add(`${prefix}.${i}.key_value`); + } + } else { + for (let i = 0; i < normalized_config.num_layers; ++i) { + names.add(`${prefix}.${i}.key`); + names.add(`${prefix}.${i}.value`); + } + } + return names; +} +var PretrainedConfig = class _PretrainedConfig { + // NOTE: Typo in original + /** @type {string|null} */ + model_type = null; + /** @type {boolean} */ + is_encoder_decoder = false; + /** @type {number} */ + max_position_embeddings; + /** @type {TransformersJSConfig} */ + "transformers.js_config"; + /** + * Create a new `PretrainedConfig` from a parsed `config.json` object. + * @param {Object} configJSON The JSON of the config. + */ + constructor(configJSON) { + Object.assign(this, configJSON); + this.normalized_config = getNormalizedConfig(this); + } + /** + * Loads a pretrained config from the given `pretrained_model_name_or_path`. + * + * @param {string} pretrained_model_name_or_path The path to the pretrained config. + * @param {PretrainedOptions} options Additional options for loading the config. + * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`. + * + * @returns {Promise} A new instance of the `PretrainedConfig` class. + */ + static async from_pretrained(pretrained_model_name_or_path, { progress_callback = null, config = null, cache_dir = null, local_files_only = false, revision = "main" } = {}) { + if (config && !(config instanceof _PretrainedConfig)) { + config = new _PretrainedConfig(config); + } + const data = config ?? await loadConfig(pretrained_model_name_or_path, { + progress_callback, + config, + cache_dir, + local_files_only, + revision + }); + return new this(data); + } +}; +var AutoConfig = class { + /** @type {typeof PretrainedConfig.from_pretrained} */ + static async from_pretrained(...args) { + return PretrainedConfig.from_pretrained(...args); + } +}; -/** - * Generates a Hanning window of length M. - * See https://numpy.org/doc/stable/reference/generated/numpy.hanning.html for more information. - * - * @param {number} M The length of the Hanning window to generate. - * @returns {Float64Array} The generated Hanning window. - */ -function hanning(M) { - return generalized_cosine_window(M, 0.5); +// src/utils/model-loader.js +function resolveExternalDataFormat(config, fullName, fileName) { + if (!config) return 0; + if (typeof config === "object" && config !== null) { + if (config.hasOwnProperty(fullName)) return +config[fullName]; + if (config.hasOwnProperty(fileName)) return +config[fileName]; + return 0; + } + return +config; } - - -/** - * Generates a Hamming window of length M. - * See https://numpy.org/doc/stable/reference/generated/numpy.hamming.html for more information. - * - * @param {number} M The length of the Hamming window to generate. - * @returns {Float64Array} The generated Hamming window. - */ -function hamming(M) { - return generalized_cosine_window(M, 0.54); +function getExternalDataChunkNames(fullName, numChunks) { + const names = []; + for (let i = 0; i < numChunks; ++i) { + names.push(`${fullName}_data${i === 0 ? "" : "_" + i}`); + } + return names; +} +async function getCoreModelFile(pretrained_model_name_or_path, fileName, options, suffix) { + const baseName = `${fileName}${suffix}.onnx`; + const fullPath = `${options.subfolder ?? ""}/${baseName}`; + return await getModelFile(pretrained_model_name_or_path, fullPath, true, options, apis.IS_NODE_ENV); +} +async function getModelDataFiles(pretrained_model_name_or_path, fileName, suffix, options, use_external_data_format, session_options = {}) { + const baseName = `${fileName}${suffix}.onnx`; + const return_path = apis.IS_NODE_ENV; + let externalDataPromises = []; + const num_chunks = resolveExternalDataFormat(use_external_data_format, baseName, fileName); + if (num_chunks > 0) { + if (num_chunks > MAX_EXTERNAL_DATA_CHUNKS) { + throw new Error( + `The number of external data chunks (${num_chunks}) exceeds the maximum allowed value (${MAX_EXTERNAL_DATA_CHUNKS}).` + ); + } + const chunkNames = getExternalDataChunkNames(baseName, num_chunks); + for (const path of chunkNames) { + const fullPath = `${options.subfolder ?? ""}/${path}`; + externalDataPromises.push( + getModelFile(pretrained_model_name_or_path, fullPath, true, options, return_path).then( + (data) => data instanceof Uint8Array ? { path, data } : path + ) + ); + } + } else if (session_options.externalData !== void 0) { + externalDataPromises = session_options.externalData.map(async (ext) => { + if (typeof ext.data === "string") { + const ext_buffer = await getModelFile(pretrained_model_name_or_path, ext.data, true, options); + return { ...ext, data: ext_buffer }; + } + return ext; + }); + } + return Promise.all(externalDataPromises); } - -const HERTZ_TO_MEL_MAPPING = { - "htk": (/** @type {number} */ freq) => 2595.0 * Math.log10(1.0 + (freq / 700.0)), - "kaldi": (/** @type {number} */ freq) => 1127.0 * Math.log(1.0 + (freq / 700.0)), - "slaney": (/** @type {number} */ freq, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = 27.0 / Math.log(6.4)) => - freq >= min_log_hertz - ? min_log_mel + Math.log(freq / min_log_hertz) * logstep - : 3.0 * freq / 200.0, +// src/models/session.js +async function getSession(pretrained_model_name_or_path, fileName, options, cache_config = false, session_name = void 0) { + let custom_config = options.config?.["transformers.js_config"] ?? {}; + const selectedDevice = ( + /** @type {import("../utils/devices.js").DeviceType} */ + selectDevice(options.device ?? custom_config.device, fileName, { + warn: (msg) => logger.info(msg) + }) + ); + const executionProviders = deviceToExecutionProviders(selectedDevice); + const device_config = custom_config.device_config ?? {}; + if (device_config.hasOwnProperty(selectedDevice)) { + custom_config = { + ...custom_config, + ...device_config[selectedDevice] + }; + } + const selectedDtype = ( + /** @type {import("../utils/dtypes.js").DataType} */ + selectDtype(options.dtype ?? custom_config.dtype, fileName, selectedDevice, { + configDtype: custom_config.dtype, + warn: (msg) => logger.info(msg) + }) + ); + if (!DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(selectedDtype)) { + throw new Error(`Invalid dtype: ${selectedDtype}. Should be one of: ${Object.keys(DATA_TYPES).join(", ")}`); + } else if (selectedDevice === "webgpu" && // NOTE: Currently, we assume that the Native WebGPU EP always supports fp16. In future, we will add a check for this. + !apis.IS_NODE_ENV && selectedDtype === DATA_TYPES.fp16 && !await isWebGpuFp16Supported()) { + throw new Error(`The device (${selectedDevice}) does not support fp16.`); + } + const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype]; + const session_options = { ...options.session_options }; + session_options.executionProviders ??= executionProviders; + const free_dimension_overrides = custom_config.free_dimension_overrides; + if (free_dimension_overrides) { + session_options.freeDimensionOverrides ??= free_dimension_overrides; + } else if (selectedDevice.startsWith("webnn") && !session_options.freeDimensionOverrides) { + logger.warn( + `WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${selectedDevice}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.` + ); + } + const bufferOrPathPromise = getCoreModelFile(pretrained_model_name_or_path, fileName, options, suffix); + const use_external_data_format = options.use_external_data_format ?? custom_config.use_external_data_format; + const externalData = await getModelDataFiles( + pretrained_model_name_or_path, + fileName, + suffix, + options, + use_external_data_format, + session_options + ); + if (externalData.length > 0 && (!apis.IS_NODE_ENV || externalData.some((data) => typeof data !== "string"))) { + session_options.externalData = externalData; + } + if (cache_config && selectedDevice === "webgpu") { + const names = getCacheNames(options.config, { + prefix: "present", + session_name + }); + if (names.size > 0 && !isONNXProxy()) { + const preferredOutputLocation = {}; + for (const key of names) { + preferredOutputLocation[key] = "gpu-buffer"; + } + session_options.preferredOutputLocation = preferredOutputLocation; + } + } + const buffer_or_path = await bufferOrPathPromise; + const session_config = { + dtype: selectedDtype, + device: selectedDevice + }; + return { buffer_or_path, session_options, session_config }; +} +async function constructSessions(pretrained_model_name_or_path, names, options, cache_sessions = void 0) { + return Object.fromEntries( + await Promise.all( + Object.keys(names).map(async (name) => { + const cache_config = cache_sessions?.[name] ?? false; + const { buffer_or_path, session_options, session_config } = await getSession( + pretrained_model_name_or_path, + names[name], + options, + cache_config, + name + ); + const session = await createInferenceSession(buffer_or_path, session_options, session_config); + return [name, session]; + }) + ) + ); } - -/** - * @template {Float32Array|Float64Array|number} T - * @param {T} freq - * @param {string} [mel_scale] - * @returns {T} - */ -function hertz_to_mel(freq, mel_scale = "htk") { - const fn = HERTZ_TO_MEL_MAPPING[mel_scale]; - if (!fn) { - throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); +function replaceTensors(obj) { + for (let prop in obj) { + if (isONNXTensor(obj[prop])) { + obj[prop] = new Tensor3(obj[prop]); + } else if (typeof obj[prop] === "object") { + replaceTensors(obj[prop]); } - - // @ts-expect-error ts(2322) - return typeof freq === 'number' ? fn(freq) : freq.map(x => fn(x)); + } + return obj; } - -const MEL_TO_HERTZ_MAPPING = { - "htk": (/** @type {number} */ mels) => 700.0 * (10.0 ** (mels / 2595.0) - 1.0), - "kaldi": (/** @type {number} */ mels) => 700.0 * (Math.exp(mels / 1127.0) - 1.0), - "slaney": (/** @type {number} */ mels, min_log_hertz = 1000.0, min_log_mel = 15.0, logstep = Math.log(6.4) / 27.0) => mels >= min_log_mel - ? min_log_hertz * Math.exp(logstep * (mels - min_log_mel)) - : 200.0 * mels / 3.0, +async function sessionRun(session, inputs) { + const checkedInputs = validateInputs(session, inputs); + try { + const ortFeed = Object.fromEntries( + Object.entries(checkedInputs).map(([k, v]) => { + const tensor = ( + /** @type {any} */ + v.ort_tensor + ); + if (apis.IS_NODE_ENV) { + if (typeof Float16Array !== "undefined" && tensor.cpuData instanceof Float16Array) { + tensor.cpuData = new Uint16Array(tensor.cpuData.buffer); + } + } + return [k, tensor]; + }) + ); + const output = await runInferenceSession(session, ortFeed); + return replaceTensors(output); + } catch (e) { + const formatted = Object.fromEntries( + Object.entries(checkedInputs).map(([k, tensor]) => { + const unpacked = { + type: tensor.type, + dims: tensor.dims, + location: tensor.location + }; + if (unpacked.location !== "gpu-buffer") { + unpacked.data = tensor.data; + } + return [k, unpacked]; + }) + ); + logger.error(`An error occurred during model execution: "${e}".`); + logger.error("Inputs given to model:", formatted); + throw e; + } +} +function validateInputs(session, inputs) { + const checkedInputs = /* @__PURE__ */ Object.create(null); + const missingInputs = []; + for (const inputName of session.inputNames) { + const tensor = inputs[inputName]; + if (!(tensor instanceof Tensor3)) { + missingInputs.push(inputName); + continue; + } + checkedInputs[inputName] = isONNXProxy() ? tensor.clone() : tensor; + } + if (missingInputs.length > 0) { + throw new Error( + `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.` + ); + } + const numInputsProvided = Object.keys(inputs).length; + const numInputsNeeded = session.inputNames.length; + if (numInputsProvided > numInputsNeeded) { + let ignored = Object.keys(inputs).filter((inputName) => !session.inputNames.includes(inputName)); + logger.warn( + `WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".` + ); + } + return checkedInputs; } -/** - * @template {Float32Array|Float64Array|number} T - * @param {T} mels - * @param {string} [mel_scale] - * @returns {T} - */ -function mel_to_hertz(mels, mel_scale = "htk") { - const fn = MEL_TO_HERTZ_MAPPING[mel_scale]; - if (!fn) { - throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".'); +// src/models/modeling_outputs.js +var ModelOutput = class { +}; +var BaseModelOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.last_hidden_state Sequence of hidden-states at the output of the last layer of the model. + * @param {Tensor} [output.hidden_states] Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. + * @param {Tensor} [output.attentions] Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + */ + constructor({ last_hidden_state, hidden_states = null, attentions = null }) { + super(); + this.last_hidden_state = last_hidden_state; + this.hidden_states = hidden_states; + this.attentions = attentions; + } +}; +var SequenceClassifierOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax). + * @param {Record} [output.attentions] Object of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. + * Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. + */ + constructor({ logits, ...attentions }) { + super(); + this.logits = logits; + const attentions_list = Object.values(attentions); + if (attentions_list.length > 0) { + this.attentions = attentions_list; } + } +}; +var TokenClassifierOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification scores (before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +}; +var MaskedLMOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +}; +var QuestionAnsweringModelOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.start_logits Span-start scores (before SoftMax). + * @param {Tensor} output.end_logits Span-end scores (before SoftMax). + */ + constructor({ start_logits, end_logits }) { + super(); + this.start_logits = start_logits; + this.end_logits = end_logits; + } +}; +var CausalLMOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + */ + constructor({ logits }) { + super(); + this.logits = logits; + } +}; +var CausalLMOutputWithPast = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax). + * @param {Tensor} output.past_key_values Contains pre-computed hidden-states (key and values in the self-attention blocks) + * that can be used (see `past_key_values` input) to speed up sequential decoding. + */ + constructor({ logits, past_key_values }) { + super(); + this.logits = logits; + this.past_key_values = past_key_values; + } +}; +var Seq2SeqLMOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model. + * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model. + * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. + * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. + */ + constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) { + super(); + this.logits = logits; + this.past_key_values = past_key_values; + this.encoder_outputs = encoder_outputs; + this.decoder_attentions = decoder_attentions; + this.cross_attentions = cross_attentions; + } +}; +var ImageMattingOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`. + */ + constructor({ alphas }) { + super(); + this.alphas = alphas; + } +}; - // @ts-expect-error ts(2322) - return typeof mels === 'number' ? fn(mels) : mels.map(x => fn(x)); -} - -/** -* Creates a triangular filter bank. -* -* Adapted from torchaudio and librosa. -* -* @param {Float64Array} fft_freqs Discrete frequencies of the FFT bins in Hz, of shape `(num_frequency_bins,)`. -* @param {Float64Array} filter_freqs Center frequencies of the triangular filters to create, in Hz, of shape `(num_mel_filters,)`. -* @returns {number[][]} of shape `(num_frequency_bins, num_mel_filters)`. -*/ -function _create_triangular_filter_bank(fft_freqs, filter_freqs) { - const filter_diff = Float64Array.from( - { length: filter_freqs.length - 1 }, - (_, i) => filter_freqs[i + 1] - filter_freqs[i] - ); - - const slopes = Array.from({ - length: fft_freqs.length - }, () => new Array(filter_freqs.length)); - - for (let j = 0; j < fft_freqs.length; ++j) { - const slope = slopes[j]; - for (let i = 0; i < filter_freqs.length; ++i) { - slope[i] = filter_freqs[i] - fft_freqs[j]; - } +// src/generation/logits_process.js +var LogitsProcessor = class extends Callable { + /** + * Apply the processor to the input logits. + * + * @abstract + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits to process. + * @throws {Error} Throws an error if `_call` is not implemented in the subclass. + */ + _call(input_ids, logits) { + throw Error("`_call` should be implemented in a subclass"); + } +}; +var LogitsWarper = class extends Callable { + /** + * Apply the processor to the input logits. + * + * @abstract + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits to process. + * @throws {Error} Throws an error if `_call` is not implemented in the subclass. + */ + _call(input_ids, logits) { + throw Error("`_call` should be implemented in a subclass"); + } +}; +var LogitsProcessorList = class extends Callable { + /** + * Constructs a new instance of `LogitsProcessorList`. + */ + constructor() { + super(); + this.processors = []; + } + /** + * Adds a new logits processor to the list. + * + * @param {LogitsProcessor} item The logits processor function to add. + */ + push(item) { + this.processors.push(item); + } + /** + * Adds multiple logits processors to the list. + * + * @param {LogitsProcessor[]} items The logits processor functions to add. + */ + extend(items) { + this.processors.push(...items); + } + /** + * Applies all logits processors in the list to a batch of logits, modifying them in-place. + * + * @param {bigint[][]} input_ids The input IDs for the language model. + * @param {Tensor} logits + */ + _call(input_ids, logits) { + let toReturn = logits; + for (const processor of this.processors) { + toReturn = processor(input_ids, toReturn); } - - const numFreqs = filter_freqs.length - 2; - const ret = Array.from({ length: numFreqs }, () => new Array(fft_freqs.length)); - - for (let j = 0; j < fft_freqs.length; ++j) { // 201 - const slope = slopes[j]; - for (let i = 0; i < numFreqs; ++i) { // 80 - const down = -slope[i] / filter_diff[i]; - const up = slope[i + 2] / filter_diff[i + 1]; - ret[i][j] = Math.max(0, Math.min(down, up)); + return toReturn; + } + [Symbol.iterator]() { + return this.processors.values(); + } +}; +var ForcedBOSTokenLogitsProcessor = class extends LogitsProcessor { + /** + * Create a ForcedBOSTokenLogitsProcessor. + * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced. + */ + constructor(bos_token_id) { + super(); + this.bos_token_id = bos_token_id; + } + /** + * Apply the BOS token forcing to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with BOS token forcing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length === 1) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + batch_logits_data.fill(-Infinity); + batch_logits_data[this.bos_token_id] = 0; + } + } + return logits; + } +}; +var ForcedEOSTokenLogitsProcessor = class extends LogitsProcessor { + /** + * Create a ForcedEOSTokenLogitsProcessor. + * @param {number} max_length The maximum length of the sequence to be generated. + * @param {number|number[]} eos_token_id The ID or IDs of the *end-of-sequence* token. + */ + constructor(max_length, eos_token_id) { + super(); + this.max_length = max_length; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply the processor to input_ids and logits. + * + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits tensor. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length === this.max_length - 1) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + batch_logits_data.fill(-Infinity); + for (const eos_token of this.eos_token_id) { + batch_logits_data[eos_token] = 0; } + } } - return ret; -} - -/** - * Return evenly spaced numbers over a specified interval. - * @param {number} start The starting value of the sequence. - * @param {number} end The end value of the sequence. - * @param {number} num Number of samples to generate. - * @returns `num` evenly spaced samples, calculated over the interval `[start, stop]`. - */ -function linspace(start, end, num) { - const step = (end - start) / (num - 1); - return Float64Array.from({ length: num }, (_, i) => start + step * i); -} - -/** - * Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and - * various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters - * are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these - * features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency. - * @param {number} num_frequency_bins Number of frequency bins (should be the same as `n_fft // 2 + 1` - * where `n_fft` is the size of the Fourier Transform used to compute the spectrogram). - * @param {number} num_mel_filters Number of mel filters to generate. - * @param {number} min_frequency Lowest frequency of interest in Hz. - * @param {number} max_frequency Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`. - * @param {number} sampling_rate Sample rate of the audio waveform. - * @param {string} [norm] If `"slaney"`, divide the triangular mel weights by the width of the mel band (area normalization). - * @param {string} [mel_scale] The mel frequency scale to use, `"htk"` or `"slaney"`. - * @param {boolean} [triangularize_in_mel_space] If this option is enabled, the triangular filter is applied in mel space rather than frequency space. - * This should be set to `true` in order to get the same results as `torchaudio` when computing mel filters. - * @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`). - * This is a projection matrix to go from a spectrogram to a mel spectrogram. - */ -function mel_filter_bank( - num_frequency_bins, - num_mel_filters, - min_frequency, - max_frequency, - sampling_rate, - norm = null, - mel_scale = "htk", - triangularize_in_mel_space = false, -) { - if (norm !== null && norm !== "slaney") { - throw new Error('norm must be one of null or "slaney"'); - } - - if (num_frequency_bins < 2) { - throw new Error(`Require num_frequency_bins: ${num_frequency_bins} >= 2`); - } - - if (min_frequency > max_frequency) { - throw new Error(`Require min_frequency: ${min_frequency} <= max_frequency: ${max_frequency}`); - } - - const mel_min = hertz_to_mel(min_frequency, mel_scale); - const mel_max = hertz_to_mel(max_frequency, mel_scale); - const mel_freqs = linspace(mel_min, mel_max, num_mel_filters + 2); - - let filter_freqs = mel_to_hertz(mel_freqs, mel_scale); - let fft_freqs; // frequencies of FFT bins in Hz - - if (triangularize_in_mel_space) { - const fft_bin_width = sampling_rate / ((num_frequency_bins - 1) * 2); - fft_freqs = hertz_to_mel(Float64Array.from({ length: num_frequency_bins }, (_, i) => i * fft_bin_width), mel_scale); - filter_freqs = mel_freqs; - } else { - fft_freqs = linspace(0, Math.floor(sampling_rate / 2), num_frequency_bins); + return logits; + } +}; +var SuppressTokensLogitsProcessor = class extends LogitsProcessor { + /** + * Create a SuppressTokensLogitsProcessor. + * @param {number[]} suppress_tokens The IDs of the tokens to suppress. + */ + constructor(suppress_tokens) { + super(); + this.suppress_tokens = suppress_tokens; + } + /** + * Suppress the specified tokens by setting their logits to -Infinity. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The modified logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const token_id of this.suppress_tokens) { + batch_logits_data[token_id] = -Infinity; + } } - - const mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs); - - if (norm !== null && norm === "slaney") { - // Slaney-style mel is scaled to be approx constant energy per channel - for (let i = 0; i < num_mel_filters; ++i) { - const filter = mel_filters[i]; - const enorm = 2.0 / (filter_freqs[i + 2] - filter_freqs[i]); - for (let j = 0; j < num_frequency_bins; ++j) { - // Apply this enorm to all frequency bins - filter[j] *= enorm; - } + return logits; + } +}; +var SuppressTokensAtBeginLogitsProcessor = class extends LogitsProcessor { + /** + * Create a SuppressTokensAtBeginLogitsProcessor. + * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress. + * @param {number} begin_index The number of tokens to generate before suppressing tokens. + */ + constructor(begin_suppress_tokens, begin_index) { + super(); + this.begin_suppress_tokens = begin_suppress_tokens; + this.begin_index = begin_index; + } + /** + * Apply the BOS token forcing to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with BOS token forcing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length === this.begin_index) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const token_id of this.begin_suppress_tokens) { + batch_logits_data[token_id] = -Infinity; } + } } - - // TODO warn if there is a zero row - - return mel_filters; - -} - -/** - * @template {Float32Array|Float64Array} T - * Pads an array with a reflected version of itself on both ends. - * @param {T} array The array to pad. - * @param {number} left The amount of padding to add to the left. - * @param {number} right The amount of padding to add to the right. - * @returns {T} The padded array. - */ -function padReflect(array, left, right) { - // @ts-ignore - const padded = new array.constructor(array.length + left + right); - const w = array.length - 1; - - for (let i = 0; i < array.length; ++i) { - padded[left + i] = array[i]; + return logits; + } +}; +var WhisperTimeStampLogitsProcessor = class extends LogitsProcessor { + /** + * Constructs a new WhisperTimeStampLogitsProcessor. + * @param {import('../models/whisper/generation_whisper.js').WhisperGenerationConfig} generate_config The config object passed to the `generate()` method of a transformer model. + * @param {number[]} init_tokens The initial tokens of the input sequence. + */ + constructor(generate_config, init_tokens) { + super(); + this.eos_token_id = Array.isArray(generate_config.eos_token_id) ? generate_config.eos_token_id[0] : generate_config.eos_token_id; + this.no_timestamps_token_id = generate_config.no_timestamps_token_id; + this.timestamp_begin = this.no_timestamps_token_id + 1; + this.begin_index = init_tokens.length; + if (init_tokens.at(-1) === this.no_timestamps_token_id) { + this.begin_index -= 1; + } + this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index; + } + /** + * Modify the logits to handle timestamp tokens. + * @param {bigint[][]} input_ids The input sequence of tokens. + * @param {Tensor} logits The logits output by the model. + * @returns {Tensor} The modified logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + batch_logits_data[this.no_timestamps_token_id] = -Infinity; + if (input_ids[i].length === this.begin_index) { + batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity); + continue; + } + const seq = input_ids[i].slice(this.begin_index); + const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin; + const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin; + if (last_was_timestamp) { + if (penultimate_was_timestamp) { + batch_logits_data.subarray(this.timestamp_begin).fill(-Infinity); + } else { + batch_logits_data.subarray(0, this.eos_token_id).fill(-Infinity); + } + } + if (input_ids[i].length === this.begin_index && this.max_initial_timestamp_index !== null) { + const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index; + batch_logits_data.subarray(last_allowed + 1).fill(-Infinity); + } + const logprobs = log_softmax(batch_logits_data); + const timestamp_logprob = Math.log( + logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b) + ); + const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0]; + if (timestamp_logprob > max_text_token_logprob) { + batch_logits_data.subarray(0, this.timestamp_begin).fill(-Infinity); + } } - - for (let i = 1; i <= left; ++i) { - padded[left - i] = array[(0,_core_js__WEBPACK_IMPORTED_MODULE_2__.calculateReflectOffset)(i, w)]; - } - - for (let i = 1; i <= right; ++i) { - padded[w + left + i] = array[(0,_core_js__WEBPACK_IMPORTED_MODULE_2__.calculateReflectOffset)(w - i, w)]; - } - - return padded; -} - -/** - * Helper function to compute `amplitude_to_db` and `power_to_db`. - * @template {Float32Array|Float64Array} T - * @param {T} spectrogram - * @param {number} factor - * @param {number} reference - * @param {number} min_value - * @param {number} db_range - * @returns {T} - */ -function _db_conversion_helper(spectrogram, factor, reference, min_value, db_range) { - if (reference <= 0) { - throw new Error('reference must be greater than zero'); - } - - if (min_value <= 0) { - throw new Error('min_value must be greater than zero'); - } - - reference = Math.max(min_value, reference); - - const logReference = Math.log10(reference); - for (let i = 0; i < spectrogram.length; ++i) { - spectrogram[i] = factor * Math.log10(Math.max(min_value, spectrogram[i]) - logReference) - } - - if (db_range !== null) { - if (db_range <= 0) { - throw new Error('db_range must be greater than zero'); - } - const maxValue = (0,_maths_js__WEBPACK_IMPORTED_MODULE_1__.max)(spectrogram)[0] - db_range; - for (let i = 0; i < spectrogram.length; ++i) { - spectrogram[i] = Math.max(spectrogram[i], maxValue); - } - } - - return spectrogram; -} - -/** - * Converts an amplitude spectrogram to the decibel scale. This computes `20 * log10(spectrogram / reference)`, - * using basic logarithm properties for numerical stability. NOTE: Operates in-place. - * - * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a - * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it. - * This means that large variations in energy may not sound all that different if the sound is loud to begin with. - * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear. - * - * @template {Float32Array|Float64Array} T - * @param {T} spectrogram The input amplitude (mel) spectrogram. - * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. - * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero. - * @param {number} [min_value=1e-5] The spectrogram will be clipped to this minimum value before conversion to decibels, - * to avoid taking `log(0)`. The default of `1e-5` corresponds to a minimum of -100 dB. Must be greater than zero. - * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the - * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero. - * @returns {T} The modified spectrogram in decibels. - */ -function amplitude_to_db(spectrogram, reference = 1.0, min_value = 1e-5, db_range = null) { - return _db_conversion_helper(spectrogram, 20.0, reference, min_value, db_range); -} - -/** - * Converts a power spectrogram to the decibel scale. This computes `10 * log10(spectrogram / reference)`, - * using basic logarithm properties for numerical stability. NOTE: Operates in-place. - * - * The motivation behind applying the log function on the (mel) spectrogram is that humans do not hear loudness on a - * linear scale. Generally to double the perceived volume of a sound we need to put 8 times as much energy into it. - * This means that large variations in energy may not sound all that different if the sound is loud to begin with. - * This compression operation makes the (mel) spectrogram features match more closely what humans actually hear. - * - * Based on the implementation of `librosa.power_to_db`. - * - * @template {Float32Array|Float64Array} T - * @param {T} spectrogram The input power (mel) spectrogram. Note that a power spectrogram has the amplitudes squared! - * @param {number} [reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. - * For example, use `np.max(spectrogram)` to set the loudest part to 0 dB. Must be greater than zero. - * @param {number} [min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, - * to avoid taking `log(0)`. The default of `1e-10` corresponds to a minimum of -100 dB. Must be greater than zero. - * @param {number} [db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the - * difference between the peak value and the smallest value will never be more than 80 dB. Must be greater than zero. - * @returns {T} The modified spectrogram in decibels. - */ -function power_to_db(spectrogram, reference = 1.0, min_value = 1e-10, db_range = null) { - return _db_conversion_helper(spectrogram, 10.0, reference, min_value, db_range); -} - -/** - * Calculates a spectrogram over one waveform using the Short-Time Fourier Transform. - * - * This function can create the following kinds of spectrograms: - * - amplitude spectrogram (`power = 1.0`) - * - power spectrogram (`power = 2.0`) - * - complex-valued spectrogram (`power = None`) - * - log spectrogram (use `log_mel` argument) - * - mel spectrogram (provide `mel_filters`) - * - log-mel spectrogram (provide `mel_filters` and `log_mel`) - * - * In this implementation, the window is assumed to be zero-padded to have the same size as the analysis frame. - * A padded window can be obtained from `window_function()`. The FFT input buffer may be larger than the analysis frame, - * typically the next power of two. - * - * @param {Float32Array|Float64Array} waveform The input waveform of shape `(length,)`. This must be a single real-valued, mono waveform. - * @param {Float32Array|Float64Array} window The windowing function to apply of shape `(frame_length,)`, including zero-padding if necessary. The actual window length may be - * shorter than `frame_length`, but we're assuming the array has already been zero-padded. - * @param {number} frame_length The length of the analysis frames in samples (a.k.a., `fft_length`). - * @param {number} hop_length The stride between successive analysis frames in samples. - * @param {Object} options - * @param {number} [options.fft_length=null] The size of the FFT buffer in samples. This determines how many frequency bins the spectrogram will have. - * For optimal speed, this should be a power of two. If `null`, uses `frame_length`. - * @param {number} [options.power=1.0] If 1.0, returns the amplitude spectrogram. If 2.0, returns the power spectrogram. If `null`, returns complex numbers. - * @param {boolean} [options.center=true] Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `false`, frame - * `t` will start at time `t * hop_length`. - * @param {string} [options.pad_mode="reflect"] Padding mode used when `center` is `true`. Possible values are: `"constant"` (pad with zeros), - * `"edge"` (pad with edge values), `"reflect"` (pads with mirrored values). - * @param {boolean} [options.onesided=true] If `true`, only computes the positive frequencies and returns a spectrogram containing `fft_length // 2 + 1` - * frequency bins. If `false`, also computes the negative frequencies and returns `fft_length` frequency bins. - * @param {number} [options.preemphasis=null] Coefficient for a low-pass filter that applies pre-emphasis before the DFT. - * @param {boolean} [options.preemphasis_htk_flavor=true] Whether to apply the pre-emphasis filter in the HTK flavor. - * @param {number[][]} [options.mel_filters=null] The mel filter bank of shape `(num_freq_bins, num_mel_filters)`. - * If supplied, applies this filter bank to create a mel spectrogram. - * @param {number} [options.mel_floor=1e-10] Minimum value of mel frequency banks. - * @param {string} [options.log_mel=null] How to convert the spectrogram to log scale. Possible options are: - * `null` (don't convert), `"log"` (take the natural logarithm) `"log10"` (take the base-10 logarithm), `"dB"` (convert to decibels). - * Can only be used when `power` is not `null`. - * @param {number} [options.reference=1.0] Sets the input spectrogram value that corresponds to 0 dB. For example, use `max(spectrogram)[0]` to set - * the loudest part to 0 dB. Must be greater than zero. - * @param {number} [options.min_value=1e-10] The spectrogram will be clipped to this minimum value before conversion to decibels, to avoid taking `log(0)`. - * For a power spectrogram, the default of `1e-10` corresponds to a minimum of -100 dB. For an amplitude spectrogram, the value `1e-5` corresponds to -100 dB. - * Must be greater than zero. - * @param {number} [options.db_range=null] Sets the maximum dynamic range in decibels. For example, if `db_range = 80`, the difference between the - * peak value and the smallest value will never be more than 80 dB. Must be greater than zero. - * @param {boolean} [options.remove_dc_offset=null] Subtract mean from waveform on each frame, applied before pre-emphasis. This should be set to `true` in - * order to get the same results as `torchaudio.compliance.kaldi.fbank` when computing mel filters. - * @param {number} [options.max_num_frames=null] If provided, limits the number of frames to compute to this value. - * @param {number} [options.min_num_frames=null] If provided, ensures the number of frames to compute is at least this value. - * @param {boolean} [options.do_pad=true] If `true`, pads the output spectrogram to have `max_num_frames` frames. - * @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`. - * @returns {Promise} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram). - */ -async function spectrogram( - waveform, - window, - frame_length, - hop_length, - { - fft_length = null, - power = 1.0, - center = true, - pad_mode = "reflect", - onesided = true, - preemphasis = null, - preemphasis_htk_flavor = true, - mel_filters = null, - mel_floor = 1e-10, - log_mel = null, - reference = 1.0, - min_value = 1e-10, - db_range = null, - remove_dc_offset = null, - - // Custom parameters for efficiency reasons - min_num_frames = null, - max_num_frames = null, - do_pad = true, - transpose = false, - } = {} -) { - const window_length = window.length; - if (fft_length === null) { - fft_length = frame_length; - } - if (frame_length > fft_length) { - throw Error(`frame_length (${frame_length}) may not be larger than fft_length (${fft_length})`) - } - - if (window_length !== frame_length) { - throw new Error(`Length of the window (${window_length}) must equal frame_length (${frame_length})`); - } - - if (hop_length <= 0) { - throw new Error("hop_length must be greater than zero"); - } - - if (power === null && mel_filters !== 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." - ); + return logits; + } +}; +var NoRepeatNGramLogitsProcessor = class extends LogitsProcessor { + /** + * Create a NoRepeatNGramLogitsProcessor. + * @param {number} no_repeat_ngram_size The no-repeat n-gram size. All n-grams of this size can only occur once. + */ + constructor(no_repeat_ngram_size) { + super(); + this.no_repeat_ngram_size = no_repeat_ngram_size; + } + /** + * Generate n-grams from a sequence of token IDs. + * @param {bigint[]} prevInputIds List of previous input IDs. + * @returns {Map} Map of generated n-grams + */ + getNgrams(prevInputIds) { + const curLen = prevInputIds.length; + const ngrams = []; + for (let j2 = 0; j2 < curLen + 1 - this.no_repeat_ngram_size; ++j2) { + const ngram = []; + for (let k = 0; k < this.no_repeat_ngram_size; ++k) { + ngram.push(prevInputIds[j2 + k]); + } + ngrams.push(ngram.map(Number)); } - - if (!preemphasis_htk_flavor) { - throw new Error( - "`preemphasis_htk_flavor=false` is not currently supported." - ); + const generatedNgram = /* @__PURE__ */ new Map(); + for (const ngram of ngrams) { + const prevNgram = ngram.slice(0, ngram.length - 1); + const prevNgramKey = JSON.stringify(prevNgram); + const prevNgramValue = generatedNgram.get(prevNgramKey) ?? []; + prevNgramValue.push(ngram[ngram.length - 1]); + generatedNgram.set(prevNgramKey, prevNgramValue); } - - if (center) { - if (pad_mode !== 'reflect') { - throw new Error(`pad_mode="${pad_mode}" not implemented yet.`) - } - const half_window = Math.floor((fft_length - 1) / 2) + 1; - waveform = padReflect(waveform, half_window, half_window); + return generatedNgram; + } + /** + * Generate n-grams from a sequence of token IDs. + * @param {Map} bannedNgrams Map of banned n-grams + * @param {bigint[]} prevInputIds List of previous input IDs. + * @returns {number[]} Map of generated n-grams + */ + getGeneratedNgrams(bannedNgrams, prevInputIds) { + const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length); + const banned = bannedNgrams.get(JSON.stringify(ngramIdx.map(Number))) ?? []; + return banned; + } + /** + * Calculate banned n-gram tokens + * @param {bigint[]} prevInputIds List of previous input IDs. + * @returns {number[]} Map of generated n-grams + */ + calcBannedNgramTokens(prevInputIds) { + const bannedTokens = []; + if (prevInputIds.length + 1 < this.no_repeat_ngram_size) { + return bannedTokens; + } else { + const generatedNgrams = this.getNgrams(prevInputIds); + const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds); + return bannedTokens2; } - - // split waveform into frames of frame_length size - let num_frames = Math.floor(1 + Math.floor((waveform.length - frame_length) / hop_length)) - if (min_num_frames !== null && num_frames < min_num_frames) { - num_frames = min_num_frames + } + /** + * Apply the no-repeat n-gram processor to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with no-repeat n-gram processing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + const bannedTokens = this.calcBannedNgramTokens(input_ids[i]); + for (const token of bannedTokens) { + batch_logits_data[token] = -Infinity; + } } - const num_frequency_bins = onesided ? Math.floor(fft_length / 2) + 1 : fft_length - - let d1 = num_frames; - let d1Max = num_frames; - - // If maximum number of frames is provided, we must either pad or truncate - if (max_num_frames !== null) { - if (max_num_frames > num_frames) { // input is too short, so we pad - if (do_pad) { - d1Max = max_num_frames; - } - } else { // input is too long, so we truncate - d1Max = d1 = max_num_frames; + return logits; + } +}; +var RepetitionPenaltyLogitsProcessor = class extends LogitsProcessor { + /** + * Create a RepetitionPenaltyLogitsProcessor. + * @param {number} penalty Penalty applied to repeated tokens. + * - 1.0 means no penalty. Above 1.0 penalizes previously generated tokens. + * - Between 0.0 and 1.0 rewards previously generated tokens. + */ + constructor(penalty) { + super(); + this.penalty = penalty; + } + /** + * Apply the repetition penalty to the logits. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The logits with repetition penalty processing. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const input_id of new Set(input_ids[i])) { + const token = Number(input_id); + if (batch_logits_data[token] < 0) { + batch_logits_data[token] *= this.penalty; + } else { + batch_logits_data[token] /= this.penalty; } + } } - - // Preallocate arrays to store output. - const fft = new _maths_js__WEBPACK_IMPORTED_MODULE_1__.FFT(fft_length); - const inputBuffer = new Float64Array(fft_length); - const outputBuffer = new Float64Array(fft.outputBufferSize); - const transposedMagnitudeData = new Float32Array(num_frequency_bins * d1Max); - - for (let i = 0; i < d1; ++i) { - // Populate buffer with waveform data - const offset = i * hop_length; - const buffer_size = Math.min(waveform.length - offset, frame_length); - if (buffer_size !== frame_length) { - // The full buffer is not needed, so we need to reset it (avoid overflow from previous iterations) - // NOTE: We don't need to reset the buffer if it's full since we overwrite the first - // `frame_length` values and the rest (`fft_length - frame_length`) remains zero. - inputBuffer.fill(0, 0, frame_length); - } - - for (let j = 0; j < buffer_size; ++j) { - inputBuffer[j] = waveform[offset + j]; - } - - if (remove_dc_offset) { - let sum = 0; - for (let j = 0; j < buffer_size; ++j) { - sum += inputBuffer[j]; - } - const mean = sum / buffer_size; - for (let j = 0; j < buffer_size; ++j) { - inputBuffer[j] -= mean; - } - } - - if (preemphasis !== null) { - // Done in reverse to avoid copies and destructive modification - for (let j = buffer_size - 1; j >= 1; --j) { - inputBuffer[j] -= preemphasis * inputBuffer[j - 1]; - } - inputBuffer[0] *= 1 - preemphasis; - } - - // Apply window function - for (let j = 0; j < window.length; ++j) { - inputBuffer[j] *= window[j]; + return logits; + } +}; +var MinLengthLogitsProcessor = class extends LogitsProcessor { + /** + * Create a MinLengthLogitsProcessor. + * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID or IDs of the end-of-sequence token. + */ + constructor(min_length, eos_token_id) { + super(); + this.min_length = min_length; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + if (input_ids[i].length < this.min_length) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const eos_token of this.eos_token_id) { + batch_logits_data[eos_token] = -Infinity; } - - fft.realTransform(outputBuffer, inputBuffer); - - // compute magnitudes - for (let j = 0; j < num_frequency_bins; ++j) { - const j2 = j << 1; - - // NOTE: We transpose the data here to avoid doing it later - transposedMagnitudeData[j * d1Max + i] = outputBuffer[j2] ** 2 + outputBuffer[j2 + 1] ** 2; + } + } + return logits; + } +}; +var MinNewTokensLengthLogitsProcessor = class extends LogitsProcessor { + /** + * Create a MinNewTokensLengthLogitsProcessor. + * @param {number} prompt_length_to_skip The input tokens length. + * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity. + * @param {number|number[]} eos_token_id The ID or IDs of the end-of-sequence token. + */ + constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) { + super(); + this.prompt_length_to_skip = prompt_length_to_skip; + this.min_new_tokens = min_new_tokens; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const new_tokens_length = input_ids[i].length - this.prompt_length_to_skip; + if (new_tokens_length < this.min_new_tokens) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + for (const eos_token of this.eos_token_id) { + batch_logits_data[eos_token] = -Infinity; } + } } - - if (power !== null && power !== 2) { - // slight optimization to not sqrt - const pow = power / 2; // we use 2 since we already squared - for (let i = 0; i < transposedMagnitudeData.length; ++i) { - transposedMagnitudeData[i] **= pow; + return logits; + } +}; +var NoBadWordsLogitsProcessor = class extends LogitsProcessor { + /** + * Create a `NoBadWordsLogitsProcessor`. + * @param {number[][]} bad_words_ids List of token ID sequences that are not allowed to be generated. + * @param {number|number[]} eos_token_id The ID of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + constructor(bad_words_ids, eos_token_id) { + super(); + this.bad_words_ids = bad_words_ids; + this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id]; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + for (let i = 0; i < input_ids.length; ++i) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits[i].data + ); + const ids = input_ids[i]; + for (const bad_word_ids of this.bad_words_ids) { + if (ids.length < bad_word_ids.length - 1) continue; + let mark = true; + for (let j2 = 1; j2 <= bad_word_ids.length - 1; ++j2) { + if (bad_word_ids.at(-j2 - 1) != ids.at(-j2)) { + mark = false; + break; + } + } + if (mark) { + batch_logits_data[bad_word_ids.at(-1)] = -Infinity; } + } } - - // TODO: What if `mel_filters` is null? - const num_mel_filters = mel_filters.length; - - // Perform matrix muliplication: - // mel_spec = mel_filters @ magnitudes.T - // - mel_filters.shape=(80, 201) - // - magnitudes.shape=(3000, 201) => magnitudes.T.shape=(201, 3000) - // - mel_spec.shape=(80, 3000) - let mel_spec = await (0,_tensor_js__WEBPACK_IMPORTED_MODULE_4__.matmul)( - // TODO: Make `mel_filters` a Tensor during initialization - new _tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', mel_filters.flat(), [num_mel_filters, num_frequency_bins]), - new _tensor_js__WEBPACK_IMPORTED_MODULE_4__.Tensor('float32', transposedMagnitudeData, [num_frequency_bins, d1Max]), + return logits; + } +}; +var ClassifierFreeGuidanceLogitsProcessor = class extends LogitsProcessor { + /** + * Create a `ClassifierFreeGuidanceLogitsProcessor`. + * @param {number} guidance_scale The guidance scale for classifier-free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. + * Higher guidance scale encourages the model to generate samples that are more closely tied to the input + * prompt, usually at the expense of poorer quality. + */ + constructor(guidance_scale) { + super(); + if (guidance_scale <= 1) { + throw new Error( + `Require guidance scale >1 to use the classifier-free guidance processor, got guidance scale ${guidance_scale}.` + ); + } + this.guidance_scale = guidance_scale; + } + /** + * Apply logit processor. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + if (logits.dims[0] !== 2 * input_ids.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 ${logits.dims[0]} for the logits and ${input_ids.length} for the input ids.` + ); + } + const unguided_bsz = input_ids.length; + const cond_logits = logits.slice([0, unguided_bsz], null); + const uncond_logits = logits.slice([unguided_bsz, logits.dims[0]], null); + for (let i = 0; i < uncond_logits.data.length; ++i) { + uncond_logits.data[i] += (cond_logits.data[i] - uncond_logits.data[i]) * this.guidance_scale; + } + return uncond_logits; + } +}; +var TemperatureLogitsWarper = class extends LogitsWarper { + /** + * Create a `TemperatureLogitsWarper`. + * @param {number} temperature Strictly positive float value used to modulate the logits distribution. + * A value smaller than `1` decreases randomness (and vice versa), with `0` being equivalent to shifting + * all probability mass to the most likely token. + */ + constructor(temperature) { + super(); + if (typeof temperature !== "number" || temperature <= 0) { + let errorMessage = `\`temperature\` (=${temperature}) must be a strictly positive float, otherwise your next token scores will be invalid.`; + if (temperature === 0) { + errorMessage += " If you're looking for greedy decoding strategies, set `do_sample=false`."; + } + } + this.temperature = temperature; + } + /** + * Apply logit warper. + * @param {bigint[][]} input_ids The input IDs. + * @param {Tensor} logits The logits. + * @returns {Tensor} The processed logits. + */ + _call(input_ids, logits) { + const batch_logits_data = ( + /** @type {Float32Array} */ + logits.data ); - if (transpose) { - mel_spec = mel_spec.transpose(1, 0); + for (let i = 0; i < batch_logits_data.length; ++i) { + batch_logits_data[i] /= this.temperature; } - - const mel_spec_data = /** @type {Float32Array} */(mel_spec.data); - for (let i = 0; i < mel_spec_data.length; ++i) { - mel_spec_data[i] = Math.max(mel_floor, mel_spec_data[i]); + return logits; + } +}; +var TopPLogitsWarper = class extends LogitsWarper { + /** + * Create a `TopPLogitsWarper`. + * @param {number} top_p If set to < 1, only the smallest set of most probable tokens with + * probabilities that add up to `top_p` or higher are kept for generation. + * @param {Object} options Additional options for the top-p sampling. + * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. + * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. + */ + constructor(top_p, { filter_value = -Infinity, min_tokens_to_keep = 1 } = {}) { + super(); + if (top_p < 0 || top_p > 1) { + throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${top_p}`); } - - if (power !== null && log_mel !== null) { - const o = Math.min(mel_spec_data.length, d1 * num_mel_filters); - // NOTE: operates in-place - switch (log_mel) { - case 'log': - for (let i = 0; i < o; ++i) { - mel_spec_data[i] = Math.log(mel_spec_data[i]); - } - break; - case 'log10': - for (let i = 0; i < o; ++i) { - mel_spec_data[i] = Math.log10(mel_spec_data[i]); - } - break; - case 'dB': - if (power === 1.0) { - amplitude_to_db(mel_spec_data, reference, min_value, db_range); - } else if (power === 2.0) { - power_to_db(mel_spec_data, reference, min_value, db_range); - } else { - throw new Error(`Cannot use log_mel option '${log_mel}' with power ${power}`) - } - break; - default: - throw new Error(`log_mel must be one of null, 'log', 'log10' or 'dB'. Got '${log_mel}'`); - } + if (!Number.isInteger(min_tokens_to_keep) || min_tokens_to_keep < 1) { + throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${min_tokens_to_keep}`); } - - return mel_spec; -} - -/** - * Returns an array containing the specified window. - * @param {number} window_length The length of the window in samples. - * @param {string} name The name of the window function. - * @param {Object} options Additional options. - * @param {boolean} [options.periodic=true] Whether the window is periodic or symmetric. - * @param {number} [options.frame_length=null] The length of the analysis frames in samples. - * Provide a value for `frame_length` if the window is smaller than the frame length, so that it will be zero-padded. - * @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided. - * @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`. - */ -function window_function(window_length, name, { - periodic = true, - frame_length = null, - center = true, -} = {}) { - const length = periodic ? window_length + 1 : window_length; - let window; - switch (name) { - case 'boxcar': - window = new Float64Array(length).fill(1.0); - break; - case 'hann': - case 'hann_window': - window = hanning(length); - break; - case 'hamming': - window = hamming(length); - break; - case 'povey': - window = hanning(length).map(x => Math.pow(x, 0.85)); - break; - default: - throw new Error(`Unknown window type ${name}.`); - } - if (periodic) { - window = window.subarray(0, window_length); - } - if (frame_length === null) { - return window; - } - if (window_length > frame_length) { - throw new Error(`Length of the window (${window_length}) may not be larger than frame_length (${frame_length})`); - } - - return window; -} - -/** - * Encode audio data to a WAV file. - * WAV file specs : https://en.wikipedia.org/wiki/WAV#WAV_File_header - * - * Adapted from https://www.npmjs.com/package/audiobuffer-to-wav - * @param {Float32Array} samples The audio samples. - * @param {number} rate The sample rate. - * @returns {ArrayBuffer} The WAV audio buffer. - */ -function encodeWAV(samples, rate) { - let offset = 44; - const buffer = new ArrayBuffer(offset + samples.length * 4); - const view = new DataView(buffer); - - /* RIFF identifier */ - writeString(view, 0, "RIFF"); - /* RIFF chunk length */ - view.setUint32(4, 36 + samples.length * 4, true); - /* RIFF type */ - writeString(view, 8, "WAVE"); - /* format chunk identifier */ - writeString(view, 12, "fmt "); - /* format chunk length */ - view.setUint32(16, 16, true); - /* sample format (raw) */ - view.setUint16(20, 3, true); - /* channel count */ - view.setUint16(22, 1, true); - /* sample rate */ - view.setUint32(24, rate, true); - /* byte rate (sample rate * block align) */ - view.setUint32(28, rate * 4, true); - /* block align (channel count * bytes per sample) */ - view.setUint16(32, 4, true); - /* bits per sample */ - view.setUint16(34, 32, true); - /* data chunk identifier */ - writeString(view, 36, "data"); - /* data chunk length */ - view.setUint32(40, samples.length * 4, true); - - for (let i = 0; i < samples.length; ++i, offset += 4) { - view.setFloat32(offset, samples[i], true); - } - - return buffer; -} - -function writeString(view, offset, string) { - for (let i = 0; i < string.length; ++i) { - view.setUint8(offset + i, string.charCodeAt(i)); + this.top_p = top_p; + this.filter_value = filter_value; + this.min_tokens_to_keep = min_tokens_to_keep; + } +}; +var TopKLogitsWarper = class extends LogitsWarper { + /** + * Create a `TopKLogitsWarper`. + * @param {number} top_k If set to > 0, only the top `top_k` tokens are kept for generation. + * @param {Object} options Additional options for the top-k sampling. + * @param {number} [options.filter_value=-Infinity] All filtered values will be set to this float value. + * @param {number} [options.min_tokens_to_keep=1] Minimum number of tokens that cannot be filtered. + */ + constructor(top_k, { filter_value = -Infinity, min_tokens_to_keep = 1 } = {}) { + super(); + if (!Number.isInteger(top_k) || top_k < 0) { + throw new Error(`\`top_k\` must be a positive integer, but is ${top_k}`); } -} - + this.top_k = Math.max(top_k, min_tokens_to_keep); + this.filter_value = filter_value; + } +}; -class RawAudio { +// src/generation/configuration_utils.js +var GenerationConfig = class { + // Parameters that control the length of the output + /** + * The maximum length the generated tokens can have. + * Corresponds to the length of the input prompt + `max_new_tokens`. + * Its effect is overridden by `max_new_tokens`, if also set. + * @type {number} + * @default 20 + */ + max_length = 20; + /** + * The maximum number of tokens to generate, ignoring the number of tokens in the prompt. + * @type {number} + * @default null + */ + max_new_tokens = null; + /** + * The minimum length of the sequence to be generated. + * Corresponds to the length of the input prompt + `min_new_tokens`. + * Its effect is overridden by `min_new_tokens`, if also set. + * @type {number} + * @default 0 + */ + min_length = 0; + /** + * The minimum number of tokens to generate, ignoring the number of tokens in the prompt. + * @type {number} + * @default null + */ + min_new_tokens = null; + /** + * Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values: + * - `true`, where the generation stops as soon as there are `num_beams` complete candidates; + * - `false`, where a heuristic is applied and the generation stops when it is very unlikely to find better candidates; + * - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm). + * @type {boolean|"never"} + * @default false + */ + early_stopping = false; + /** + * The maximum time, in seconds, allowed for generation. + * Generation will still finish the current pass after the allocated time has passed. + * @type {number} + * @default null + */ + max_time = null; + // Parameters that control the generation strategy used + /** + * Whether to use sampling; use greedy decoding otherwise. + * @type {boolean} + * @default false + */ + do_sample = false; + /** + * Number of beams for beam search. 1 means no beam search. + * @type {number} + * @default 1 + */ + num_beams = 1; + /** + * Number of groups to divide `num_beams` into to encourage diversity among different groups of beams. + * See [this paper](https://huggingface.co/papers/1610.02424) for more details. + * @type {number} + * @default 1 + */ + num_beam_groups = 1; + /** + * Balance model confidence against the degeneration penalty during contrastive search decoding. + * @type {number} + * @default null + */ + penalty_alpha = null; + /** + * Whether the model should reuse past key/value states, when supported, to speed up decoding. + * @type {boolean} + * @default true + */ + use_cache = true; + // Parameters for manipulation of the model output logits + /** + * The value used to modulate the next token probabilities. + * @type {number} + * @default 1.0 + */ + temperature = 1; + /** + * The number of highest-probability vocabulary tokens to keep for top-k filtering. + * @type {number} + * @default 50 + */ + top_k = 50; + /** + * If set to a float below 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation. + * @type {number} + * @default 1.0 + */ + top_p = 1; + /** + * Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. + * If set to a float below 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. + * See [this paper](https://huggingface.co/papers/2202.00666) for more details. + * @type {number} + * @default 1.0 + */ + typical_p = 1; + /** + * If set to a float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. + * In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. + * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details. + * @type {number} + * @default 0.0 + */ + epsilon_cutoff = 0; + /** + * Eta sampling is a hybrid of locally typical sampling and epsilon sampling. + * If set to a float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. + * The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. + * See [Truncation Sampling as Language Model Desmoothing](https://huggingface.co/papers/2210.15191) for more details. + * @type {number} + * @default 0.0 + */ + eta_cutoff = 0; + /** + * This value is subtracted from a beam's score if it generates the same token as any beam from another group at a particular time. + * Note that `diversity_penalty` is only effective if `group beam search` is enabled. + * @type {number} + * @default 0.0 + */ + diversity_penalty = 0; + /** + * Penalty applied to repeated tokens. 1.0 means no penalty. + * See [this paper](https://huggingface.co/papers/1909.05858) for more details. + * @type {number} + * @default 1.0 + */ + repetition_penalty = 1; + /** + * Penalty applied to sequences that are not in the original input. + * 1.0 means no penalty. + * @type {number} + * @default 1.0 + */ + encoder_repetition_penalty = 1; + /** + * Exponential penalty applied to sequence length during beam-based generation. + * It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. + * Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences. + * @type {number} + * @default 1.0 + */ + length_penalty = 1; + /** + * If set to an integer greater than 0, all n-grams of that size can only occur once. + * @type {number} + * @default 0 + */ + no_repeat_ngram_size = 0; + /** + * List of token IDs that are not allowed to be generated. + * In order to get the token IDs of the words that should not appear in the generated text, use + * `tokenizer(bad_words, { add_prefix_space: true, add_special_tokens: false }).input_ids`. + * @type {number[][]} + * @default null + */ + bad_words_ids = null; + /** + * List of token IDs that must be generated. + * If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite of `bad_words_ids`. + * If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), which allows different forms of each word. + * @type {number[][]|number[][][]} + * @default null + */ + force_words_ids = null; + /** + * Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). + * It's highly recommended to set this flag to `true` because search algorithms assume the score logits are normalized, but some logit processors or warpers break the normalization. + * @type {boolean} + * @default false + */ + renormalize_logits = false; + /** + * Custom constraints that guide generation to include certain tokens as defined by `Constraint` objects. + * @type {Object[]} + * @default null + */ + constraints = null; + /** + * The ID of the token to force as the first generated token after the `decoder_start_token_id`. + * Useful for multilingual models like mBART where the first generated token needs to be the target language token. + * @type {number} + * @default null + */ + forced_bos_token_id = null; + /** + * The ID of the token to force as the last generated token when `max_length` is reached. + * Optionally, use a list to set multiple *end-of-sequence* tokens. + * @type {number|number[]} + * @default null + */ + forced_eos_token_id = null; + /** + * Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method from crashing. Note that using `remove_invalid_values` can slow down generation. + * @type {boolean} + */ + remove_invalid_values = false; + /** + * This tuple adds an exponentially increasing length penalty after a certain number of tokens have been generated. + * The tuple consists of: `(start_index, decay_factor)` where `start_index` indicates where the penalty starts and `decay_factor` represents the factor of exponential decay. + * @type {[number, number]} + * @default null + */ + exponential_decay_length_penalty = null; + /** + * A list of tokens to suppress during generation. + * The `SuppressTokens` logit processor sets their log probabilities to `-inf` so that they are not sampled. + * @type {number[]} + * @default null + */ + suppress_tokens = null; + /** + * Streamer used to yield generated text incrementally. + * @type {import('./streamers.js').TextStreamer} + * @default null + */ + streamer = null; + /** + * A list of tokens to suppress at the beginning of the generation. + * The `SuppressBeginTokens` logit processor sets their log probabilities to `-inf` so that they are not sampled. + * @type {number[]} + * @default null + */ + begin_suppress_tokens = null; + /** + * A list of integer pairs that maps generation indices to token indices that will be forced before sampling. + * For example, `[[1, 123]]` means the second generated token will always be a token of index 123. + * @type {[number, number][]} + * @default null + */ + forced_decoder_ids = null; + /** + * The guidance scale for classifier-free guidance (CFG). CFG is enabled by setting `guidance_scale > 1`. + * Higher guidance scale encourages the model to generate samples that are more closely tied to the input + * prompt, usually at the expense of poorer quality. + * @type {number} + * @default null + */ + guidance_scale = null; + // Parameters that define the output variables of `generate` + /** + * The number of independently computed returned sequences for each element in the batch. + * @type {number} + * @default 1 + */ + num_return_sequences = 1; + /** + * Whether to return attention tensors from all attention layers. + * See `attentions` under returned tensors for more details. + * @type {boolean} + * @default false + */ + output_attentions = false; + /** + * Whether to return the hidden states of all layers. + * See `hidden_states` under returned tensors for more details. + * @type {boolean} + * @default false + */ + output_hidden_states = false; + /** + * Whether to return the prediction scores. + * See `scores` under returned tensors for more details. + * @type {boolean} + * @default false + */ + output_scores = false; + /** + * Whether to return a `ModelOutput` instead of a plain tuple. + * @type {boolean} + * @default false + */ + return_dict_in_generate = false; + // Special tokens that can be used at generation time + /** + * The ID of the *padding* token. + * @type {number} + * @default null + */ + pad_token_id = null; + /** + * The ID of the *beginning-of-sequence* token. + * @type {number} + * @default null + */ + bos_token_id = null; + /** + * The ID of the *end-of-sequence* token. + * Optionally, use a list to set multiple *end-of-sequence* tokens. + * @type {number|number[]} + * @default null + */ + eos_token_id = null; + // Generation parameters exclusive to encoder-decoder models + /** + * If set to an integer greater than 0, all n-grams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`. + * @type {number} + * @default 0 + */ + encoder_no_repeat_ngram_size = 0; + /** + * If an encoder-decoder model starts decoding with a token other than *bos*, the ID of that token. + * @type {number} + * @default null + */ + decoder_start_token_id = null; + // Wild card + /** + * Additional generation kwargs forwarded to the model's `generate` function. + * Kwargs that are not present in `generate`'s signature are used in the model forward pass. + * @type {Object} + * @default {} + */ + generation_kwargs = {}; + /** + * + * @param {GenerationConfig|import('../configs.js').PretrainedConfig} config + */ + constructor(config) { + Object.assign(this, pick(config, Object.getOwnPropertyNames(this))); + } +}; - /** - * Create a new `RawAudio` object. - * @param {Float32Array} audio Audio data - * @param {number} sampling_rate Sampling rate of the audio data - */ - constructor(audio, sampling_rate) { - this.audio = audio - this.sampling_rate = sampling_rate +// src/generation/stopping_criteria.js +var StoppingCriteria = class extends Callable { + /** + * + * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`): + * Indices of input sequence tokens in the vocabulary. + * @param {number[][]} scores (`number[][]` of shape `(batch_size, config.vocab_size)`): + * Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax + * or scores for each vocabulary token after SoftMax. + * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped. + */ + _call(input_ids, scores) { + throw Error("StoppingCriteria needs to be subclassed"); + } +}; +var StoppingCriteriaList = class _StoppingCriteriaList extends Callable { + /** + * Constructs a new instance of `StoppingCriteriaList`. + */ + constructor() { + super(); + this.criteria = []; + } + /** + * Adds a new stopping criterion to the list. + * + * @param {StoppingCriteria} item The stopping criterion to add. + */ + push(item) { + this.criteria.push(item); + } + /** + * Adds multiple stopping criteria to the list. + * + * @param {StoppingCriteria|StoppingCriteriaList|StoppingCriteria[]} items The stopping criteria to add. + */ + extend(items) { + if (items instanceof _StoppingCriteriaList) { + items = items.criteria; + } else if (items instanceof StoppingCriteria) { + items = [items]; } - - /** - * Convert the audio to a wav file buffer. - * @returns {ArrayBuffer} The WAV file. - */ - toWav() { - return encodeWAV(this.audio, this.sampling_rate) + this.criteria.push(...items); + } + _call(input_ids, scores) { + const is_done = new Array(input_ids.length).fill(false); + for (const criterion of this.criteria) { + const criterion_done = criterion(input_ids, scores); + for (let i = 0; i < is_done.length; ++i) { + is_done[i] ||= criterion_done[i]; + } } - - /** - * Convert the audio to a blob. - * @returns {Blob} - */ - toBlob() { - const wav = this.toWav(); - const blob = new Blob([wav], { type: 'audio/wav' }); - return blob; + return is_done; + } + [Symbol.iterator]() { + return this.criteria.values(); + } +}; +var MaxLengthCriteria = class extends StoppingCriteria { + /** + * + * @param {number} max_length The maximum length that the output sequence can have in number of tokens. + * @param {number} [max_position_embeddings=null] The maximum model length, as defined by the model's `config.max_position_embeddings` attribute. + */ + constructor(max_length, max_position_embeddings = null) { + super(); + this.max_length = max_length; + this.max_position_embeddings = max_position_embeddings; + } + _call(input_ids) { + return input_ids.map((ids) => ids.length >= this.max_length); + } +}; +var EosTokenCriteria = class extends StoppingCriteria { + /** + * + * @param {number|number[]} eos_token_id The ID of the *end-of-sequence* token. + * Optionally, use a list to set multiple *end-of-sequence* tokens. + */ + constructor(eos_token_id) { + super(); + if (!Array.isArray(eos_token_id)) { + eos_token_id = [eos_token_id]; } + this.eos_token_id = eos_token_id; + } + /** + * + * @param {number[][]} input_ids + * @param {number[][]} scores + * @returns {boolean[]} + */ + _call(input_ids, scores) { + return input_ids.map((ids) => { + const last = ids.at(-1); + return this.eos_token_id.some((eos_id) => last == eos_id); + }); + } +}; +var InterruptableStoppingCriteria = class extends StoppingCriteria { + /** + * Constructs a new instance of `InterruptableStoppingCriteria`. + */ + constructor() { + super(); + this.interrupted = false; + } + /** + * Interrupts generation, stopping every sequence on the next call. + */ + interrupt() { + this.interrupted = true; + } + /** + * Clears a previous interruption, allowing generation to continue. + */ + reset() { + this.interrupted = false; + } + /** + * @param {number[][]} input_ids (`number[][]` of shape `(batch_size, sequence_length)`): + * Indices of input sequence tokens in the vocabulary. + * @param {number[][]} scores (`number[][]` of shape `(batch_size, config.vocab_size)`): + * Prediction scores of a language modeling head. + * @returns {boolean[]} A list of booleans indicating whether each sequence should be stopped. + */ + _call(input_ids, scores) { + return new Array(input_ids.length).fill(this.interrupted); + } +}; - /** - * Save the audio to a wav file. - * @param {string} path - */ - async save(path) { - let fn; - - if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) { - if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) { - throw new Error('Unable to save a file from a Web Worker.') - } - fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob; - } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) { - fn = async (/** @type {string} */ path, /** @type {Blob} */ blob) => { - let buffer = await blob.arrayBuffer(); - node_fs__WEBPACK_IMPORTED_MODULE_5__.writeFileSync(path, Buffer.from(buffer)); - } - } else { - throw new Error('Unable to save because filesystem is disabled in this environment.') - } - - await fn(path, this.toBlob()) - } -} - - -/***/ }), - -/***/ "./src/utils/constants.js": -/*!********************************!*\ - !*** ./src/utils/constants.js ***! - \********************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ CHAT_TEMPLATE_NAME: () => (/* binding */ CHAT_TEMPLATE_NAME), -/* harmony export */ CONFIG_NAME: () => (/* binding */ CONFIG_NAME), -/* harmony export */ FEATURE_EXTRACTOR_NAME: () => (/* binding */ FEATURE_EXTRACTOR_NAME), -/* harmony export */ GENERATION_CONFIG_NAME: () => (/* binding */ GENERATION_CONFIG_NAME), -/* harmony export */ GITHUB_ISSUE_URL: () => (/* binding */ GITHUB_ISSUE_URL), -/* harmony export */ IMAGE_PROCESSOR_NAME: () => (/* binding */ IMAGE_PROCESSOR_NAME), -/* harmony export */ PROCESSOR_NAME: () => (/* binding */ PROCESSOR_NAME) -/* harmony export */ }); - -const GITHUB_ISSUE_URL = 'https://github.com/huggingface/transformers.js/issues/new/choose'; - -const CONFIG_NAME = "config.json" -const FEATURE_EXTRACTOR_NAME = "preprocessor_config.json" -const IMAGE_PROCESSOR_NAME = FEATURE_EXTRACTOR_NAME -const PROCESSOR_NAME = "processor_config.json" -const CHAT_TEMPLATE_NAME = "chat_template.jinja" -const GENERATION_CONFIG_NAME = "generation_config.json" - - -/***/ }), - -/***/ "./src/utils/core.js": -/*!***************************!*\ - !*** ./src/utils/core.js ***! - \***************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ calculateDimensions: () => (/* binding */ calculateDimensions), -/* harmony export */ calculateReflectOffset: () => (/* binding */ calculateReflectOffset), -/* harmony export */ count: () => (/* binding */ count), -/* harmony export */ dispatchCallback: () => (/* binding */ dispatchCallback), -/* harmony export */ escapeRegExp: () => (/* binding */ escapeRegExp), -/* harmony export */ isIntegralNumber: () => (/* binding */ isIntegralNumber), -/* harmony export */ isNullishDimension: () => (/* binding */ isNullishDimension), -/* harmony export */ isTypedArray: () => (/* binding */ isTypedArray), -/* harmony export */ len: () => (/* binding */ len), -/* harmony export */ mergeArrays: () => (/* binding */ mergeArrays), -/* harmony export */ pick: () => (/* binding */ pick), -/* harmony export */ pop: () => (/* binding */ pop), -/* harmony export */ product: () => (/* binding */ product), -/* harmony export */ reverseDictionary: () => (/* binding */ reverseDictionary), -/* harmony export */ saveBlob: () => (/* binding */ saveBlob) -/* harmony export */ }); - -/** - * @file Core utility functions/classes for Transformers.js. - * - * These are only used internally, meaning an end-user shouldn't - * need to access anything here. - * - * @module utils/core - */ - -/** - * @typedef {Object} InitiateProgressInfo - * @property {'initiate'} status - * @property {string} name The model id or directory path. - * @property {string} file The name of the file. - */ - -/** - * @typedef {Object} DownloadProgressInfo - * @property {'download'} status - * @property {string} name The model id or directory path. - * @property {string} file The name of the file. - */ - -/** - * @typedef {Object} ProgressStatusInfo - * @property {'progress'} status - * @property {string} name The model id or directory path. - * @property {string} file The name of the file. - * @property {number} progress A number between 0 and 100. - * @property {number} loaded The number of bytes loaded. - * @property {number} total The total number of bytes to be loaded. - */ - -/** - * @typedef {Object} DoneProgressInfo - * @property {'done'} status - * @property {string} name The model id or directory path. - * @property {string} file The name of the file. - */ - -/** - * @typedef {Object} ReadyProgressInfo - * @property {'ready'} status - * @property {string} task The loaded task. - * @property {string} model The loaded model. - */ - -/** - * @typedef {InitiateProgressInfo | DownloadProgressInfo | ProgressStatusInfo | DoneProgressInfo | ReadyProgressInfo} ProgressInfo - */ - -/** - * A callback function that is called with progress information. - * @callback ProgressCallback - * @param {ProgressInfo} progressInfo - * @returns {void} - */ - -/** - * Helper function to dispatch progress callbacks. - * - * @param {ProgressCallback | null | undefined} progress_callback The progress callback function to dispatch. - * @param {ProgressInfo} data The data to pass to the progress callback function. - * @returns {void} - * @private - */ -function dispatchCallback(progress_callback, data) { - if (progress_callback) progress_callback(data); -} - -/** - * Reverses the keys and values of an object. - * - * @param {Object} data The object to reverse. - * @returns {Object} The reversed object. - * @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript - */ -function reverseDictionary(data) { - // https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript - return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key])); -} - -/** - * Escapes regular expression special characters from a string by replacing them with their escaped counterparts. - * - * @param {string} string The string to escape. - * @returns {string} The escaped string. - */ -function escapeRegExp(string) { - return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string -} - -/** - * Check if a value is a typed array. - * @param {*} val The value to check. - * @returns {boolean} True if the value is a `TypedArray`, false otherwise. - * - * Adapted from https://stackoverflow.com/a/71091338/13989043 - */ -function isTypedArray(val) { - return val?.prototype?.__proto__?.constructor?.name === 'TypedArray'; -} - - -/** - * Check if a value is an integer. - * @param {*} x The value to check. - * @returns {boolean} True if the value is a string, false otherwise. - */ -function isIntegralNumber(x) { - return Number.isInteger(x) || typeof x === 'bigint' -} - -/** - * Determine if a provided width or height is nullish. - * @param {*} x The value to check. - * @returns {boolean} True if the value is `null`, `undefined` or `-1`, false otherwise. - */ -function isNullishDimension(x) { - return x === null || x === undefined || x === -1; -} - -/** - * Calculates the dimensions of a nested array. - * - * @param {any[]} arr The nested array to calculate dimensions for. - * @returns {number[]} An array containing the dimensions of the input array. - */ -function calculateDimensions(arr) { - const dimensions = []; - let current = arr; - while (Array.isArray(current)) { - dimensions.push(current.length); - current = current[0]; - } - return dimensions; -} - -/** - * Replicate python's .pop() method for objects. - * @param {Object} obj The object to pop from. - * @param {string} key The key to pop. - * @param {*} defaultValue The default value to return if the key does not exist. - * @returns {*} The value of the popped key. - * @throws {Error} If the key does not exist and no default value is provided. - */ -function pop(obj, key, defaultValue = undefined) { - const value = obj[key]; - if (value !== undefined) { - delete obj[key]; - return value; - } - if (defaultValue === undefined) { - throw Error(`Key ${key} does not exist in object.`) - } - return defaultValue; -} - -/** - * Efficiently merge arrays, creating a new copy. - * Adapted from https://stackoverflow.com/a/6768642/13989043 - * @param {Array[]} arrs Arrays to merge. - * @returns {Array} The merged array. - */ -function mergeArrays(...arrs) { - return Array.prototype.concat.apply([], arrs); -} - -/** - * Compute the Cartesian product of given arrays - * @param {...Array} a Arrays to compute the product - * @returns {Array} Returns the computed Cartesian product as an array - * @private - */ -function product(...a) { - // Cartesian product of items - // Adapted from https://stackoverflow.com/a/43053803 - return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e]))); -} - -/** - * Calculates the index offset for a given index and window size. - * @param {number} i The index. - * @param {number} w The window size. - * @returns {number} The index offset. - */ -function calculateReflectOffset(i, w) { - return Math.abs((i + w) % (2 * w) - w); -} - -/** - * Save blob file on the web. - * @param {string} path The path to save the blob to - * @param {Blob} blob The blob to save - */ -function saveBlob(path, blob){ - // Convert the canvas content to a data URL - const dataURL = URL.createObjectURL(blob); - - // Create an anchor element with the data URL as the href attribute - const downloadLink = document.createElement('a'); - downloadLink.href = dataURL; - - // Set the download attribute to specify the desired filename for the downloaded image - downloadLink.download = path; - - // Trigger the download - downloadLink.click(); - - // Clean up: remove the anchor element from the DOM - downloadLink.remove(); - - // Revoke the Object URL to free up memory - URL.revokeObjectURL(dataURL); -} - -/** - * - * @param {Object} o - * @param {string[]} props - * @returns {Object} - */ -function pick(o, props) { - return Object.assign( - {}, - ...props.map((prop) => { - if (o[prop] !== undefined) { - return { [prop]: o[prop] }; - } - }) +// src/generation/logits_sampler.js +var LogitsSampler = class extends Callable { + /** + * Creates a new Sampler object with the specified generation config. + * @param {GenerationConfig} generation_config The generation config. + */ + constructor(generation_config) { + super(); + this.generation_config = generation_config; + } + /** + * Executes the sampler, using the specified logits. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} + */ + async _call(logits) { + return this.sample(logits); + } + /** + * Abstract method for sampling the logits. + * @param {Tensor} logits + * @throws {Error} If not implemented in subclass. + * @returns {Promise<[bigint, number][]>} + */ + async sample(logits) { + throw Error("sample should be implemented in subclasses."); + } + /** + * Returns the specified logits as an array, with temperature applied. + * @param {Tensor} logits + * @param {number} index + * @returns {Float32Array} + */ + getLogits(logits, index) { + let vocabSize = logits.dims.at(-1); + let logs = ( + /** @type {Float32Array} */ + logits.data ); -} - -/** - * Calculate the length of a string, taking multi-byte characters into account. - * This mimics the behavior of Python's `len` function. - * @param {string} s The string to calculate the length of. - * @returns {number} The length of the string. - */ -function len(s) { - let length = 0; - for (const c of s) ++length; - return length; -} - -/** - * Count the occurrences of a value in an array or string. - * This mimics the behavior of Python's `count` method. - * @param {any[]|string} arr The array or string to search. - * @param {any} value The value to count. - */ -function count(arr, value) { - let count = 0; - for (const v of arr) { - if (v === value) ++count; - } - return count; -} - - -/***/ }), - -/***/ "./src/utils/data-structures.js": -/*!**************************************!*\ - !*** ./src/utils/data-structures.js ***! - \**************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ CharTrie: () => (/* binding */ CharTrie), -/* harmony export */ DictionarySplitter: () => (/* binding */ DictionarySplitter), -/* harmony export */ LRUCache: () => (/* binding */ LRUCache), -/* harmony export */ PriorityQueue: () => (/* binding */ PriorityQueue), -/* harmony export */ TokenLattice: () => (/* binding */ TokenLattice) -/* harmony export */ }); - -/** - * @file Custom data structures. - * - * These are only used internally, meaning an end-user shouldn't - * need to access anything here. - * - * @module utils/data-structures - */ - - -/** - * Efficient Heap-based Implementation of a Priority Queue. - * It uses an array-based binary heap, where the root is at index `0`, and the - * children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively. - * - * Adapted from the following sources: - * - https://stackoverflow.com/a/42919752/13989043 (original) - * - https://github.com/belladoreai/llama-tokenizer-js (minor improvements) - */ -class PriorityQueue { - - /** - * Create a new PriorityQueue. - * @param {function(any, any): boolean} comparator Comparator function to determine priority. Defaults to a MaxHeap. - */ - constructor(comparator = (a, b) => a > b, maxSize = Infinity) { - this._heap = []; - this._comparator = comparator; - this._maxSize = maxSize; + if (index === -1) { + logs = logs.slice(-vocabSize); + } else { + let startIndex = index * vocabSize; + logs = logs.slice(startIndex, startIndex + vocabSize); } - - /** - * The size of the queue - */ - get size() { - return this._heap.length; + return logs; + } + /** + * Selects an item randomly based on the specified probabilities. + * @param {Float32Array} probabilities An array of probabilities to use for selection. + * @returns {number} The index of the selected item. + */ + randomSelect(probabilities) { + return _weightedIndex(probabilities); + } + /** + * Returns a Sampler object based on the specified options. + * @param {GenerationConfig} generation_config An object containing options for the sampler. + * @returns {LogitsSampler} A Sampler object. + */ + static getSampler(generation_config) { + if (generation_config.do_sample) { + return new MultinomialSampler(generation_config); + } else if (generation_config.num_beams > 1) { + return new BeamSearchSampler(generation_config); + } else { + if (generation_config.num_return_sequences > 1) { + throw Error( + `num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.` + ); + } + return new GreedySampler(generation_config); } + } +}; +var GreedySampler = class extends LogitsSampler { + /** + * Sample the maximum probability of a given logits tensor. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search). + */ + async sample(logits) { + const argmax = max(logits.data)[1]; + return [[BigInt(argmax), 0]]; + } +}; +var MultinomialSampler = class extends LogitsSampler { + /** + * Sample from the logits. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} + */ + async sample(logits) { + let k = logits.dims.at(-1); + if (this.generation_config.top_k > 0) { + k = Math.min(this.generation_config.top_k, k); + } + const [v, i] = await topk(logits, k); + const probabilities = softmax( + /** @type {Float32Array} */ + v.data + ); + return Array.from({ length: this.generation_config.num_beams }, () => { + const sampledIndex = this.randomSelect(probabilities); + return [ + i.data[sampledIndex], + // token id + Math.log(probabilities[sampledIndex]) + // score + ]; + }); + } +}; +var BeamSearchSampler = class extends LogitsSampler { + /** + * Sample from the logits. + * @param {Tensor} logits + * @returns {Promise<[bigint, number][]>} + */ + async sample(logits) { + let k = logits.dims.at(-1); + if (this.generation_config.top_k > 0) { + k = Math.min(this.generation_config.top_k, k); + } + const [v, i] = await topk(logits, k); + const probabilities = softmax( + /** @type {Float32Array} */ + v.data + ); + return Array.from({ length: this.generation_config.num_beams }, (_, x) => { + return [ + i.data[x], + // token id + Math.log(probabilities[x]) + // score + ]; + }); + } +}; - /** - * Check if the queue is empty. - * @returns {boolean} `true` if the queue is empty, `false` otherwise. - */ - isEmpty() { - return this.size === 0; +// src/cache_utils.js +var _DynamicCache = class { + /** + * Create a DynamicCache, optionally pre-populated with entries. + * @param {Record} [entries] Initial name→Tensor mappings. + */ + constructor(entries) { + if (!entries) return; + for (const key in entries) { + if (key in this) { + throw new TypeError(`Key "${key}" conflicts with an existing property on DynamicCache`); + } + const value = entries[key]; + if (!(value instanceof Tensor3)) { + throw new TypeError(`Expected a Tensor for key "${key}", got ${typeof value}`); + } + this[key] = value; } - - /** - * Return the element with the highest priority in the queue. - * @returns {any} The highest priority element in the queue. - */ - peek() { - return this._heap[0]; + } + /** + * Get the cached sequence length. This requires at least one attention cache entry to be present. + * @returns {number} The past sequence length. + */ + get_seq_length() { + const self2 = ( + /** @type {any} */ + this + ); + if (Object.keys(self2).length === 0) { + return 0; } - - /** - * Add one or more elements to the queue. - * @param {...any} values The values to push into the queue. - * @returns {number} The new size of the queue. - */ - push(...values) { - return this.extend(values); + for (const name in self2) { + if (name.startsWith("past_key_values.")) { + return self2[name].dims.at(-2); + } } - - /** - * Add multiple elements to the queue. - * @param {any[]} values The values to push into the queue. - * @returns {number} The new size of the queue. - */ - extend(values) { - for (const value of values) { - if (this.size < this._maxSize) { - this._heap.push(value); - this._siftUp(); - } else { - // Get index of value with the lowest priority - const smallest = this._smallest(); - - // If the new value has higher priority than the smallest value in the heap - // then replace the smallest value with the new value and update the heap - if (this._comparator(value, this._heap[smallest])) { - this._heap[smallest] = value; - this._siftUpFrom(smallest); - } - } - } - return this.size; + throw new Error("Unable to determine sequence length from the cache."); + } + /** + * Update the cache in-place with new entries, disposing replaced GPU tensors. + * @param {Record} newEntries The new name → Tensor mappings. + */ + update(newEntries) { + for (const key in newEntries) { + const oldValue = this[key]; + const newValue = newEntries[key]; + if (oldValue && oldValue !== newValue && oldValue.location === "gpu-buffer") { + oldValue.dispose(); + } + this[key] = newValue; + } + } + /** + * Dispose all contained tensors whose data resides on the GPU. + * Returns a promise that resolves when all disposals are complete. + * @returns {Promise} Promise that resolves when all GPU tensors are disposed. + */ + async dispose() { + const promises = []; + for ( + const t of + /** @type {Tensor[]} */ + Object.values(this) + ) { + if (t.location === "gpu-buffer") { + promises.push(t.dispose()); + } } + await Promise.all(promises); + } +}; +var DynamicCache = ( + /** @type {new (entries?: Record) => DynamicCache} */ + /** @type {unknown} */ + _DynamicCache +); + +// src/models/session_config.js +var MODEL_TYPES = { + EncoderOnly: 0, + EncoderDecoder: 1, + Seq2Seq: 2, + Vision2Seq: 3, + DecoderOnly: 4, + DecoderOnlyWithoutHead: 5, + MaskGeneration: 6, + ImageTextToText: 7, + Musicgen: 8, + MultiModality: 9, + Phi3V: 10, + AudioTextToText: 11, + AutoEncoder: 12, + ImageAudioTextToText: 13, + Supertonic: 14, + Chatterbox: 15, + VoxtralRealtime: 16, + MultimodalEncoder: 17 +}; +var MODEL_SESSION_CONFIG = { + [MODEL_TYPES.DecoderOnly]: { + sessions: (config, options) => ({ model: options.model_file_name ?? "model" }), + cache_sessions: { model: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.DecoderOnlyWithoutHead]: { + sessions: (config, options) => ({ model: options.model_file_name ?? "model" }) + }, + [MODEL_TYPES.Seq2Seq]: { + sessions: () => ({ model: "encoder_model", decoder_model_merged: "decoder_model_merged" }), + cache_sessions: { decoder_model_merged: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.Vision2Seq]: { + sessions: () => ({ model: "encoder_model", decoder_model_merged: "decoder_model_merged" }), + cache_sessions: { decoder_model_merged: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.Musicgen]: { + sessions: () => ({ + model: "text_encoder", + decoder_model_merged: "decoder_model_merged", + encodec_decode: "encodec_decode" + }), + cache_sessions: { decoder_model_merged: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.EncoderDecoder]: { + sessions: () => ({ model: "encoder_model", decoder_model_merged: "decoder_model_merged" }), + cache_sessions: { decoder_model_merged: true } + }, + [MODEL_TYPES.MaskGeneration]: { + sessions: () => ({ model: "vision_encoder", prompt_encoder_mask_decoder: "prompt_encoder_mask_decoder" }) + }, + [MODEL_TYPES.ImageTextToText]: { + text_only_sessions: { embed_tokens: "embed_tokens", decoder_model_merged: "decoder_model_merged" }, + sessions: (config, options, textOnly) => { + const s = { ...MODEL_SESSION_CONFIG[MODEL_TYPES.ImageTextToText].text_only_sessions }; + if (!textOnly) s["vision_encoder"] = "vision_encoder"; + if (config.is_encoder_decoder) s["model"] = "encoder_model"; + return s; + }, + cache_sessions: { decoder_model_merged: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.AudioTextToText]: { + text_only_sessions: { embed_tokens: "embed_tokens", decoder_model_merged: "decoder_model_merged" }, + sessions: (config, options, textOnly) => { + const s = { ...MODEL_SESSION_CONFIG[MODEL_TYPES.AudioTextToText].text_only_sessions }; + if (!textOnly) s["audio_encoder"] = "audio_encoder"; + return s; + }, + cache_sessions: { decoder_model_merged: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.ImageAudioTextToText]: { + text_only_sessions: { embed_tokens: "embed_tokens", decoder_model_merged: "decoder_model_merged" }, + sessions: (config, options, textOnly) => { + const s = { ...MODEL_SESSION_CONFIG[MODEL_TYPES.ImageAudioTextToText].text_only_sessions }; + if (!textOnly) { + s["audio_encoder"] = "audio_encoder"; + s["vision_encoder"] = "vision_encoder"; + } + return s; + }, + cache_sessions: { decoder_model_merged: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.Phi3V]: { + sessions: () => ({ + prepare_inputs_embeds: "prepare_inputs_embeds", + model: "model", + vision_encoder: "vision_encoder" + }), + cache_sessions: { model: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.MultiModality]: { + sessions: () => ({ + 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" + }), + cache_sessions: { model: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.AutoEncoder]: { + sessions: () => ({ encoder_model: "encoder_model", decoder_model: "decoder_model" }) + }, + [MODEL_TYPES.Supertonic]: { + sessions: () => ({ + text_encoder: "text_encoder", + latent_denoiser: "latent_denoiser", + voice_decoder: "voice_decoder" + }) + }, + [MODEL_TYPES.Chatterbox]: { + sessions: () => ({ + embed_tokens: "embed_tokens", + speech_encoder: "speech_encoder", + model: "language_model", + conditional_decoder: "conditional_decoder" + }), + cache_sessions: { model: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.VoxtralRealtime]: { + text_only_sessions: { embed_tokens: "embed_tokens", decoder_model_merged: "decoder_model_merged" }, + sessions: (config, options, textOnly) => { + const s = { ...MODEL_SESSION_CONFIG[MODEL_TYPES.VoxtralRealtime].text_only_sessions }; + if (!textOnly) s["audio_encoder"] = "audio_encoder"; + return s; + }, + cache_sessions: { decoder_model_merged: true, audio_encoder: true }, + optional_configs: { generation_config: "generation_config.json" } + }, + [MODEL_TYPES.MultimodalEncoder]: { + // The vision and audio encoders are only loaded when the config has their `vision_config` / `audio_config` + sessions: (config, options) => ({ + model: options.model_file_name ?? "model", + ...config.vision_config && { vision_encoder: "vision_encoder" }, + ...config.audio_config && { audio_encoder: "audio_encoder" } + }) + }, + default: { + sessions: (config, options) => ({ model: options.model_file_name ?? "model" }) + } +}; +function getTextOnlySessions(modelType) { + const typeConfig = MODEL_SESSION_CONFIG[modelType]; + return typeConfig?.text_only_sessions ?? null; +} +function getSessionsConfig(modelType, config, options = {}) { + const typeConfig = MODEL_SESSION_CONFIG[modelType] ?? MODEL_SESSION_CONFIG.default; + return { + sessions: typeConfig.sessions(config, options, options.textOnly ?? false), + cache_sessions: typeConfig.cache_sessions, + optional_configs: typeConfig.optional_configs + }; +} - /** - * Remove and return the element with the highest priority in the queue. - * @returns {any} The element with the highest priority in the queue. - */ - pop() { - const poppedValue = this.peek(); - const bottom = this.size - 1; - if (bottom > 0) { - this._swap(0, bottom); +// src/utils/model_registry/resolve_model_type.js +function resolve_model_type(config, { warn = true } = {}) { + const architectures = ( + /** @type {string[]} */ + config.architectures || [] + ); + for (const arch of architectures) { + const mappedType = MODEL_TYPE_MAPPING.get(arch); + if (mappedType !== void 0) { + return mappedType; + } + } + if (config.model_type) { + const mappedType = MODEL_TYPE_MAPPING.get(config.model_type); + if (mappedType !== void 0) { + return mappedType; + } + for (const mapping of Object.values(MODEL_MAPPING_NAMES)) { + if (mapping.has(config.model_type)) { + const resolved = MODEL_TYPE_MAPPING.get(mapping.get(config.model_type)); + if (resolved !== void 0) { + return resolved; } - this._heap.pop(); - this._siftDown(); - return poppedValue; + } } + } + if (warn) { + const archList = architectures.length > 0 ? architectures.join(", ") : "(none)"; + logger.warn( + `[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${archList}] for model type '${config.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${GITHUB_ISSUE_URL}` + ); + } + return MODEL_TYPES.EncoderOnly; +} - /** - * Replace the element with the highest priority in the queue with a new value. - * @param {*} value The new value. - * @returns {*} The replaced value. - */ - replace(value) { - const replacedValue = this.peek(); - this._heap[0] = value; - this._siftDown(); - return replacedValue; +// src/utils/model_registry/get_model_files.js +function get_config(modelId, { config = null, cache_dir = null, local_files_only = false, revision = "main" } = {}) { + if (config !== null) { + return AutoConfig.from_pretrained(modelId, { config, cache_dir, local_files_only, revision }); + } + const key = makePretrainedOptionsKey(modelId, { cache_dir, local_files_only, revision }); + return memoizePromise( + key, + () => AutoConfig.from_pretrained(modelId, { config, cache_dir, local_files_only, revision }) + ); +} +async function get_model_files(modelId, { config = null, dtype: overrideDtype = null, device: overrideDevice = null, model_file_name = null } = {}) { + config = await get_config(modelId, { config }); + const files = [ + // Add config.json (always loaded) + "config.json" + ]; + const custom_config = config["transformers.js_config"] ?? {}; + const use_external_data_format = custom_config.use_external_data_format; + const subfolder = "onnx"; + const rawDevice = overrideDevice ?? custom_config.device; + let dtype = overrideDtype ?? custom_config.dtype; + const modelType = resolve_model_type(config); + const add_model_file = (fileName, baseName = null) => { + baseName = baseName ?? fileName; + const selectedDevice = selectDevice(rawDevice, fileName); + const selectedDtype = selectDtype(dtype, fileName, selectedDevice); + const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[selectedDtype] ?? ""; + const fullName = `${baseName}${suffix}.onnx`; + const fullPath = subfolder ? `${subfolder}/${fullName}` : fullName; + files.push(fullPath); + const num_chunks = resolveExternalDataFormat(use_external_data_format, fullName, fileName); + for (const dataFileName of getExternalDataChunkNames(fullName, num_chunks)) { + const dataFilePath = subfolder ? `${subfolder}/${dataFileName}` : dataFileName; + files.push(dataFilePath); } - - /** - * Compute the index for the parent of the node at index `i`. - * @param {number} i The index of the node to get the parent of. - * @returns {number} The index of the parent node. - * @private - */ - _parent(i) { - return ((i + 1) >>> 1) - 1; + }; + const { sessions, optional_configs } = getSessionsConfig(modelType, config, { model_file_name }); + for (const [sessionKey, baseName] of Object.entries(sessions)) { + add_model_file(sessionKey, baseName); + } + if (optional_configs) { + for (const configFile of Object.values(optional_configs)) { + files.push(configFile); } + } + return files; +} - /** - * Compute the index for the left child of the node at index `i`. - * @param {number} i The index of the node to get the left child of. - * @returns {number} The index of the left child. - * @private - */ - _left(i) { - return (i << 1) + 1; +// src/models/modeling_utils.js +var MODEL_MAPPING_NAMES = null; +function registerTaskMappings(mappings) { + MODEL_MAPPING_NAMES = mappings; +} +function toI64Tensor(items) { + if (items instanceof Tensor3) { + return items; + } + if (items.length === 0) { + throw Error("items must be non-empty"); + } + if (Array.isArray(items[0])) { + if (items.some((x) => x.length !== items[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." + ); } - - /** - * Compute the index for the right child of the node at index `i`. - * @param {number} i The index of the node to get the right child of. - * @returns {number} The index of the right child. - * @private - */ - _right(i) { - return (i + 1) << 1; + return new Tensor3("int64", BigInt64Array.from(items.flat().map((x) => BigInt(x))), [ + items.length, + items[0].length + ]); + } else { + return new Tensor3("int64", BigInt64Array.from(items.map((x) => BigInt(x))), [1, items.length]); + } +} +function boolTensor(value) { + return new Tensor3("bool", [value], [1]); +} +var MODEL_RUNTIME_CONFIG = { + [MODEL_TYPES.DecoderOnly]: { + can_generate: true, + forward: decoder_forward, + prepare_inputs: decoder_prepare_inputs_for_generation + }, + [MODEL_TYPES.DecoderOnlyWithoutHead]: { + can_generate: false, + forward: decoder_forward, + prepare_inputs: decoder_prepare_inputs_for_generation + }, + [MODEL_TYPES.Seq2Seq]: { + can_generate: true, + forward: seq2seq_forward, + prepare_inputs: encoder_decoder_prepare_inputs_for_generation + }, + [MODEL_TYPES.Vision2Seq]: { + can_generate: true, + forward: seq2seq_forward, + prepare_inputs: encoder_decoder_prepare_inputs_for_generation + }, + [MODEL_TYPES.Musicgen]: { + can_generate: true, + forward: seq2seq_forward + }, + [MODEL_TYPES.EncoderDecoder]: { + can_generate: false, + forward: seq2seq_forward + }, + [MODEL_TYPES.ImageTextToText]: { + can_generate: true, + forward: image_text_to_text_forward, + prepare_inputs: multimodal_text_to_text_prepare_inputs_for_generation + }, + [MODEL_TYPES.AudioTextToText]: { + can_generate: true, + forward: audio_text_to_text_forward, + prepare_inputs: multimodal_text_to_text_prepare_inputs_for_generation + }, + [MODEL_TYPES.ImageAudioTextToText]: { + can_generate: true, + prepare_inputs: multimodal_text_to_text_prepare_inputs_for_generation + }, + [MODEL_TYPES.Phi3V]: { + can_generate: true, + prepare_inputs: multimodal_text_to_text_prepare_inputs_for_generation + }, + [MODEL_TYPES.MultiModality]: { + can_generate: true + }, + [MODEL_TYPES.AutoEncoder]: { + can_generate: false, + forward: auto_encoder_forward + }, + [MODEL_TYPES.Chatterbox]: { + can_generate: true, + forward: encoder_forward + }, + [MODEL_TYPES.VoxtralRealtime]: { + can_generate: true, + prepare_inputs: decoder_prepare_inputs_for_generation + }, + default: { + can_generate: false, + forward: encoder_forward + } +}; +function resolveTypeConfig(modelName, config) { + let modelType = MODEL_TYPE_MAPPING.get(modelName); + let textOnly = false; + const nativeArch = config?.architectures?.[0]; + if (nativeArch && nativeArch !== modelName && modelName?.endsWith("ForCausalLM") && nativeArch.endsWith("ForConditionalGeneration")) { + const nativeType = MODEL_TYPE_MAPPING.get(nativeArch); + if (nativeType !== void 0) { + modelType = nativeType; + textOnly = true; } - - /** - * Check if the element at index `i` is greater than the element at index `j`. - * @param {number} i The index of the first element to compare. - * @param {number} j The index of the second element to compare. - * @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise. - * @private - */ - _greater(i, j) { - return this._comparator(this._heap[i], this._heap[j]); + } + const runtimeConfig = MODEL_RUNTIME_CONFIG[modelType] ?? MODEL_RUNTIME_CONFIG.default; + const sessionConfig = MODEL_SESSION_CONFIG[modelType] ?? MODEL_SESSION_CONFIG.default; + return { typeConfig: { ...runtimeConfig, ...sessionConfig }, textOnly, modelType }; +} +var MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map(); +var MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map(); +var MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map(); +var PreTrainedModel = class extends Callable { + main_input_name = "input_ids"; + forward_params = ["input_ids", "attention_mask"]; + _return_dict_in_generate_keys = null; + /** + * Create a model from configuration and inference sessions. + * @param {import('../configs.js').PretrainedConfig} config The model configuration. + * @param {Record} sessions The inference sessions for the model. + * @param {Record} configs Additional configuration files (e.g., generation_config.json). + */ + constructor(config, sessions, configs) { + super(); + this.config = config; + this.sessions = sessions; + this.configs = configs; + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); + const { typeConfig } = resolveTypeConfig(modelName, config); + this.can_generate = typeConfig.can_generate; + this._forward = typeConfig.forward; + this._prepare_inputs_for_generation = typeConfig.prepare_inputs; + if (this.can_generate) { + this.forward_params.push("past_key_values"); + } + this.custom_config = this.config["transformers.js_config"] ?? {}; + } + /** + * Disposes of all the ONNX sessions that were created during inference. + * @returns {Promise} Resolves after each session has been released. + * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry + */ + async dispose() { + const promises = []; + for (const session of Object.values(this.sessions)) { + promises.push(session.release?.()); } - - /** - * Swap the elements at indices `i` and `j`. - * @param {number} i The index of the first element to swap. - * @param {number} j The index of the second element to swap. - * @private - */ - _swap(i, j) { - const temp = this._heap[i]; - this._heap[i] = this._heap[j]; - this._heap[j] = temp; + return await Promise.all(promises); + } + /** + * Instantiate one of the model classes of the library from a pretrained model. + * + * The model class to instantiate is selected based on the `model_type` property of the config object + * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible) + * + * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either: + * - A string, the *model ID* of a pretrained model hosted inside a model repo on huggingface.co. + * Valid model IDs can be located at the root level, like `bert-base-uncased`, or namespaced under a + * user or organization name, like `dbmdz/bert-base-german-cased`. + * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`. + * @param {import('../utils/hub.js').PretrainedModelOptions} options Additional options for loading the model. + * + * @returns {Promise} A model instance with ready inference sessions. + */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + model_file_name = null, + subfolder = "onnx", + device = null, + dtype = null, + use_external_data_format = null, + session_options = {} + } = {}) { + const options = { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + model_file_name, + subfolder, + device, + dtype, + use_external_data_format, + session_options + }; + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this); + config = options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options); + const { typeConfig, textOnly, modelType } = resolveTypeConfig(modelName, config); + if (modelType === void 0) { + const type = modelName ?? config?.model_type; + if (type !== "custom") { + logger.warn( + `Model type for '${type}' not found, assuming encoder-only architecture. Please report this at ${GITHUB_ISSUE_URL}.` + ); + } } - - /** - * Maintain the heap property by updating positions in the heap, - * starting at the last element and moving up the heap. - * @private - */ - _siftUp() { - this._siftUpFrom(this.size - 1); + if (progress_callback && !(progress_callback instanceof DefaultProgressCallback)) { + const files_loading = {}; + try { + const expected_files = await get_model_files(pretrained_model_name_or_path, { + config, + dtype, + device, + model_file_name + }); + const metadata = await Promise.all( + expected_files.map((file) => get_file_metadata(pretrained_model_name_or_path, file, options)) + ); + metadata.forEach((m, i) => { + if (m.exists) { + const isAlreadyLoaded = expected_files[i] === "config.json"; + files_loading[expected_files[i]] = { + loaded: isAlreadyLoaded ? m.size ?? 0 : 0, + total: m.size ?? 0 + }; + } + }); + } catch (e) { + logger.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`); + } + if (Object.keys(files_loading).length > 0) { + options.progress_callback = new DefaultProgressCallback(progress_callback, files_loading); + } } - - /** - * Helper function to sift up from a given node. - * @param {number} node The index of the node to start sifting up from. - */ - _siftUpFrom(node) { - while (node > 0 && this._greater(node, this._parent(node))) { - this._swap(node, this._parent(node)); - node = this._parent(node); - } + const sessions = typeConfig.sessions(config, options, textOnly); + const promises = [ + constructSessions(pretrained_model_name_or_path, sessions, options, typeConfig.cache_sessions) + ]; + if (typeConfig.optional_configs) { + promises.push(get_optional_configs(pretrained_model_name_or_path, typeConfig.optional_configs, options)); } - - /** - * Maintain the heap property by updating positions in the heap, - * starting at the first element and moving down the heap. - * @private - */ - _siftDown() { - let node = 0; - while ( - (this._left(node) < this.size && this._greater(this._left(node), node)) || - (this._right(node) < this.size && this._greater(this._right(node), node)) - ) { - const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node))) - ? this._right(node) - : this._left(node); - this._swap(node, maxChild); - node = maxChild; - } + const info = await Promise.all(promises); + return new this(config, ...info); + } + /** + * Runs the model with the provided inputs. + * @param {Object} model_inputs Object containing input tensors. + * @returns {Promise} Object containing output tensors. + */ + async _call(model_inputs) { + return await this.forward(model_inputs); + } + /** + * Run the model's forward pass. + * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model. + * @returns {Promise} The output data from the model in the format specified in the ONNX model. + */ + async forward(model_inputs) { + return await this._forward(this, model_inputs); + } + /** + * Get the model's generation config, if it exists. + * @returns {GenerationConfig|null} The model's generation config if it exists, otherwise `null`. + */ + get generation_config() { + return this.configs?.generation_config ?? null; + } + /** + * @param {GenerationConfig} generation_config + * @param {number} input_ids_seq_length The starting sequence length for the input ids. + * @returns {LogitsProcessorList} + * @private + */ + _get_logits_processor(generation_config, input_ids_seq_length, logits_processor = null) { + const processors = new LogitsProcessorList(); + if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1) { + processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty)); } - - /** - * Get the index of the smallest element in the heap. Since we use an array-based heap, - * the index can be computed without needing to traverse the heap. - * @private - */ - _smallest() { - return (2 ** (Math.floor(Math.log2(this.size))) - 1); + if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) { + processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size)); } -} - -/** - * A trie structure to efficiently store and search for strings. - */ -class CharTrie { - constructor() { - this.root = CharTrieNode.default(); + if (generation_config.bad_words_ids !== null) { + processors.push( + new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id) + ); } - - /** - * Adds one or more `texts` to the trie. - * @param {string[]} texts The strings to add to the trie. - */ - extend(texts) { - for (const text of texts) { - this.push(text); - } + if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) { + processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id)); } - - /** - * Adds text to the trie. - * @param {string} text The string to add to the trie. - */ - push(text) { - let node = this.root; - for (const ch of text) { - let child = node.children.get(ch); - if (child === undefined) { - child = CharTrieNode.default(); - node.children.set(ch, child); - } - node = child; - } - node.isLeaf = true; + if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) { + processors.push( + new MinNewTokensLengthLogitsProcessor( + input_ids_seq_length, + generation_config.min_new_tokens, + generation_config.eos_token_id + ) + ); } - - /** - * Searches the trie for all strings with a common prefix of `text`. - * @param {string} text The common prefix to search for. - * @yields {string} Each string in the trie that has `text` as a prefix. - */ - *commonPrefixSearch(text) { - let node = this.root; - if (node === undefined) return; - - let prefix = ""; - for (const ch of text) { - prefix += ch; - node = node.children.get(ch); - if (node === undefined) return; - if (node.isLeaf) { - yield prefix; - } - } + if (generation_config.forced_bos_token_id !== null) { + processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id)); } -} - -/** - * Represents a node in a character trie. - */ -class CharTrieNode { - /** - * Create a new CharTrieNode. - * @param {boolean} isLeaf Whether the node is a leaf node or not. - * @param {Map} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`. - */ - constructor(isLeaf, children) { - this.isLeaf = isLeaf; - this.children = children; + if (generation_config.forced_eos_token_id !== null) { + processors.push( + new ForcedEOSTokenLogitsProcessor(generation_config.max_length, generation_config.forced_eos_token_id) + ); } - - /** - * Returns a new `CharTrieNode` instance with default values. - * @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map. - */ - static default() { - return new CharTrieNode(false, new Map()); + if (generation_config.suppress_tokens !== null) { + processors.push(new SuppressTokensLogitsProcessor(generation_config.suppress_tokens)); } -} - -/** - * A lattice data structure to be used for tokenization. - */ -class TokenLattice { - /** - * Creates a new TokenLattice instance. - * - * @param {string} sentence The input sentence to be tokenized. - * @param {number} bosTokenId The beginning-of-sequence token ID. - * @param {number} eosTokenId The end-of-sequence token ID. - */ - constructor(sentence, bosTokenId, eosTokenId) { - this.chars = Array.from(sentence); - this.len = this.chars.length; - this.bosTokenId = bosTokenId; - this.eosTokenId = eosTokenId; - this.nodes = []; - this.beginNodes = Array.from({ length: this.len + 1 }, () => []); - this.endNodes = Array.from({ length: this.len + 1 }, () => []); - - const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0); - const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0); - this.nodes.push(bos.clone()); - this.nodes.push(eos.clone()); - this.beginNodes[this.len].push(eos); - this.endNodes[0].push(bos); + if (generation_config.begin_suppress_tokens !== null) { + const begin_index = input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null ? input_ids_seq_length : input_ids_seq_length + 1; + processors.push( + new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index) + ); } - - /** - * Inserts a new token node into the token lattice. - * - * @param {number} pos The starting position of the token. - * @param {number} length The length of the token. - * @param {number} score The score of the token. - * @param {number} tokenId The token ID of the token. - */ - insert(pos, length, score, tokenId) { - const nodeId = this.nodes.length; - const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score); - this.beginNodes[pos].push(node); - this.endNodes[pos + length].push(node); - this.nodes.push(node); + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + processors.push(new ClassifierFreeGuidanceLogitsProcessor(generation_config.guidance_scale)); } - - /** - * Implements the Viterbi algorithm to compute the most likely sequence of tokens. - * - * @returns {TokenLatticeNode[]} The most likely sequence of tokens. - */ - viterbi() { - const len = this.len; - let pos = 0; - while (pos <= len) { - if (this.beginNodes[pos].length == 0) { - return []; - } - for (let rnode of this.beginNodes[pos]) { - rnode.prev = null; - let bestScore = 0.0; - let bestNode = null; - for (let lnode of this.endNodes[pos]) { - const score = lnode.backtraceScore + rnode.score; - if (bestNode === null || score > bestScore) { - bestNode = lnode.clone(); - bestScore = score; - } - } - - if (bestNode !== null) { - rnode.prev = bestNode; - rnode.backtraceScore = bestScore; - } else { - return []; - } - } - ++pos; - } - - const results = []; - const root = this.beginNodes[len][0]; - const prev = root.prev; - if (prev === null) { - return []; - } - - let node = prev.clone(); - while (node.prev !== null) { - results.push(node.clone()); - const n = node.clone(); - node = n.prev.clone(); - } - - results.reverse(); - return results; + if (generation_config.temperature === 0 && generation_config.do_sample) { + logger.warn( + "`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`." + ); + generation_config.do_sample = false; } - - /** - * @param {TokenLatticeNode} node - * @returns {string} The array of nodes representing the most likely sequence of tokens. - */ - piece(node) { - return this.chars.slice(node.pos, node.pos + node.length).join(''); + if (generation_config.do_sample) { + if (generation_config.temperature !== null && generation_config.temperature !== 1) { + processors.push(new TemperatureLogitsWarper(generation_config.temperature)); + } } - - /** - * @returns {string[]} The most likely sequence of tokens. - */ - tokens() { - const nodes = this.viterbi(); - return nodes.map(x => this.piece(x)); + if (logits_processor !== null) { + processors.extend(logits_processor); } - - /** - * @returns {number[]} The most likely sequence of token ids. - */ - tokenIds() { - const nodes = this.viterbi(); - return nodes.map(x => x.tokenId); + return processors; + } + /** + * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation. + * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object. + * @param {GenerationConfig|null} generation_config A `GenerationConfig` object containing generation parameters. + * @param {Object} kwargs Additional generation parameters to be used in place of those in the `generation_config` object. + * @returns {GenerationConfig} The final generation config object to be used by the model for text generation. + */ + _prepare_generation_config(generation_config, kwargs, cls = GenerationConfig) { + const config = { ...this.config }; + for (const key of ["decoder", "generator", "text_config"]) { + if (key in config) { + Object.assign(config, config[key]); + } } -} -class TokenLatticeNode { - /** - * Represents a node in a token lattice for a given sentence. - * @param {number} tokenId The ID of the token associated with this node. - * @param {number} nodeId The ID of this node. - * @param {number} pos The starting position of the token in the sentence. - * @param {number} length The length of the token. - * @param {number} score The score associated with the token. - */ - constructor(tokenId, nodeId, pos, length, score) { - this.tokenId = tokenId; - this.nodeId = nodeId; - this.pos = pos; - this.length = length; - this.score = score; - this.prev = null; - this.backtraceScore = 0.0; + const gen_config = new cls(config); + Object.assign(gen_config, this.generation_config ?? {}); + if (generation_config) { + Object.assign(gen_config, generation_config); } - - /** - * Returns a clone of this node. - * @returns {TokenLatticeNode} A clone of this node. - */ - clone() { - const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score); - n.prev = this.prev; - n.backtraceScore = this.backtraceScore; - return n; + if (kwargs) { + Object.assign(gen_config, pick(kwargs, Object.getOwnPropertyNames(gen_config))); } -} - -/** - * A data structure which uses a trie to split a string into tokens based on a dictionary. - * It can also use a regular expression to preprocess the input text before splitting. - * - * NOTE: To ensure multi-byte characters are handled correctly, we operate at byte-level instead of character-level. - */ -class DictionarySplitter { - /** - * @param {string[]} dictionary The dictionary of words to use for splitting. - */ - constructor(dictionary) { - this.trie = this._buildTrie(dictionary); + return gen_config; + } + /** + * + * @param {GenerationConfig} generation_config + * @param {import('../generation/stopping_criteria.js').StoppingCriteria|import('../generation/stopping_criteria.js').StoppingCriteria[]|StoppingCriteriaList} [stopping_criteria=null] + */ + _get_stopping_criteria(generation_config, stopping_criteria = null) { + const criteria = new StoppingCriteriaList(); + if (generation_config.max_length !== null) { + criteria.push( + new MaxLengthCriteria(generation_config.max_length, this.config.max_position_embeddings ?? null) + ); } - - /** - * Builds a trie from the given dictionary. - * @param {string[]} dictionary The dictionary of words to build the trie from. - * @returns {Object} The root node of the trie. - * @private - */ - _buildTrie(dictionary) { - const trie = Object.create(null); - for (const word of dictionary) { - let node = trie; - for (let i = 0; i < word.length; ++i) { - node = (node[word[i]] ??= Object.create(null)); - } - node.end = word; - } - return trie; + if (generation_config.eos_token_id !== null) { + criteria.push(new EosTokenCriteria(generation_config.eos_token_id)); } - - /** - * Splits the input text into tokens based on the dictionary. - * @param {string} text The input text to split. - * @returns {string[]} An array of tokens. - */ - split(text) { - const result = []; - const n = text.length; - let start = 0; - let i = 0; - - while (i < n) { - let node = this.trie; - let match = null; - let j = i; - - while (j < n && (node = node[text[j]])) { - if (node.end) { - // Always keep the last (i.e., longest) match. - match = node.end; - } - ++j; - } - - if (match) { - if (i > start) { - result.push(text.slice(start, i)); - } - result.push(match); - i += match.length; - start = i; - } else { - ++i; - } - } - if (start < n) { - result.push(text.slice(start)); + if (stopping_criteria) { + criteria.extend(stopping_criteria); + } + return criteria; + } + /** + * Confirms that the model class is compatible with generation. + * If not, raises an exception that points to the right class to use. + */ + _validate_model_class() { + if (!this.can_generate) { + const generate_compatible_mappings = [ + MODEL_MAPPING_NAMES.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, + // MODEL_MAPPING_NAMES.MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, // TODO + MODEL_MAPPING_NAMES.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, + MODEL_MAPPING_NAMES.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_MAPPING_NAMES.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES + ].filter(Boolean); + const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor); + const generate_compatible_classes = /* @__PURE__ */ new Set(); + const modelType = this.config.model_type; + for (const model_mapping of generate_compatible_mappings) { + const supported_models = model_mapping?.get(modelType); + if (supported_models) { + generate_compatible_classes.add(supported_models); } - return result; + } + let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`; + if (generate_compatible_classes.size > 0) { + errorMessage += ` Please use the following class instead: ${[...generate_compatible_classes].join(", ")}`; + } + throw Error(errorMessage); } -} - -/** -* A simple Least Recently Used (LRU) cache implementation in JavaScript. -* This cache stores key-value pairs and evicts the least recently used item -* when the capacity is exceeded. -*/ -class LRUCache { - /** - * Creates an LRUCache instance. - * @param {number} capacity The maximum number of items the cache can hold. - */ - constructor(capacity) { - this.capacity = capacity; - this.cache = new Map(); + } + prepare_inputs_for_generation(...args) { + if (!this._prepare_inputs_for_generation) { + throw new Error("prepare_inputs_for_generation is not implemented for this model."); } - - /** - * Retrieves the value associated with the given key and marks the key as recently used. - * @param {any} key The key to retrieve. - * @returns {any} The value associated with the key, or undefined if the key does not exist. - */ - get(key) { - if (!this.cache.has(key)) return undefined; - const value = this.cache.get(key); - this.cache.delete(key); - this.cache.set(key, value); - return value; + return this._prepare_inputs_for_generation(this, ...args); + } + /** + * + * @param {Object} inputs + * @param {bigint[][]} inputs.generated_input_ids + * @param {Object} inputs.outputs + * @param {Object} inputs.model_inputs + * @param {boolean} inputs.is_encoder_decoder + * @returns {Object} The updated model inputs for the next generation iteration. + */ + _update_model_kwargs_for_generation({ generated_input_ids, outputs, model_inputs, is_encoder_decoder }) { + model_inputs["past_key_values"] = getPastKeyValues(outputs, model_inputs.past_key_values); + model_inputs["input_ids"] = new Tensor3("int64", generated_input_ids.flat(), [generated_input_ids.length, 1]); + if (!is_encoder_decoder) { + model_inputs.attention_mask = cat( + [model_inputs.attention_mask, ones([model_inputs.attention_mask.dims[0], 1])], + 1 + ); + } else if ("decoder_attention_mask" in model_inputs) { + model_inputs.decoder_attention_mask = cat( + [model_inputs.decoder_attention_mask, ones([model_inputs.decoder_attention_mask.dims[0], 1])], + 1 + ); } - - /** - * Inserts or updates the key-value pair in the cache. - * If the key already exists, it is updated and marked as recently used. - * If the cache exceeds its capacity, the least recently used item is evicted. - * @param {any} key The key to add or update. - * @param {any} value The value to associate with the key. - */ - put(key, value) { - if (this.cache.has(key)) { - this.cache.delete(key); - } - this.cache.set(key, value); - if (this.cache.size > this.capacity) { - this.cache.delete(this.cache.keys().next().value); - } + model_inputs["position_ids"] = null; + return model_inputs; + } + /** + * This function extracts the model-specific `inputs` for generation. + * @param {Object} params + * @param {Tensor} [params.inputs=null] + * @param {number} [params.bos_token_id=null] + * @param {Record} [params.model_kwargs] + * @returns {{inputs_tensor: Tensor, model_inputs: Record & {past_key_values?: DynamicCache}, model_input_name: string}} The model-specific inputs for generation. + */ + _prepare_model_inputs({ inputs, bos_token_id, model_kwargs }) { + const model_inputs = pick(model_kwargs, this.forward_params); + const input_name = this.main_input_name; + if (input_name in model_inputs) { + if (inputs) { + throw new Error( + "`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=..." + ); + } + } else { + model_inputs[input_name] = inputs; } - - /** - * Clears the cache. - */ - clear() { - this.cache.clear(); + const inputs_tensor = model_inputs[input_name]; + return { inputs_tensor, model_inputs, model_input_name: input_name }; + } + async _prepare_encoder_decoder_kwargs_for_generation({ + inputs_tensor, + model_inputs, + model_input_name, + generation_config + }) { + if (this.sessions["model"].inputNames.includes("inputs_embeds") && !model_inputs.inputs_embeds && "_prepare_inputs_embeds" in this) { + const { input_ids, pixel_values, attention_mask, ...kwargs } = model_inputs; + const prepared_inputs = await this._prepare_inputs_embeds(model_inputs); + model_inputs = { + ...kwargs, + ...pick(prepared_inputs, ["inputs_embeds", "attention_mask"]) + }; + } + let { last_hidden_state } = await encoder_forward(this, model_inputs); + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + last_hidden_state = cat([last_hidden_state, full_like(last_hidden_state, 0)], 0); + if ("attention_mask" in model_inputs) { + model_inputs["attention_mask"] = cat( + [model_inputs["attention_mask"], zeros_like(model_inputs["attention_mask"])], + 0 + ); + } + } else if (model_inputs.decoder_input_ids) { + const decoder_input_ids_batch_size = toI64Tensor(model_inputs.decoder_input_ids).dims[0]; + if (decoder_input_ids_batch_size !== last_hidden_state.dims[0]) { + if (last_hidden_state.dims[0] !== 1) { + throw new Error( + `The encoder outputs have a different batch size (${last_hidden_state.dims[0]}) than the decoder inputs (${decoder_input_ids_batch_size}).` + ); + } + last_hidden_state = cat( + Array.from({ length: decoder_input_ids_batch_size }, () => last_hidden_state), + 0 + ); + } } -} - - -/***/ }), - -/***/ "./src/utils/devices.js": -/*!******************************!*\ - !*** ./src/utils/devices.js ***! - \******************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DEVICE_TYPES: () => (/* binding */ DEVICE_TYPES) -/* harmony export */ }); - -/** - * The list of devices supported by Transformers.js - */ -const DEVICE_TYPES = Object.freeze({ - auto: 'auto', // Auto-detect based on device and environment - gpu: 'gpu', // Auto-detect GPU - cpu: 'cpu', // CPU - wasm: 'wasm', // WebAssembly - webgpu: 'webgpu', // WebGPU - cuda: 'cuda', // CUDA - dml: 'dml', // DirectML - - webnn: 'webnn', // WebNN (default) - 'webnn-npu': 'webnn-npu', // WebNN NPU - 'webnn-gpu': 'webnn-gpu', // WebNN GPU - 'webnn-cpu': 'webnn-cpu', // WebNN CPU -}); - -/** - * @typedef {keyof typeof DEVICE_TYPES} DeviceType - */ - - -/***/ }), - -/***/ "./src/utils/dtypes.js": -/*!*****************************!*\ - !*** ./src/utils/dtypes.js ***! - \*****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DATA_TYPES: () => (/* binding */ DATA_TYPES), -/* harmony export */ DEFAULT_DEVICE_DTYPE_MAPPING: () => (/* binding */ DEFAULT_DEVICE_DTYPE_MAPPING), -/* harmony export */ DEFAULT_DTYPE_SUFFIX_MAPPING: () => (/* binding */ DEFAULT_DTYPE_SUFFIX_MAPPING), -/* harmony export */ isWebGpuFp16Supported: () => (/* binding */ isWebGpuFp16Supported) -/* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); -/* harmony import */ var _devices_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./devices.js */ "./src/utils/devices.js"); -/// - - - - - -// TODO: Use the adapter from `env.backends.onnx.webgpu.adapter` to check for `shader-f16` support, -// when available in https://github.com/microsoft/onnxruntime/pull/19940. -// For more information, see https://github.com/microsoft/onnxruntime/pull/19857#issuecomment-1999984753 - -/** - * Checks if WebGPU fp16 support is available in the current environment. - */ -const isWebGpuFp16Supported = (function () { - /** @type {boolean} */ - let cachedResult; - - return async function () { - if (cachedResult === undefined) { - if (!_env_js__WEBPACK_IMPORTED_MODULE_0__.apis.IS_WEBGPU_AVAILABLE) { - cachedResult = false; - } else { - try { - const adapter = await navigator.gpu.requestAdapter(); - cachedResult = adapter.features.has('shader-f16'); - } catch (e) { - cachedResult = false; - } - } + model_inputs["encoder_outputs"] = last_hidden_state; + return model_inputs; + } + /** + * Prepares `decoder_input_ids` for generation with encoder-decoder models + * @param {*} param0 + */ + _prepare_decoder_input_ids_for_generation({ + batch_size, + model_input_name, + model_kwargs, + decoder_start_token_id, + bos_token_id, + generation_config + }) { + let { decoder_input_ids, ...model_inputs } = model_kwargs; + if (!(decoder_input_ids instanceof Tensor3)) { + if (!decoder_input_ids) { + decoder_start_token_id ??= bos_token_id; + if (this.config.model_type === "musicgen") { + decoder_input_ids = Array.from( + { + // @ts-expect-error TS2339 + length: batch_size * this.config.decoder.num_codebooks + }, + () => [decoder_start_token_id] + ); + } else if (Array.isArray(decoder_start_token_id)) { + if (decoder_start_token_id.length !== batch_size) { + throw new Error( + `\`decoder_start_token_id\` expected to have length ${batch_size} but got ${decoder_start_token_id.length}` + ); + } + decoder_input_ids = decoder_start_token_id; + } else { + decoder_input_ids = Array.from( + { + length: batch_size + }, + () => [decoder_start_token_id] + ); + } + } else if (!Array.isArray(decoder_input_ids[0])) { + decoder_input_ids = Array.from( + { + length: batch_size + }, + () => decoder_input_ids + ); + } + decoder_input_ids = toI64Tensor(decoder_input_ids); + } + model_inputs["decoder_attention_mask"] = ones_like(decoder_input_ids); + return { input_ids: decoder_input_ids, model_inputs }; + } + /** + * Generate token sequences with a language-modeling head. + * @param {import('../generation/parameters.js').GenerationFunctionParameters} options + * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. + */ + async generate({ + inputs = null, + generation_config = null, + logits_processor = null, + stopping_criteria = null, + streamer = null, + // inputs_attention_mask = null, + ...kwargs + }) { + this._validate_model_class(); + generation_config = this._prepare_generation_config(generation_config, kwargs); + let { inputs_tensor, model_inputs, model_input_name } = this._prepare_model_inputs({ + inputs, + model_kwargs: ( + /** @type {Record} */ + kwargs + ) + }); + const is_encoder_decoder = this.config.is_encoder_decoder; + if (!is_encoder_decoder) { + } else if (!("encoder_outputs" in model_inputs)) { + model_inputs = await this._prepare_encoder_decoder_kwargs_for_generation({ + inputs_tensor, + model_inputs, + model_input_name, + generation_config + }); + } + let input_ids; + if (is_encoder_decoder) { + ({ input_ids, model_inputs } = this._prepare_decoder_input_ids_for_generation({ + batch_size: model_inputs[model_input_name].dims.at(0), + model_input_name, + model_kwargs: model_inputs, + decoder_start_token_id: generation_config.decoder_start_token_id, + bos_token_id: generation_config.bos_token_id, + generation_config + })); + } else { + input_ids = model_inputs[model_input_name]; + } + let input_ids_length = input_ids.dims.at(-1); + if (generation_config.max_new_tokens !== null) { + generation_config.max_length = input_ids_length + generation_config.max_new_tokens; + } + const prepared_logits_processor = this._get_logits_processor( + generation_config, + input_ids_length, + logits_processor + ); + const prepared_stopping_criteria = this._get_stopping_criteria(generation_config, stopping_criteria); + const numInputs = model_inputs[model_input_name].dims.at(0); + const sampler = LogitsSampler.getSampler(generation_config); + const scores = new Array(numInputs).fill(0); + const all_input_ids = input_ids.tolist(); + if (streamer) { + streamer.put(all_input_ids); + } + let outputs; + let attentions = {}; + let return_dict_items = {}; + while (true) { + model_inputs = this.prepare_inputs_for_generation(all_input_ids, model_inputs, generation_config); + outputs = await this.forward(model_inputs); + if (generation_config.return_dict_in_generate) { + if (generation_config.output_attentions) { + const token_attentions = getAttentions(outputs); + for (const key in token_attentions) { + if (!(key in attentions)) { + attentions[key] = []; + } + attentions[key].push(token_attentions[key]); + } + } else if (this._return_dict_in_generate_keys) { + Object.assign(return_dict_items, pick(outputs, this._return_dict_in_generate_keys)); } - return cachedResult; - }; -})(); - -const DATA_TYPES = Object.freeze({ - auto: 'auto', // Auto-detect based on environment - fp32: 'fp32', - fp16: 'fp16', - q8: 'q8', - int8: 'int8', - uint8: 'uint8', - q4: 'q4', - bnb4: 'bnb4', - q4f16: 'q4f16', // fp16 model with int4 block weight quantization -}); -/** @typedef {keyof typeof DATA_TYPES} DataType */ - -const DEFAULT_DEVICE_DTYPE_MAPPING = Object.freeze({ - // NOTE: If not specified, will default to fp32 - [_devices_js__WEBPACK_IMPORTED_MODULE_1__.DEVICE_TYPES.wasm]: DATA_TYPES.q8, -}); - -/** @type {Record, string>} */ -const DEFAULT_DTYPE_SUFFIX_MAPPING = Object.freeze({ - [DATA_TYPES.fp32]: '', - [DATA_TYPES.fp16]: '_fp16', - [DATA_TYPES.int8]: '_int8', - [DATA_TYPES.uint8]: '_uint8', - [DATA_TYPES.q8]: '_quantized', - [DATA_TYPES.q4]: '_q4', - [DATA_TYPES.q4f16]: '_q4f16', - [DATA_TYPES.bnb4]: '_bnb4', -}); - - -/***/ }), - -/***/ "./src/utils/generic.js": -/*!******************************!*\ - !*** ./src/utils/generic.js ***! - \******************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ Callable: () => (/* binding */ Callable) -/* harmony export */ }); - -/** - * A base class for creating callable objects. - * See [here](https://stackoverflow.com/q/76073890) for more information. - * - * @type {new () => {(...args: any[]): any, _call(...args: any[]): any}} - */ -const Callable = /** @type {any} */ (class { - /** - * Creates a new instance of the Callable class. - */ - constructor() { - /** - * Creates a closure that delegates to a private method '_call' with the given arguments. - * @type {any} - * @param {...any} args Zero or more arguments to pass to the '_call' method. - * @returns {*} The result of calling the '_call' method. - */ - let closure = function (...args) { - return closure._call(...args) + } + const logits = outputs.logits.slice(null, -1, null).to("float32"); + const next_tokens_scores = prepared_logits_processor(all_input_ids, logits); + const generated_input_ids = []; + for (let batch_idx = 0; batch_idx < next_tokens_scores.dims.at(0); ++batch_idx) { + const logs = next_tokens_scores[batch_idx]; + const sampledTokens = await sampler(logs); + for (const [newTokenId, logProb] of sampledTokens) { + const bigint = BigInt(newTokenId); + scores[batch_idx] += logProb; + all_input_ids[batch_idx].push(bigint); + generated_input_ids.push([bigint]); + break; } - return Object.setPrototypeOf(closure, new.target.prototype) + } + if (streamer) { + streamer.put(generated_input_ids); + } + const stop = prepared_stopping_criteria(all_input_ids); + if (stop.every((x) => x)) { + break; + } + model_inputs = this._update_model_kwargs_for_generation({ + generated_input_ids, + outputs, + model_inputs, + is_encoder_decoder + }); } - - /** - * This method should be implemented in subclasses to provide the - * functionality of the callable object. - * - * @param {any[]} args - * @throws {Error} If the subclass does not implement the `_call` method. - */ - _call(...args) { - throw Error('Must implement _call method in subclass') + if (streamer) { + streamer.end(); } -}); - - -/***/ }), - -/***/ "./src/utils/hub.js": -/*!**************************!*\ - !*** ./src/utils/hub.js ***! - \**************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ MAX_EXTERNAL_DATA_CHUNKS: () => (/* binding */ MAX_EXTERNAL_DATA_CHUNKS), -/* harmony export */ getFile: () => (/* binding */ getFile), -/* harmony export */ getModelFile: () => (/* binding */ getModelFile), -/* harmony export */ getModelJSON: () => (/* binding */ getModelJSON), -/* harmony export */ getModelText: () => (/* binding */ getModelText) -/* harmony export */ }); -/* harmony import */ var node_fs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! node:fs */ "?7992"); -/* harmony import */ var node_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! node:path */ "?5af5"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); -/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./core.js */ "./src/utils/core.js"); - -/** - * @file Utility functions to interact with the Hugging Face Hub (https://huggingface.co/models) - * - * @module utils/hub - */ - - - - - - - -/** - * @typedef {boolean|number} ExternalData Whether to load the model using the external data format (used for models >= 2GB in size). - * If `true`, the model will be loaded using the external data format. - * If a number, this many chunks will be loaded using the external data format (of the form: "model.onnx_data[_{chunk_number}]"). - */ -const MAX_EXTERNAL_DATA_CHUNKS = 100; - -/** - * @typedef {Object} PretrainedOptions Options for loading a pretrained model. - * @property {import('./core.js').ProgressCallback} [progress_callback=null] If specified, this function will be called during model construction, to provide the user with progress updates. - * @property {import('../configs.js').PretrainedConfig} [config=null] Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: - * - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). - * - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory. - * @property {string} [cache_dir=null] Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. - * @property {boolean} [local_files_only=false] Whether or not to only look at local files (e.g., not try downloading the model). - * @property {string} [revision='main'] The specific model version to use. It can be a branch name, a tag name, or a commit id, - * since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. - * NOTE: This setting is ignored for local requests. - */ - -/** - * @typedef {Object} ModelSpecificPretrainedOptions Options for loading a pretrained model. - * @property {string} [subfolder='onnx'] In case the relevant files are located inside a subfolder of the model repo on huggingface.co, - * you can specify the folder name here. - * @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models. - * @property {import("./devices.js").DeviceType|Record} [device=null] The device to run the model on. If not specified, the device will be chosen from the environment settings. - * @property {import("./dtypes.js").DataType|Record} [dtype=null] The data type to use for the model. If not specified, the data type will be chosen from the environment settings. - * @property {ExternalData|Record} [use_external_data_format=false] Whether to load the model using the external data format (used for models >= 2GB in size). - * @property {import('onnxruntime-common').InferenceSession.SessionOptions} [session_options] (Optional) User-specified session options passed to the runtime. If not provided, suitable defaults will be chosen. - */ - -/** - * @typedef {PretrainedOptions & ModelSpecificPretrainedOptions} PretrainedModelOptions Options for loading a pretrained model. - */ - -/** - * Mapping from file extensions to MIME types. - */ -const CONTENT_TYPE_MAP = { - '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 FileResponse { - - /** - * Creates a new `FileResponse` object. - * @param {string} filePath - */ - constructor(filePath) { - this.filePath = filePath; - this.headers = new Headers(); - - this.exists = node_fs__WEBPACK_IMPORTED_MODULE_0__.existsSync(filePath); - if (this.exists) { - this.status = 200; - this.statusText = 'OK'; - - let stats = node_fs__WEBPACK_IMPORTED_MODULE_0__.statSync(filePath); - this.headers.set('content-length', stats.size.toString()); - - this.updateContentType(); - - const stream = node_fs__WEBPACK_IMPORTED_MODULE_0__.createReadStream(filePath); - this.body = new ReadableStream({ - start(controller) { - stream.on('data', (chunk) => controller.enqueue(chunk)); - stream.on('end', () => controller.close()); - stream.on('error', (err) => controller.error(err)); - }, - cancel() { - stream.destroy(); - } - }); - } else { - this.status = 404; - this.statusText = 'Not Found'; - this.body = null; - } + const sequences = new Tensor3("int64", all_input_ids.flat(), [all_input_ids.length, all_input_ids[0].length]); + const past_key_values = getPastKeyValues(outputs, model_inputs.past_key_values); + const cachedTensors = new Set(Object.values(past_key_values)); + for (const tensor of Object.values(outputs)) { + if (tensor.location === "gpu-buffer" && !cachedTensors.has(tensor)) { + tensor.dispose(); + } } - - /** - * Updates the 'content-type' header property of the response based on the extension of - * the file specified by the filePath property of the current object. - * @returns {void} - */ - updateContentType() { - // Set content-type header based on file extension - const extension = this.filePath.toString().split('.').pop().toLowerCase(); - this.headers.set('content-type', CONTENT_TYPE_MAP[extension] ?? 'application/octet-stream'); + const keepCacheAlive = "past_key_values" in kwargs || generation_config.return_dict_in_generate; + if (!keepCacheAlive) { + await past_key_values.dispose(); } - - /** - * Clone the current FileResponse object. - * @returns {FileResponse} A new FileResponse object with the same properties as the current object. - */ - clone() { - let response = new FileResponse(this.filePath); - response.exists = this.exists; - response.status = this.status; - response.statusText = this.statusText; - response.headers = new Headers(this.headers); - return response; + if (generation_config.return_dict_in_generate) { + return { + sequences, + past_key_values, + ...attentions, + ...return_dict_items + // TODO: + // scores, + // logits, + }; } - - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with an ArrayBuffer containing the file's contents. - * @returns {Promise} A Promise that resolves with an ArrayBuffer containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async arrayBuffer() { - const data = await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath); - return /** @type {ArrayBuffer} */ (data.buffer); + return sequences; + } + /** + * Helper function to select valid inputs and run through the appropriate encoder (vision, text, audio) based on the input type. + * @param {string} sessionName + * @param {Record} inputs + * @param {string} outputName + * @private + */ + async _encode_input(sessionName, inputs, outputName) { + if (!Object.hasOwn(this.sessions, sessionName)) { + throw new Error(`Model does not have a ${sessionName} session.`); } - - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with a Blob containing the file's contents. - * @returns {Promise} A Promise that resolves with a Blob containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async blob() { - const data = await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath); - return new Blob([data], { type: this.headers.get('content-type') }); + const session = this.sessions[sessionName]; + const output = await sessionRun(session, pick(inputs, session.inputNames)); + return output[outputName]; + } + /** + * Encode image inputs into features for multimodal generation. + * @param {any} inputs Vision encoder inputs. + * @returns {Promise} Image features. + * @internal + */ + async encode_image(inputs) { + return this._encode_input("vision_encoder", inputs, "image_features"); + } + /** + * Encode token ids into embeddings for multimodal generation. + * @param {any} inputs Text encoder inputs. + * @returns {Promise} Text embeddings. + * @internal + */ + async encode_text(inputs) { + return this._encode_input("embed_tokens", inputs, "inputs_embeds"); + } + /** + * Encode audio inputs into features for multimodal generation. + * @param {any} inputs Audio encoder inputs. + * @returns {Promise} Audio features. + * @internal + */ + async encode_audio(inputs) { + return this._encode_input("audio_encoder", inputs, "audio_features"); + } +}; +async function seq2seq_forward(self2, model_inputs) { + let { encoder_outputs, input_ids, decoder_input_ids, decoder_attention_mask, ...other_decoder_inputs } = model_inputs; + if (!encoder_outputs) { + const encoder_inputs = pick(model_inputs, self2.sessions["model"].inputNames); + encoder_outputs = (await encoder_forward(self2, encoder_inputs)).last_hidden_state; + } + other_decoder_inputs.input_ids = decoder_input_ids; + other_decoder_inputs.encoder_hidden_states = encoder_outputs; + if (self2.sessions["decoder_model_merged"].inputNames.includes("encoder_attention_mask")) { + other_decoder_inputs.encoder_attention_mask = model_inputs.attention_mask; + } + if (decoder_attention_mask && !other_decoder_inputs.attention_mask) { + other_decoder_inputs.attention_mask = decoder_attention_mask; + } + return await decoder_forward(self2, other_decoder_inputs, true); +} +async function encoder_forward(self2, model_inputs) { + const session = self2.sessions["model"]; + const encoderFeeds = pick(model_inputs, session.inputNames); + if (session.inputNames.includes("inputs_embeds") && !encoderFeeds.inputs_embeds) { + if (!model_inputs.input_ids) { + throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs."); } - - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with a string containing the file's contents. - * @returns {Promise} A Promise that resolves with a string containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async text() { - const data = await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.readFile(this.filePath, 'utf8'); - return data; + encoderFeeds.inputs_embeds = await self2.encode_text({ input_ids: model_inputs.input_ids }); + } + if (session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) { + if (!encoderFeeds.input_ids) { + throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs."); } - - /** - * Reads the contents of the file specified by the filePath property and returns a Promise that - * resolves with a parsed JavaScript object containing the file's contents. - * - * @returns {Promise} A Promise that resolves with a parsed JavaScript object containing the file's contents. - * @throws {Error} If the file cannot be read. - */ - async json() { - return JSON.parse(await this.text()); + encoderFeeds.token_type_ids = zeros_like(encoderFeeds.input_ids); + } + if (session.inputNames.includes("pixel_mask") && !encoderFeeds.pixel_mask) { + if (!encoderFeeds.pixel_values) { + throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs."); + } + const dims = encoderFeeds.pixel_values.dims; + encoderFeeds.pixel_mask = ones([dims[0], dims[2], dims[3]]); + } + return await sessionRun(session, encoderFeeds); +} +async function auto_encoder_forward(self2, model_inputs) { + const encoded = await self2.encode(model_inputs); + const decoded = await self2.decode(encoded); + return decoded; +} +function getPastKeyValues(decoderResults, pastKeyValues) { + const pkvs = /* @__PURE__ */ Object.create(null); + for (const name in decoderResults) { + if (name.startsWith("present")) { + const newName = name.replace("present_ssm", "past_ssm").replace("present_conv", "past_conv").replace("present_recurrent", "past_recurrent").replace("present_compressor", "past_compressor").replace("present_indexer", "past_indexer").replace("present", "past_key_values"); + const is_encoder_pkv = name.includes("encoder"); + if (is_encoder_pkv && pastKeyValues) { + pkvs[newName] = pastKeyValues[newName]; + } else { + pkvs[newName] = decoderResults[name]; + } + } + } + if (pastKeyValues) { + pastKeyValues.update(pkvs); + return pastKeyValues; + } + return new DynamicCache(pkvs); +} +function getAttentions(model_output) { + const attentions = {}; + for (const attnName of ["cross_attentions", "encoder_attentions", "decoder_attentions"]) { + for (const name in model_output) { + if (name.startsWith(attnName)) { + if (!(attnName in attentions)) { + attentions[attnName] = []; + } + attentions[attnName].push(model_output[name]); + } + } + } + return attentions; +} +function resolveCacheShape(metadataShape, symbols) { + return metadataShape.map((d) => { + if (typeof d === "number") return d; + return symbols[d] ?? 0; + }); +} +function addPastKeyValues(self2, decoderFeeds, pastKeyValues) { + if (pastKeyValues && Object.keys(pastKeyValues).length > 0) { + Object.assign(decoderFeeds, pastKeyValues); + return pastKeyValues; + } + const session = self2.sessions["decoder_model_merged"] ?? self2.sessions["model"]; + const batch_size = (decoderFeeds[self2.main_input_name] ?? decoderFeeds.attention_mask)?.dims?.[0] ?? 1; + const names = getCacheNames(self2.config); + const num_heads = self2.config?.normalized_config?.num_heads; + const symbols = { batch_size }; + if (typeof num_heads === "number") { + symbols["batch_size x num_heads"] = batch_size * num_heads; + } + const entries = /* @__PURE__ */ Object.create(null); + for (const meta of session.inputMetadata) { + if (!names.has(meta.name)) continue; + const shape = resolveCacheShape(meta.shape, symbols); + const size = shape.reduce((a, b) => a * b, 1); + const cls = DataTypeMap[meta.type]; + const t = new Tensor3(meta.type, new cls(size), shape); + decoderFeeds[meta.name] = t; + entries[meta.name] = t; + } + if (pastKeyValues) { + pastKeyValues.update(entries); + return pastKeyValues; + } + return new DynamicCache(entries); +} +function setNumLogitsToKeep(self2, model_inputs, value) { + if (model_inputs.num_logits_to_keep) return; + const session = self2.sessions["decoder_model_merged"] ?? self2.sessions["model"]; + if (session?.inputNames.includes("num_logits_to_keep")) { + model_inputs.num_logits_to_keep = new Tensor3("int64", [value], []); + } +} +async function decoder_forward(self2, model_inputs, is_encoder_decoder = false) { + const session = self2.sessions[is_encoder_decoder ? "decoder_model_merged" : "model"]; + const { past_key_values, ...new_model_inputs } = model_inputs; + if (session.inputNames.includes("use_cache_branch")) { + new_model_inputs.use_cache_branch = boolTensor( + past_key_values != null && Object.keys(past_key_values).length > 0 + ); + } + if (session.inputNames.includes("position_ids") && new_model_inputs.attention_mask && !new_model_inputs.position_ids) { + const start_index = ["paligemma", "gemma3_text", "gemma3"].includes(self2.config.model_type) ? 1 : 0; + new_model_inputs.position_ids = create_position_ids(new_model_inputs, past_key_values, start_index); + } + setNumLogitsToKeep(self2, new_model_inputs, 0n); + addPastKeyValues(self2, new_model_inputs, past_key_values); + const fixed = pick(new_model_inputs, session.inputNames); + return await sessionRun(session, fixed); +} +async function generic_text_to_text_forward(self2, { + // Generic parameters: + encode_function, + merge_function, + modality_input_names, + modality_output_name, + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + num_logits_to_keep = null, + // Additional parameters + ...kwargs +}) { + if (!inputs_embeds) { + inputs_embeds = await self2.encode_text({ input_ids, ...kwargs }); + const modality_values = pick(kwargs, modality_input_names); + if (Object.keys(modality_values).length > 0) { + if (input_ids.dims[1] !== 1) { + const modality_features = await encode_function({ + // Pass the modality values under its expected key. + // The caller knows whether this is audio or image. + ...modality_values, + ...kwargs + }); + ({ inputs_embeds, attention_mask } = merge_function({ + [modality_output_name]: modality_features, + inputs_embeds, + input_ids, + attention_mask + })); + } else if (past_key_values && input_ids.dims[1] === 1) { + const target_length = input_ids.dims[1]; + const past_length = past_key_values.get_seq_length(); + attention_mask = cat( + [ + ones([input_ids.dims[0], past_length]), + attention_mask.slice(null, [attention_mask.dims[1] - target_length, attention_mask.dims[1]]) + ], + 1 + ); + } + } + } + if (!position_ids) { + if ( + // Handle special case for qwen vl models + [ + "qwen2_vl", + "qwen2_vl_text", + "qwen2_5_vl", + "qwen2_5_vl_text", + "qwen3_vl", + "qwen3_vl_text", + "qwen3_vl_moe", + "qwen3_vl_moe_text", + "qwen3_5", + "qwen3_5_text", + "qwen3_5_moe", + "qwen3_5_moe_text", + "glm_ocr", + "glm_ocr_text" + ].includes(self2.config.model_type) + ) { + const { image_grid_thw, video_grid_thw } = kwargs; + [position_ids] = self2.get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask); } + } + const outputs = await decoder_forward( + self2, + { + inputs_embeds, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor, + num_logits_to_keep + }, + true + ); + return outputs; +} +async function audio_text_to_text_forward(self2, params) { + return await generic_text_to_text_forward(self2, { + ...params, + modality_input_names: ["audio_values", "input_features"], + modality_output_name: "audio_features", + encode_function: self2.encode_audio.bind(self2), + merge_function: self2._merge_input_ids_with_audio_features.bind(self2) + }); } - -/** - * Determines whether the given string is a valid URL. - * @param {string|URL} string The string to test for validity as an URL. - * @param {string[]} [protocols=null] A list of valid protocols. If specified, the protocol must be in this list. - * @param {string[]} [validHosts=null] A list of valid hostnames. If specified, the URL's hostname must be in this list. - * @returns {boolean} True if the string is a valid URL, false otherwise. - */ -function isValidUrl(string, protocols = null, validHosts = null) { - let url; - try { - url = new URL(string); - } catch (_) { - return false; +async function image_text_to_text_forward(self2, params) { + return await generic_text_to_text_forward(self2, { + ...params, + modality_input_names: ["pixel_values"], + modality_output_name: "image_features", + encode_function: self2.encode_image.bind(self2), + merge_function: self2._merge_input_ids_with_image_features.bind(self2) + }); +} +function cumsum_masked_fill(attention_mask, start_index = 0) { + const [bz, seq_len] = attention_mask.dims; + const attn_mask_data = attention_mask.data; + const data = new BigInt64Array(attn_mask_data.length); + for (let i = 0; i < bz; ++i) { + const start = i * seq_len; + let sum = BigInt(start_index); + for (let j2 = 0; j2 < seq_len; ++j2) { + const index = start + j2; + if (attn_mask_data[index] === 0n) { + data[index] = BigInt(1); + } else { + data[index] = sum; + sum += attn_mask_data[index]; + } } - if (protocols && !protocols.includes(url.protocol)) { - return false; + } + return { data, dims: attention_mask.dims }; +} +function create_position_ids(model_inputs, past_key_values = null, start_index = 0) { + const { input_ids, inputs_embeds, attention_mask } = model_inputs; + const { data, dims } = cumsum_masked_fill(attention_mask, start_index); + let position_ids = new Tensor3("int64", data, dims); + if (past_key_values) { + const offset = -(input_ids ?? inputs_embeds).dims.at(1); + position_ids = position_ids.slice(null, [offset, null]); + } + return position_ids; +} +function decoder_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) { + const past_length = model_inputs.past_key_values ? model_inputs.past_key_values.get_seq_length() : 0; + setNumLogitsToKeep(self2, model_inputs, 1n); + if (!model_inputs.attention_mask) { + let dims; + for (const key of ["input_ids", "inputs_embeds", "position_ids"]) { + if (model_inputs[key]) { + dims = model_inputs[key].dims; + break; + } } - if (validHosts && !validHosts.includes(url.hostname)) { - return false; + if (!dims) { + throw new Error("attention_mask is not provided, and unable to infer its shape from model inputs."); } - return true; -} - -const REPO_ID_REGEX = /^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/; - -/** - * Tests whether a string is a valid Hugging Face model ID or not. - * Adapted from https://github.com/huggingface/huggingface_hub/blob/6378820ebb03f071988a96c7f3268f5bdf8f9449/src/huggingface_hub/utils/_validators.py#L119-L170 - * - * @param {string} string The string to test - * @returns {boolean} True if the string is a valid model ID, false otherwise. - */ -function isValidHfModelId(string) { - if (!REPO_ID_REGEX.test(string)) return false; - if (string.includes("..") || string.includes("--")) return false; - if (string.endsWith(".git") || string.endsWith(".ipynb")) return false; - return true; -} - -/** - * Helper function to get a file, using either the Fetch API or FileSystem API. - * - * @param {URL|string} urlOrPath The URL/path of the file to get. - * @returns {Promise} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API). - */ -async function getFile(urlOrPath) { - - if (_env_js__WEBPACK_IMPORTED_MODULE_2__.env.useFS && !isValidUrl(urlOrPath, ["http:", "https:", "blob:"])) { - return new FileResponse( - urlOrPath instanceof URL - ? urlOrPath.protocol === "file:" - ? urlOrPath.pathname - : urlOrPath.toString() - : urlOrPath, - ); - } else if (typeof process !== 'undefined' && process?.release?.name === 'node') { - const IS_CI = !!process.env?.TESTING_REMOTELY; - const version = _env_js__WEBPACK_IMPORTED_MODULE_2__.env.version; - - const headers = new Headers(); - headers.set('User-Agent', `transformers.js/${version}; is_ci/${IS_CI};`); - - // Check whether we are making a request to the Hugging Face Hub. - const isHFURL = isValidUrl(urlOrPath, ['http:', 'https:'], ['huggingface.co', 'hf.co']); - if (isHFURL) { - // If an access token is present in the environment variables, - // we add it to the request headers. - // NOTE: We keep `HF_ACCESS_TOKEN` for backwards compatibility (as a fallback). - const token = process.env?.HF_TOKEN ?? process.env?.HF_ACCESS_TOKEN; - if (token) { - headers.set('Authorization', `Bearer ${token}`); - } - } - return fetch(urlOrPath, { headers }); + model_inputs.attention_mask = ones([dims[0], past_length + dims[1]]); + } + if (model_inputs.past_key_values) { + const { input_ids: input_ids2, attention_mask } = model_inputs; + if (attention_mask && attention_mask.dims[1] > input_ids2.dims[1]) { + } else if (past_length < input_ids2.dims[1]) { + model_inputs.input_ids = input_ids2.slice(null, [past_length, null]); } else { - // Running in a browser-environment, so we use default headers - // NOTE: We do not allow passing authorization headers in the browser, - // since this would require exposing the token to the client. - return fetch(urlOrPath); - } -} - -const ERROR_MAPPING = { - // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) - 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', - - // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses) - 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', -} -/** - * Helper method to handle fatal errors that occur while trying to load a file from the Hugging Face Hub. - * @param {number} status The HTTP status code of the error. - * @param {string} remoteURL The URL of the file that could not be loaded. - * @param {boolean} fatal Whether to raise an error if the file could not be loaded. - * @returns {null} Returns `null` if `fatal = true`. - * @throws {Error} If `fatal = false`. - */ -function handleError(status, remoteURL, fatal) { - if (!fatal) { - // File was not loaded correctly, but it is optional. - // TODO in future, cache the response? - return null; } - - const message = ERROR_MAPPING[status] ?? `Error (${status}) occurred while trying to load file`; - throw Error(`${message}: "${remoteURL}".`); + } + return model_inputs; } - -class FileCache { - /** - * Instantiate a `FileCache` object. - * @param {string} path - */ - constructor(path) { - this.path = path; +function encoder_decoder_prepare_inputs_for_generation(self2, input_ids, model_inputs, generation_config) { + if (model_inputs.past_key_values) { + input_ids = input_ids.map((x) => [x.at(-1)]); + } + setNumLogitsToKeep(self2, model_inputs, 1n); + return { + ...model_inputs, + decoder_input_ids: toI64Tensor(input_ids) + }; +} +function multimodal_text_to_text_prepare_inputs_for_generation(self2, ...args) { + if (self2.config.is_encoder_decoder) { + return encoder_decoder_prepare_inputs_for_generation(self2, ...args); + } else { + return decoder_prepare_inputs_for_generation(self2, ...args); + } +} +function default_merge_input_ids_with_features({ + modality_token_id, + inputs_embeds, + modality_features, + input_ids, + attention_mask +}) { + const token_positions = input_ids.tolist().map( + (ids) => ids.reduce((acc, x, idx) => { + if (x == modality_token_id) acc.push(idx); + return acc; + }, []) + ); + const n_tokens = token_positions.reduce((acc, x) => acc + x.length, 0); + const n_features = modality_features.dims[0]; + if (n_tokens !== n_features) { + throw new Error(`Number of tokens and features do not match: tokens: ${n_tokens}, features ${n_features}`); + } + let img = 0; + for (let i = 0; i < token_positions.length; ++i) { + const tokens = token_positions[i]; + const embeds = inputs_embeds[i]; + for (let j2 = 0; j2 < tokens.length; ++j2) { + embeds[tokens[j2]].data.set(modality_features[img++].data); } + } + return { inputs_embeds, attention_mask }; +} +function default_merge_input_ids_with_image_features({ + image_token_id, + inputs_embeds, + image_features, + input_ids, + attention_mask +}) { + return default_merge_input_ids_with_features({ + modality_token_id: image_token_id, + inputs_embeds, + modality_features: image_features, + input_ids, + attention_mask + }); +} +function default_merge_input_ids_with_audio_features({ + audio_token_id, + inputs_embeds, + audio_features, + input_ids, + attention_mask +}) { + return default_merge_input_ids_with_features({ + modality_token_id: audio_token_id, + inputs_embeds, + modality_features: audio_features, + input_ids, + attention_mask + }); +} +async function get_optional_configs(pretrained_model_name_or_path, names, options) { + return Object.fromEntries( + await Promise.all( + Object.keys(names).map(async (name) => { + const config = await getModelJSON(pretrained_model_name_or_path, names[name], false, options); + return [name, config]; + }) + ) + ); +} + +// src/models/models.js +var models_exports = {}; +__export(models_exports, { + ASTForAudioClassification: () => ASTForAudioClassification, + ASTModel: () => ASTModel, + ASTPreTrainedModel: () => ASTPreTrainedModel, + AfmoeForCausalLM: () => AfmoeForCausalLM, + AfmoeModel: () => AfmoeModel, + AfmoePreTrainedModel: () => AfmoePreTrainedModel, + AlbertForMaskedLM: () => AlbertForMaskedLM, + AlbertForQuestionAnswering: () => AlbertForQuestionAnswering, + AlbertForSequenceClassification: () => AlbertForSequenceClassification, + AlbertModel: () => AlbertModel, + AlbertPreTrainedModel: () => AlbertPreTrainedModel, + ApertusForCausalLM: () => ApertusForCausalLM, + ApertusModel: () => ApertusModel, + ApertusPreTrainedModel: () => ApertusPreTrainedModel, + ArceeForCausalLM: () => ArceeForCausalLM, + ArceeModel: () => ArceeModel, + ArceePreTrainedModel: () => ArceePreTrainedModel, + BartForConditionalGeneration: () => BartForConditionalGeneration, + BartForSequenceClassification: () => BartForSequenceClassification, + BartModel: () => BartModel, + BartPretrainedModel: () => BartPretrainedModel, + BaseModelOutput: () => BaseModelOutput, + BeitForImageClassification: () => BeitForImageClassification, + BeitModel: () => BeitModel, + BeitPreTrainedModel: () => BeitPreTrainedModel, + BertForMaskedLM: () => BertForMaskedLM, + BertForQuestionAnswering: () => BertForQuestionAnswering, + BertForSequenceClassification: () => BertForSequenceClassification, + BertForTokenClassification: () => BertForTokenClassification, + BertModel: () => BertModel, + BertPreTrainedModel: () => BertPreTrainedModel, + BlenderbotForConditionalGeneration: () => BlenderbotForConditionalGeneration, + BlenderbotModel: () => BlenderbotModel, + BlenderbotPreTrainedModel: () => BlenderbotPreTrainedModel, + BlenderbotSmallForConditionalGeneration: () => BlenderbotSmallForConditionalGeneration, + BlenderbotSmallModel: () => BlenderbotSmallModel, + BlenderbotSmallPreTrainedModel: () => BlenderbotSmallPreTrainedModel, + BloomForCausalLM: () => BloomForCausalLM, + BloomModel: () => BloomModel, + BloomPreTrainedModel: () => BloomPreTrainedModel, + CHMv2ForDepthEstimation: () => CHMv2ForDepthEstimation, + CHMv2PreTrainedModel: () => CHMv2PreTrainedModel, + CLIPModel: () => CLIPModel, + CLIPPreTrainedModel: () => CLIPPreTrainedModel, + CLIPSegForImageSegmentation: () => CLIPSegForImageSegmentation, + CLIPSegModel: () => CLIPSegModel, + CLIPSegPreTrainedModel: () => CLIPSegPreTrainedModel, + CLIPTextModel: () => CLIPTextModel, + CLIPTextModelWithProjection: () => CLIPTextModelWithProjection, + CLIPVisionModel: () => CLIPVisionModel, + CLIPVisionModelWithProjection: () => CLIPVisionModelWithProjection, + CamembertForMaskedLM: () => CamembertForMaskedLM, + CamembertForQuestionAnswering: () => CamembertForQuestionAnswering, + CamembertForSequenceClassification: () => CamembertForSequenceClassification, + CamembertForTokenClassification: () => CamembertForTokenClassification, + CamembertModel: () => CamembertModel, + CamembertPreTrainedModel: () => CamembertPreTrainedModel, + CausalLMOutput: () => CausalLMOutput, + CausalLMOutputWithPast: () => CausalLMOutputWithPast, + ChatterboxModel: () => ChatterboxModel, + ChatterboxPreTrainedModel: () => ChatterboxPreTrainedModel, + ChineseCLIPModel: () => ChineseCLIPModel, + ChineseCLIPPreTrainedModel: () => ChineseCLIPPreTrainedModel, + ClapAudioModelWithProjection: () => ClapAudioModelWithProjection, + ClapModel: () => ClapModel, + ClapPreTrainedModel: () => ClapPreTrainedModel, + ClapTextModelWithProjection: () => ClapTextModelWithProjection, + CodeGenForCausalLM: () => CodeGenForCausalLM, + CodeGenModel: () => CodeGenModel, + CodeGenPreTrainedModel: () => CodeGenPreTrainedModel, + Cohere2ForCausalLM: () => Cohere2ForCausalLM, + Cohere2Model: () => Cohere2Model, + Cohere2PreTrainedModel: () => Cohere2PreTrainedModel, + CohereAsrForConditionalGeneration: () => CohereAsrForConditionalGeneration, + CohereAsrModel: () => CohereAsrModel, + CohereAsrPreTrainedModel: () => CohereAsrPreTrainedModel, + CohereForCausalLM: () => CohereForCausalLM, + CohereModel: () => CohereModel, + CoherePreTrainedModel: () => CoherePreTrainedModel, + ConvBertForMaskedLM: () => ConvBertForMaskedLM, + ConvBertForQuestionAnswering: () => ConvBertForQuestionAnswering, + ConvBertForSequenceClassification: () => ConvBertForSequenceClassification, + ConvBertForTokenClassification: () => ConvBertForTokenClassification, + ConvBertModel: () => ConvBertModel, + ConvBertPreTrainedModel: () => ConvBertPreTrainedModel, + ConvNextForImageClassification: () => ConvNextForImageClassification, + ConvNextModel: () => ConvNextModel, + ConvNextPreTrainedModel: () => ConvNextPreTrainedModel, + ConvNextV2ForImageClassification: () => ConvNextV2ForImageClassification, + ConvNextV2Model: () => ConvNextV2Model, + ConvNextV2PreTrainedModel: () => ConvNextV2PreTrainedModel, + DFineForObjectDetection: () => DFineForObjectDetection, + DFineModel: () => DFineModel, + DFinePreTrainedModel: () => DFinePreTrainedModel, + DINOv3ConvNextModel: () => DINOv3ConvNextModel, + DINOv3ConvNextPreTrainedModel: () => DINOv3ConvNextPreTrainedModel, + DINOv3ViTModel: () => DINOv3ViTModel, + DINOv3ViTPreTrainedModel: () => DINOv3ViTPreTrainedModel, + DPTForDepthEstimation: () => DPTForDepthEstimation, + DPTModel: () => DPTModel, + DPTPreTrainedModel: () => DPTPreTrainedModel, + DacDecoderModel: () => DacDecoderModel, + DacDecoderOutput: () => DacDecoderOutput, + DacEncoderModel: () => DacEncoderModel, + DacEncoderOutput: () => DacEncoderOutput, + DacModel: () => DacModel, + DacPreTrainedModel: () => DacPreTrainedModel, + DebertaForMaskedLM: () => DebertaForMaskedLM, + DebertaForQuestionAnswering: () => DebertaForQuestionAnswering, + DebertaForSequenceClassification: () => DebertaForSequenceClassification, + DebertaForTokenClassification: () => DebertaForTokenClassification, + DebertaModel: () => DebertaModel, + DebertaPreTrainedModel: () => DebertaPreTrainedModel, + DebertaV2ForMaskedLM: () => DebertaV2ForMaskedLM, + DebertaV2ForQuestionAnswering: () => DebertaV2ForQuestionAnswering, + DebertaV2ForSequenceClassification: () => DebertaV2ForSequenceClassification, + DebertaV2ForTokenClassification: () => DebertaV2ForTokenClassification, + DebertaV2Model: () => DebertaV2Model, + DebertaV2PreTrainedModel: () => DebertaV2PreTrainedModel, + DecisionTransformerModel: () => DecisionTransformerModel, + DecisionTransformerPreTrainedModel: () => DecisionTransformerPreTrainedModel, + DeepseekV3ForCausalLM: () => DeepseekV3ForCausalLM, + DeepseekV3Model: () => DeepseekV3Model, + DeepseekV3PreTrainedModel: () => DeepseekV3PreTrainedModel, + DeepseekV4ForCausalLM: () => DeepseekV4ForCausalLM, + DeepseekV4Model: () => DeepseekV4Model, + DeepseekV4PreTrainedModel: () => DeepseekV4PreTrainedModel, + DeiTForImageClassification: () => DeiTForImageClassification, + DeiTModel: () => DeiTModel, + DeiTPreTrainedModel: () => DeiTPreTrainedModel, + DepthAnythingForDepthEstimation: () => DepthAnythingForDepthEstimation, + DepthAnythingPreTrainedModel: () => DepthAnythingPreTrainedModel, + DepthProForDepthEstimation: () => DepthProForDepthEstimation, + DepthProPreTrainedModel: () => DepthProPreTrainedModel, + DetrForObjectDetection: () => DetrForObjectDetection, + DetrForSegmentation: () => DetrForSegmentation, + DetrModel: () => DetrModel, + DetrObjectDetectionOutput: () => DetrObjectDetectionOutput, + DetrPreTrainedModel: () => DetrPreTrainedModel, + DetrSegmentationOutput: () => DetrSegmentationOutput, + Dinov2ForImageClassification: () => Dinov2ForImageClassification, + Dinov2Model: () => Dinov2Model, + Dinov2PreTrainedModel: () => Dinov2PreTrainedModel, + Dinov2WithRegistersForImageClassification: () => Dinov2WithRegistersForImageClassification, + Dinov2WithRegistersModel: () => Dinov2WithRegistersModel, + Dinov2WithRegistersPreTrainedModel: () => Dinov2WithRegistersPreTrainedModel, + DistilBertForMaskedLM: () => DistilBertForMaskedLM, + DistilBertForQuestionAnswering: () => DistilBertForQuestionAnswering, + DistilBertForSequenceClassification: () => DistilBertForSequenceClassification, + DistilBertForTokenClassification: () => DistilBertForTokenClassification, + DistilBertModel: () => DistilBertModel, + DistilBertPreTrainedModel: () => DistilBertPreTrainedModel, + DonutSwinModel: () => DonutSwinModel, + DonutSwinPreTrainedModel: () => DonutSwinPreTrainedModel, + EdgeTamModel: () => EdgeTamModel, + EfficientNetForImageClassification: () => EfficientNetForImageClassification, + EfficientNetModel: () => EfficientNetModel, + EfficientNetPreTrainedModel: () => EfficientNetPreTrainedModel, + ElectraForMaskedLM: () => ElectraForMaskedLM, + ElectraForQuestionAnswering: () => ElectraForQuestionAnswering, + ElectraForSequenceClassification: () => ElectraForSequenceClassification, + ElectraForTokenClassification: () => ElectraForTokenClassification, + ElectraModel: () => ElectraModel, + ElectraPreTrainedModel: () => ElectraPreTrainedModel, + EmbeddingGemma2Model: () => EmbeddingGemma2Model, + EmbeddingGemma2PreTrainedModel: () => EmbeddingGemma2PreTrainedModel, + Ernie4_5ForCausalLM: () => Ernie4_5ForCausalLM, + Ernie4_5Model: () => Ernie4_5Model, + Ernie4_5PretrainedModel: () => Ernie4_5PretrainedModel, + EsmForMaskedLM: () => EsmForMaskedLM, + EsmForSequenceClassification: () => EsmForSequenceClassification, + EsmForTokenClassification: () => EsmForTokenClassification, + EsmModel: () => EsmModel, + EsmPreTrainedModel: () => EsmPreTrainedModel, + EuroBertForMaskedLM: () => EuroBertForMaskedLM, + EuroBertForSequenceClassification: () => EuroBertForSequenceClassification, + EuroBertForTokenClassification: () => EuroBertForTokenClassification, + EuroBertModel: () => EuroBertModel, + EuroBertPreTrainedModel: () => EuroBertPreTrainedModel, + ExaoneForCausalLM: () => ExaoneForCausalLM, + ExaoneModel: () => ExaoneModel, + ExaonePreTrainedModel: () => ExaonePreTrainedModel, + FalconForCausalLM: () => FalconForCausalLM, + FalconH1ForCausalLM: () => FalconH1ForCausalLM, + FalconH1Model: () => FalconH1Model, + FalconH1PreTrainedModel: () => FalconH1PreTrainedModel, + FalconModel: () => FalconModel, + FalconPreTrainedModel: () => FalconPreTrainedModel, + FastViTForImageClassification: () => FastViTForImageClassification, + FastViTModel: () => FastViTModel, + FastViTPreTrainedModel: () => FastViTPreTrainedModel, + Florence2ForConditionalGeneration: () => Florence2ForConditionalGeneration, + Florence2PreTrainedModel: () => Florence2PreTrainedModel, + GLPNForDepthEstimation: () => GLPNForDepthEstimation, + GLPNModel: () => GLPNModel, + GLPNPreTrainedModel: () => GLPNPreTrainedModel, + GPT2LMHeadModel: () => GPT2LMHeadModel, + GPT2Model: () => GPT2Model, + GPT2PreTrainedModel: () => GPT2PreTrainedModel, + GPTBigCodeForCausalLM: () => GPTBigCodeForCausalLM, + GPTBigCodeModel: () => GPTBigCodeModel, + GPTBigCodePreTrainedModel: () => GPTBigCodePreTrainedModel, + GPTJForCausalLM: () => GPTJForCausalLM, + GPTJModel: () => GPTJModel, + GPTJPreTrainedModel: () => GPTJPreTrainedModel, + GPTNeoForCausalLM: () => GPTNeoForCausalLM, + GPTNeoModel: () => GPTNeoModel, + GPTNeoPreTrainedModel: () => GPTNeoPreTrainedModel, + GPTNeoXForCausalLM: () => GPTNeoXForCausalLM, + GPTNeoXModel: () => GPTNeoXModel, + GPTNeoXPreTrainedModel: () => GPTNeoXPreTrainedModel, + Gemma2ForCausalLM: () => Gemma2ForCausalLM, + Gemma2Model: () => Gemma2Model, + Gemma2PreTrainedModel: () => Gemma2PreTrainedModel, + Gemma3ForCausalLM: () => Gemma3ForCausalLM, + Gemma3ForConditionalGeneration: () => Gemma3ForConditionalGeneration, + Gemma3Model: () => Gemma3Model, + Gemma3PreTrainedModel: () => Gemma3PreTrainedModel, + Gemma3nForCausalLM: () => Gemma3nForCausalLM, + Gemma3nForConditionalGeneration: () => Gemma3nForConditionalGeneration, + Gemma3nPreTrainedModel: () => Gemma3nPreTrainedModel, + Gemma4ForCausalLM: () => Gemma4ForCausalLM, + Gemma4ForConditionalGeneration: () => Gemma4ForConditionalGeneration, + GemmaForCausalLM: () => GemmaForCausalLM, + GemmaModel: () => GemmaModel, + GemmaPreTrainedModel: () => GemmaPreTrainedModel, + GlmForCausalLM: () => GlmForCausalLM, + GlmModel: () => GlmModel, + GlmMoeDsaForCausalLM: () => GlmMoeDsaForCausalLM, + GlmMoeDsaModel: () => GlmMoeDsaModel, + GlmMoeDsaPreTrainedModel: () => GlmMoeDsaPreTrainedModel, + GlmOcrForConditionalGeneration: () => GlmOcrForConditionalGeneration, + GlmPreTrainedModel: () => GlmPreTrainedModel, + GptOssForCausalLM: () => GptOssForCausalLM, + GptOssModel: () => GptOssModel, + GptOssPreTrainedModel: () => GptOssPreTrainedModel, + GraniteForCausalLM: () => GraniteForCausalLM, + GraniteModel: () => GraniteModel, + GraniteMoeHybridForCausalLM: () => GraniteMoeHybridForCausalLM, + GraniteMoeHybridModel: () => GraniteMoeHybridModel, + GraniteMoeHybridPreTrainedModel: () => GraniteMoeHybridPreTrainedModel, + GranitePreTrainedModel: () => GranitePreTrainedModel, + GraniteSpeechForConditionalGeneration: () => GraniteSpeechForConditionalGeneration, + GroundingDinoForObjectDetection: () => GroundingDinoForObjectDetection, + GroundingDinoPreTrainedModel: () => GroundingDinoPreTrainedModel, + GroupViTModel: () => GroupViTModel, + GroupViTPreTrainedModel: () => GroupViTPreTrainedModel, + HeliumForCausalLM: () => HeliumForCausalLM, + HeliumModel: () => HeliumModel, + HeliumPreTrainedModel: () => HeliumPreTrainedModel, + HieraForImageClassification: () => HieraForImageClassification, + HieraModel: () => HieraModel, + HieraPreTrainedModel: () => HieraPreTrainedModel, + HrmTextForCausalLM: () => HrmTextForCausalLM, + HrmTextModel: () => HrmTextModel, + HrmTextPreTrainedModel: () => HrmTextPreTrainedModel, + HubertForCTC: () => HubertForCTC, + HubertForSequenceClassification: () => HubertForSequenceClassification, + HubertModel: () => HubertModel, + HubertPreTrainedModel: () => HubertPreTrainedModel, + HunYuanDenseV1ForCausalLM: () => HunYuanDenseV1ForCausalLM, + HunYuanDenseV1Model: () => HunYuanDenseV1Model, + HunYuanDenseV1PreTrainedModel: () => HunYuanDenseV1PreTrainedModel, + IJepaForImageClassification: () => IJepaForImageClassification, + IJepaModel: () => IJepaModel, + IJepaPreTrainedModel: () => IJepaPreTrainedModel, + Idefics3ForConditionalGeneration: () => Idefics3ForConditionalGeneration, + ImageMattingOutput: () => ImageMattingOutput, + JAISLMHeadModel: () => JAISLMHeadModel, + JAISModel: () => JAISModel, + JAISPreTrainedModel: () => JAISPreTrainedModel, + JinaCLIPModel: () => JinaCLIPModel, + JinaCLIPPreTrainedModel: () => JinaCLIPPreTrainedModel, + JinaCLIPTextModel: () => JinaCLIPTextModel, + JinaCLIPVisionModel: () => JinaCLIPVisionModel, + Lfm2ForCausalLM: () => Lfm2ForCausalLM, + Lfm2Model: () => Lfm2Model, + Lfm2MoeForCausalLM: () => Lfm2MoeForCausalLM, + Lfm2MoeModel: () => Lfm2MoeModel, + Lfm2MoePreTrainedModel: () => Lfm2MoePreTrainedModel, + Lfm2PreTrainedModel: () => Lfm2PreTrainedModel, + Lfm2VlForConditionalGeneration: () => Lfm2VlForConditionalGeneration, + Lfm3ForCausalLM: () => Lfm3ForCausalLM, + Lfm3Model: () => Lfm3Model, + Lfm3PreTrainedModel: () => Lfm3PreTrainedModel, + Lfm3VlForConditionalGeneration: () => Lfm3VlForConditionalGeneration, + LightOnOcrForConditionalGeneration: () => LightOnOcrForConditionalGeneration, + LiteWhisperForConditionalGeneration: () => LiteWhisperForConditionalGeneration, + Llama4ForCausalLM: () => Llama4ForCausalLM, + Llama4PreTrainedModel: () => Llama4PreTrainedModel, + LlamaForCausalLM: () => LlamaForCausalLM, + LlamaModel: () => LlamaModel, + LlamaPreTrainedModel: () => LlamaPreTrainedModel, + LlavaForConditionalGeneration: () => LlavaForConditionalGeneration, + LlavaOnevisionForConditionalGeneration: () => LlavaForConditionalGeneration, + LlavaPreTrainedModel: () => LlavaPreTrainedModel, + LlavaQwen2ForCausalLM: () => LlavaQwen2ForCausalLM, + LongT5ForConditionalGeneration: () => LongT5ForConditionalGeneration, + LongT5Model: () => LongT5Model, + LongT5PreTrainedModel: () => LongT5PreTrainedModel, + M2M100ForConditionalGeneration: () => M2M100ForConditionalGeneration, + M2M100Model: () => M2M100Model, + M2M100PreTrainedModel: () => M2M100PreTrainedModel, + MBartForCausalLM: () => MBartForCausalLM, + MBartForConditionalGeneration: () => MBartForConditionalGeneration, + MBartForSequenceClassification: () => MBartForSequenceClassification, + MBartModel: () => MBartModel, + MBartPreTrainedModel: () => MBartPreTrainedModel, + MPNetForMaskedLM: () => MPNetForMaskedLM, + MPNetForQuestionAnswering: () => MPNetForQuestionAnswering, + MPNetForSequenceClassification: () => MPNetForSequenceClassification, + MPNetForTokenClassification: () => MPNetForTokenClassification, + MPNetModel: () => MPNetModel, + MPNetPreTrainedModel: () => MPNetPreTrainedModel, + MT5ForConditionalGeneration: () => MT5ForConditionalGeneration, + MT5Model: () => MT5Model, + MT5PreTrainedModel: () => MT5PreTrainedModel, + MarianMTModel: () => MarianMTModel, + MarianModel: () => MarianModel, + MarianPreTrainedModel: () => MarianPreTrainedModel, + MaskFormerForInstanceSegmentation: () => MaskFormerForInstanceSegmentation, + MaskFormerModel: () => MaskFormerModel, + MaskFormerPreTrainedModel: () => MaskFormerPreTrainedModel, + MaskedLMOutput: () => MaskedLMOutput, + Metric3DForDepthEstimation: () => Metric3DForDepthEstimation, + Metric3DPreTrainedModel: () => Metric3DPreTrainedModel, + Metric3Dv2ForDepthEstimation: () => Metric3Dv2ForDepthEstimation, + Metric3Dv2PreTrainedModel: () => Metric3Dv2PreTrainedModel, + MgpstrForSceneTextRecognition: () => MgpstrForSceneTextRecognition, + MgpstrModelOutput: () => MgpstrModelOutput, + MgpstrPreTrainedModel: () => MgpstrPreTrainedModel, + MimiDecoderModel: () => MimiDecoderModel, + MimiDecoderOutput: () => MimiDecoderOutput, + MimiEncoderModel: () => MimiEncoderModel, + MimiEncoderOutput: () => MimiEncoderOutput, + MimiModel: () => MimiModel, + MimiPreTrainedModel: () => MimiPreTrainedModel, + Ministral3ForCausalLM: () => Ministral3ForCausalLM, + Ministral3Model: () => Ministral3Model, + Ministral3PreTrainedModel: () => Ministral3PreTrainedModel, + MinistralForCausalLM: () => MinistralForCausalLM, + MinistralModel: () => MinistralModel, + MinistralPreTrainedModel: () => MinistralPreTrainedModel, + Mistral3ForConditionalGeneration: () => Mistral3ForConditionalGeneration, + Mistral4ForCausalLM: () => Mistral4ForCausalLM, + Mistral4Model: () => Mistral4Model, + Mistral4PreTrainedModel: () => Mistral4PreTrainedModel, + MistralForCausalLM: () => MistralForCausalLM, + MistralModel: () => MistralModel, + MistralPreTrainedModel: () => MistralPreTrainedModel, + MobileBertForMaskedLM: () => MobileBertForMaskedLM, + MobileBertForQuestionAnswering: () => MobileBertForQuestionAnswering, + MobileBertForSequenceClassification: () => MobileBertForSequenceClassification, + MobileBertModel: () => MobileBertModel, + MobileBertPreTrainedModel: () => MobileBertPreTrainedModel, + MobileLLMForCausalLM: () => MobileLLMForCausalLM, + MobileLLMModel: () => MobileLLMModel, + MobileLLMPreTrainedModel: () => MobileLLMPreTrainedModel, + MobileNetV1ForImageClassification: () => MobileNetV1ForImageClassification, + MobileNetV1ForSemanticSegmentation: () => MobileNetV1ForSemanticSegmentation, + MobileNetV1Model: () => MobileNetV1Model, + MobileNetV1PreTrainedModel: () => MobileNetV1PreTrainedModel, + MobileNetV2ForImageClassification: () => MobileNetV2ForImageClassification, + MobileNetV2ForSemanticSegmentation: () => MobileNetV2ForSemanticSegmentation, + MobileNetV2Model: () => MobileNetV2Model, + MobileNetV2PreTrainedModel: () => MobileNetV2PreTrainedModel, + MobileNetV3ForImageClassification: () => MobileNetV3ForImageClassification, + MobileNetV3ForSemanticSegmentation: () => MobileNetV3ForSemanticSegmentation, + MobileNetV3Model: () => MobileNetV3Model, + MobileNetV3PreTrainedModel: () => MobileNetV3PreTrainedModel, + MobileNetV4ForImageClassification: () => MobileNetV4ForImageClassification, + MobileNetV4ForSemanticSegmentation: () => MobileNetV4ForSemanticSegmentation, + MobileNetV4Model: () => MobileNetV4Model, + MobileNetV4PreTrainedModel: () => MobileNetV4PreTrainedModel, + MobileViTForImageClassification: () => MobileViTForImageClassification, + MobileViTModel: () => MobileViTModel, + MobileViTPreTrainedModel: () => MobileViTPreTrainedModel, + MobileViTV2ForImageClassification: () => MobileViTV2ForImageClassification, + MobileViTV2Model: () => MobileViTV2Model, + MobileViTV2PreTrainedModel: () => MobileViTV2PreTrainedModel, + ModelOutput: () => ModelOutput, + ModernBertDecoderForCausalLM: () => ModernBertDecoderForCausalLM, + ModernBertDecoderModel: () => ModernBertDecoderModel, + ModernBertDecoderPreTrainedModel: () => ModernBertDecoderPreTrainedModel, + ModernBertForMaskedLM: () => ModernBertForMaskedLM, + ModernBertForSequenceClassification: () => ModernBertForSequenceClassification, + ModernBertForTokenClassification: () => ModernBertForTokenClassification, + ModernBertModel: () => ModernBertModel, + ModernBertPreTrainedModel: () => ModernBertPreTrainedModel, + Moondream1ForConditionalGeneration: () => Moondream1ForConditionalGeneration, + MoonshineForConditionalGeneration: () => MoonshineForConditionalGeneration, + MoonshineModel: () => MoonshineModel, + MoonshinePreTrainedModel: () => MoonshinePreTrainedModel, + MptForCausalLM: () => MptForCausalLM, + MptModel: () => MptModel, + MptPreTrainedModel: () => MptPreTrainedModel, + MultiModalityCausalLM: () => MultiModalityCausalLM, + MultiModalityPreTrainedModel: () => MultiModalityPreTrainedModel, + MusicgenForCausalLM: () => MusicgenForCausalLM, + MusicgenForConditionalGeneration: () => MusicgenForConditionalGeneration, + MusicgenModel: () => MusicgenModel, + MusicgenPreTrainedModel: () => MusicgenPreTrainedModel, + NanoChatForCausalLM: () => NanoChatForCausalLM, + NanoChatModel: () => NanoChatModel, + NanoChatPreTrainedModel: () => NanoChatPreTrainedModel, + NemotronHForCausalLM: () => NemotronHForCausalLM, + NemotronHModel: () => NemotronHModel, + NemotronHPreTrainedModel: () => NemotronHPreTrainedModel, + NeoBertForMaskedLM: () => NeoBertForMaskedLM, + NeoBertForQuestionAnswering: () => NeoBertForQuestionAnswering, + NeoBertForSequenceClassification: () => NeoBertForSequenceClassification, + NeoBertForTokenClassification: () => NeoBertForTokenClassification, + NeoBertModel: () => NeoBertModel, + NeoBertPreTrainedModel: () => NeoBertPreTrainedModel, + NomicBertModel: () => NomicBertModel, + NomicBertPreTrainedModel: () => NomicBertPreTrainedModel, + OPTForCausalLM: () => OPTForCausalLM, + OPTModel: () => OPTModel, + OPTPreTrainedModel: () => OPTPreTrainedModel, + Olmo2ForCausalLM: () => Olmo2ForCausalLM, + Olmo2Model: () => Olmo2Model, + Olmo2PreTrainedModel: () => Olmo2PreTrainedModel, + Olmo3ForCausalLM: () => Olmo3ForCausalLM, + Olmo3Model: () => Olmo3Model, + Olmo3PreTrainedModel: () => Olmo3PreTrainedModel, + OlmoForCausalLM: () => OlmoForCausalLM, + OlmoHybridForCausalLM: () => OlmoHybridForCausalLM, + OlmoHybridModel: () => OlmoHybridModel, + OlmoHybridPreTrainedModel: () => OlmoHybridPreTrainedModel, + OlmoModel: () => OlmoModel, + OlmoPreTrainedModel: () => OlmoPreTrainedModel, + OpenAIPrivacyFilterForTokenClassification: () => OpenAIPrivacyFilterForTokenClassification, + OpenAIPrivacyFilterModel: () => OpenAIPrivacyFilterModel, + OpenAIPrivacyFilterPreTrainedModel: () => OpenAIPrivacyFilterPreTrainedModel, + OpenELMForCausalLM: () => OpenELMForCausalLM, + OpenELMModel: () => OpenELMModel, + OpenELMPreTrainedModel: () => OpenELMPreTrainedModel, + OwlViTForObjectDetection: () => OwlViTForObjectDetection, + OwlViTModel: () => OwlViTModel, + OwlViTPreTrainedModel: () => OwlViTPreTrainedModel, + Owlv2ForObjectDetection: () => Owlv2ForObjectDetection, + Owlv2Model: () => Owlv2Model, + Owlv2PreTrainedModel: () => Owlv2PreTrainedModel, + PaliGemmaForConditionalGeneration: () => PaliGemmaForConditionalGeneration, + ParakeetForCTC: () => ParakeetForCTC, + ParakeetPreTrainedModel: () => ParakeetPreTrainedModel, + PatchTSMixerForPrediction: () => PatchTSMixerForPrediction, + PatchTSMixerModel: () => PatchTSMixerModel, + PatchTSMixerPreTrainedModel: () => PatchTSMixerPreTrainedModel, + PatchTSTForPrediction: () => PatchTSTForPrediction, + PatchTSTModel: () => PatchTSTModel, + PatchTSTPreTrainedModel: () => PatchTSTPreTrainedModel, + Phi3ForCausalLM: () => Phi3ForCausalLM, + Phi3Model: () => Phi3Model, + Phi3PreTrainedModel: () => Phi3PreTrainedModel, + Phi3VForCausalLM: () => Phi3VForCausalLM, + Phi3VPreTrainedModel: () => Phi3VPreTrainedModel, + PhiForCausalLM: () => PhiForCausalLM, + PhiModel: () => PhiModel, + PhiPreTrainedModel: () => PhiPreTrainedModel, + PreTrainedModel: () => PreTrainedModel, + PvtForImageClassification: () => PvtForImageClassification, + PvtModel: () => PvtModel, + PvtPreTrainedModel: () => PvtPreTrainedModel, + PyAnnoteForAudioFrameClassification: () => PyAnnoteForAudioFrameClassification, + PyAnnoteModel: () => PyAnnoteModel, + PyAnnotePreTrainedModel: () => PyAnnotePreTrainedModel, + QuestionAnsweringModelOutput: () => QuestionAnsweringModelOutput, + Qwen2ForCausalLM: () => Qwen2ForCausalLM, + Qwen2Model: () => Qwen2Model, + Qwen2MoeForCausalLM: () => Qwen2MoeForCausalLM, + Qwen2MoeModel: () => Qwen2MoeModel, + Qwen2MoePreTrainedModel: () => Qwen2MoePreTrainedModel, + Qwen2PreTrainedModel: () => Qwen2PreTrainedModel, + Qwen2VLForCausalLM: () => Qwen2VLForCausalLM, + Qwen2VLForConditionalGeneration: () => Qwen2VLForConditionalGeneration, + Qwen2VLPreTrainedModel: () => Qwen2VLPreTrainedModel, + Qwen2_5_VLForCausalLM: () => Qwen2_5_VLForCausalLM, + Qwen2_5_VLForConditionalGeneration: () => Qwen2_5_VLForConditionalGeneration, + Qwen3ForCausalLM: () => Qwen3ForCausalLM, + Qwen3Model: () => Qwen3Model, + Qwen3MoeForCausalLM: () => Qwen3MoeForCausalLM, + Qwen3MoeModel: () => Qwen3MoeModel, + Qwen3MoePreTrainedModel: () => Qwen3MoePreTrainedModel, + Qwen3NextForCausalLM: () => Qwen3NextForCausalLM, + Qwen3NextModel: () => Qwen3NextModel, + Qwen3NextPreTrainedModel: () => Qwen3NextPreTrainedModel, + Qwen3PreTrainedModel: () => Qwen3PreTrainedModel, + Qwen3VLForCausalLM: () => Qwen3VLForCausalLM, + Qwen3VLForConditionalGeneration: () => Qwen3VLForConditionalGeneration, + Qwen3VLMoeForCausalLM: () => Qwen3VLMoeForCausalLM, + Qwen3VLMoeForConditionalGeneration: () => Qwen3VLMoeForConditionalGeneration, + Qwen3_5ForCausalLM: () => Qwen3_5ForCausalLM, + Qwen3_5ForConditionalGeneration: () => Qwen3_5ForConditionalGeneration, + Qwen3_5MoeForCausalLM: () => Qwen3_5MoeForCausalLM, + Qwen3_5MoeForConditionalGeneration: () => Qwen3_5MoeForConditionalGeneration, + RFDetrForObjectDetection: () => RFDetrForObjectDetection, + RFDetrModel: () => RFDetrModel, + RFDetrObjectDetectionOutput: () => RFDetrObjectDetectionOutput, + RFDetrPreTrainedModel: () => RFDetrPreTrainedModel, + RTDetrForObjectDetection: () => RTDetrForObjectDetection, + RTDetrModel: () => RTDetrModel, + RTDetrObjectDetectionOutput: () => RTDetrObjectDetectionOutput, + RTDetrPreTrainedModel: () => RTDetrPreTrainedModel, + RTDetrV2ForObjectDetection: () => RTDetrV2ForObjectDetection, + RTDetrV2Model: () => RTDetrV2Model, + RTDetrV2ObjectDetectionOutput: () => RTDetrV2ObjectDetectionOutput, + RTDetrV2PreTrainedModel: () => RTDetrV2PreTrainedModel, + ResNetForImageClassification: () => ResNetForImageClassification, + ResNetModel: () => ResNetModel, + ResNetPreTrainedModel: () => ResNetPreTrainedModel, + RoFormerForMaskedLM: () => RoFormerForMaskedLM, + RoFormerForQuestionAnswering: () => RoFormerForQuestionAnswering, + RoFormerForSequenceClassification: () => RoFormerForSequenceClassification, + RoFormerForTokenClassification: () => RoFormerForTokenClassification, + RoFormerModel: () => RoFormerModel, + RoFormerPreTrainedModel: () => RoFormerPreTrainedModel, + RobertaForMaskedLM: () => RobertaForMaskedLM, + RobertaForQuestionAnswering: () => RobertaForQuestionAnswering, + RobertaForSequenceClassification: () => RobertaForSequenceClassification, + RobertaForTokenClassification: () => RobertaForTokenClassification, + RobertaModel: () => RobertaModel, + RobertaPreTrainedModel: () => RobertaPreTrainedModel, + Sam2ImageSegmentationOutput: () => Sam2ImageSegmentationOutput, + Sam2Model: () => Sam2Model, + Sam2PreTrainedModel: () => Sam2PreTrainedModel, + Sam3TrackerModel: () => Sam3TrackerModel, + SamImageSegmentationOutput: () => SamImageSegmentationOutput, + SamModel: () => SamModel, + SamPreTrainedModel: () => SamPreTrainedModel, + SapiensForDepthEstimation: () => SapiensForDepthEstimation, + SapiensForNormalEstimation: () => SapiensForNormalEstimation, + SapiensForSemanticSegmentation: () => SapiensForSemanticSegmentation, + SapiensPreTrainedModel: () => SapiensPreTrainedModel, + SegformerForImageClassification: () => SegformerForImageClassification, + SegformerForSemanticSegmentation: () => SegformerForSemanticSegmentation, + SegformerModel: () => SegformerModel, + SegformerPreTrainedModel: () => SegformerPreTrainedModel, + Seq2SeqLMOutput: () => Seq2SeqLMOutput, + SequenceClassifierOutput: () => SequenceClassifierOutput, + SiglipModel: () => SiglipModel, + SiglipPreTrainedModel: () => SiglipPreTrainedModel, + SiglipTextModel: () => SiglipTextModel, + SiglipVisionModel: () => SiglipVisionModel, + SmolLM3ForCausalLM: () => SmolLM3ForCausalLM, + SmolLM3Model: () => SmolLM3Model, + SmolLM3PreTrainedModel: () => SmolLM3PreTrainedModel, + SmolVLMForConditionalGeneration: () => SmolVLMForConditionalGeneration, + SnacDecoderModel: () => SnacDecoderModel, + SnacEncoderModel: () => SnacEncoderModel, + SnacModel: () => SnacModel, + SnacPreTrainedModel: () => SnacPreTrainedModel, + SolarOpenForCausalLM: () => SolarOpenForCausalLM, + SolarOpenModel: () => SolarOpenModel, + SolarOpenPreTrainedModel: () => SolarOpenPreTrainedModel, + SpeechT5ForSpeechToText: () => SpeechT5ForSpeechToText, + SpeechT5ForTextToSpeech: () => SpeechT5ForTextToSpeech, + SpeechT5HifiGan: () => SpeechT5HifiGan, + SpeechT5Model: () => SpeechT5Model, + SpeechT5PreTrainedModel: () => SpeechT5PreTrainedModel, + SqueezeBertForMaskedLM: () => SqueezeBertForMaskedLM, + SqueezeBertForQuestionAnswering: () => SqueezeBertForQuestionAnswering, + SqueezeBertForSequenceClassification: () => SqueezeBertForSequenceClassification, + SqueezeBertModel: () => SqueezeBertModel, + SqueezeBertPreTrainedModel: () => SqueezeBertPreTrainedModel, + StableLmForCausalLM: () => StableLmForCausalLM, + StableLmModel: () => StableLmModel, + StableLmPreTrainedModel: () => StableLmPreTrainedModel, + Starcoder2ForCausalLM: () => Starcoder2ForCausalLM, + Starcoder2Model: () => Starcoder2Model, + Starcoder2PreTrainedModel: () => Starcoder2PreTrainedModel, + StyleTextToSpeech2Model: () => StyleTextToSpeech2Model, + StyleTextToSpeech2PreTrainedModel: () => StyleTextToSpeech2PreTrainedModel, + SupertonicForConditionalGeneration: () => SupertonicForConditionalGeneration, + SupertonicPreTrainedModel: () => SupertonicPreTrainedModel, + Swin2SRForImageSuperResolution: () => Swin2SRForImageSuperResolution, + Swin2SRModel: () => Swin2SRModel, + Swin2SRPreTrainedModel: () => Swin2SRPreTrainedModel, + SwinForImageClassification: () => SwinForImageClassification, + SwinForSemanticSegmentation: () => SwinForSemanticSegmentation, + SwinModel: () => SwinModel, + SwinPreTrainedModel: () => SwinPreTrainedModel, + T5ForConditionalGeneration: () => T5ForConditionalGeneration, + T5Model: () => T5Model, + T5PreTrainedModel: () => T5PreTrainedModel, + TableTransformerForObjectDetection: () => TableTransformerForObjectDetection, + TableTransformerModel: () => TableTransformerModel, + TableTransformerObjectDetectionOutput: () => TableTransformerObjectDetectionOutput, + TableTransformerPreTrainedModel: () => TableTransformerPreTrainedModel, + TokenClassifierOutput: () => TokenClassifierOutput, + TrOCRForCausalLM: () => TrOCRForCausalLM, + TrOCRPreTrainedModel: () => TrOCRPreTrainedModel, + UltravoxModel: () => UltravoxModel, + UltravoxPreTrainedModel: () => UltravoxPreTrainedModel, + UniSpeechForCTC: () => UniSpeechForCTC, + UniSpeechForSequenceClassification: () => UniSpeechForSequenceClassification, + UniSpeechModel: () => UniSpeechModel, + UniSpeechPreTrainedModel: () => UniSpeechPreTrainedModel, + UniSpeechSatForAudioFrameClassification: () => UniSpeechSatForAudioFrameClassification, + UniSpeechSatForCTC: () => UniSpeechSatForCTC, + UniSpeechSatForSequenceClassification: () => UniSpeechSatForSequenceClassification, + UniSpeechSatModel: () => UniSpeechSatModel, + UniSpeechSatPreTrainedModel: () => UniSpeechSatPreTrainedModel, + VaultGemmaForCausalLM: () => VaultGemmaForCausalLM, + VaultGemmaModel: () => VaultGemmaModel, + VaultGemmaPreTrainedModel: () => VaultGemmaPreTrainedModel, + ViTForImageClassification: () => ViTForImageClassification, + ViTMAEModel: () => ViTMAEModel, + ViTMAEPreTrainedModel: () => ViTMAEPreTrainedModel, + ViTMSNForImageClassification: () => ViTMSNForImageClassification, + ViTMSNModel: () => ViTMSNModel, + ViTMSNPreTrainedModel: () => ViTMSNPreTrainedModel, + ViTModel: () => ViTModel, + ViTPreTrainedModel: () => ViTPreTrainedModel, + VisionEncoderDecoderModel: () => VisionEncoderDecoderModel, + VitMatteForImageMatting: () => VitMatteForImageMatting, + VitMattePreTrainedModel: () => VitMattePreTrainedModel, + VitPoseForPoseEstimation: () => VitPoseForPoseEstimation, + VitPosePreTrainedModel: () => VitPosePreTrainedModel, + VitsModel: () => VitsModel, + VitsModelOutput: () => VitsModelOutput, + VitsPreTrainedModel: () => VitsPreTrainedModel, + VoxtralForConditionalGeneration: () => VoxtralForConditionalGeneration, + VoxtralRealtimeForConditionalGeneration: () => VoxtralRealtimeForConditionalGeneration, + VoxtralRealtimePreTrainedModel: () => VoxtralRealtimePreTrainedModel, + Wav2Vec2BertForCTC: () => Wav2Vec2BertForCTC, + Wav2Vec2BertForSequenceClassification: () => Wav2Vec2BertForSequenceClassification, + Wav2Vec2BertModel: () => Wav2Vec2BertModel, + Wav2Vec2BertPreTrainedModel: () => Wav2Vec2BertPreTrainedModel, + Wav2Vec2ForAudioFrameClassification: () => Wav2Vec2ForAudioFrameClassification, + Wav2Vec2ForCTC: () => Wav2Vec2ForCTC, + Wav2Vec2ForSequenceClassification: () => Wav2Vec2ForSequenceClassification, + Wav2Vec2Model: () => Wav2Vec2Model, + Wav2Vec2PreTrainedModel: () => Wav2Vec2PreTrainedModel, + WavLMForAudioFrameClassification: () => WavLMForAudioFrameClassification, + WavLMForCTC: () => WavLMForCTC, + WavLMForSequenceClassification: () => WavLMForSequenceClassification, + WavLMForXVector: () => WavLMForXVector, + WavLMModel: () => WavLMModel, + WavLMPreTrainedModel: () => WavLMPreTrainedModel, + WeSpeakerResNetModel: () => WeSpeakerResNetModel, + WeSpeakerResNetPreTrainedModel: () => WeSpeakerResNetPreTrainedModel, + WhisperForConditionalGeneration: () => WhisperForConditionalGeneration, + WhisperModel: () => WhisperModel, + WhisperPreTrainedModel: () => WhisperPreTrainedModel, + XLMForQuestionAnswering: () => XLMForQuestionAnswering, + XLMForSequenceClassification: () => XLMForSequenceClassification, + XLMForTokenClassification: () => XLMForTokenClassification, + XLMModel: () => XLMModel, + XLMPreTrainedModel: () => XLMPreTrainedModel, + XLMRobertaForMaskedLM: () => XLMRobertaForMaskedLM, + XLMRobertaForQuestionAnswering: () => XLMRobertaForQuestionAnswering, + XLMRobertaForSequenceClassification: () => XLMRobertaForSequenceClassification, + XLMRobertaForTokenClassification: () => XLMRobertaForTokenClassification, + XLMRobertaModel: () => XLMRobertaModel, + XLMRobertaPreTrainedModel: () => XLMRobertaPreTrainedModel, + XLMWithLMHeadModel: () => XLMWithLMHeadModel, + XVectorOutput: () => XVectorOutput, + YolosForObjectDetection: () => YolosForObjectDetection, + YolosModel: () => YolosModel, + YolosObjectDetectionOutput: () => YolosObjectDetectionOutput, + YolosPreTrainedModel: () => YolosPreTrainedModel, + YoutuForCausalLM: () => YoutuForCausalLM, + YoutuModel: () => YoutuModel, + YoutuPreTrainedModel: () => YoutuPreTrainedModel, + ZayaForCausalLM: () => ZayaForCausalLM, + ZayaModel: () => ZayaModel, + ZayaPreTrainedModel: () => ZayaPreTrainedModel +}); - /** - * Checks whether the given request is in the cache. - * @param {string} request - * @returns {Promise} - */ - async match(request) { +// src/models/albert/modeling_albert.js +var AlbertPreTrainedModel = class extends PreTrainedModel { +}; +var AlbertModel = class extends AlbertPreTrainedModel { +}; +var AlbertForSequenceClassification = class extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var AlbertForQuestionAnswering = class extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; +var AlbertForMaskedLM = class extends AlbertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; - let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.path, request); - let file = new FileResponse(filePath); +// src/models/apertus/modeling_apertus.js +var ApertusPreTrainedModel = class extends PreTrainedModel { +}; +var ApertusModel = class extends ApertusPreTrainedModel { +}; +var ApertusForCausalLM = class extends ApertusPreTrainedModel { +}; - if (file.exists) { - return file; - } else { - return undefined; - } - } +// src/models/afmoe/modeling_afmoe.js +var AfmoePreTrainedModel = class extends PreTrainedModel { +}; +var AfmoeModel = class extends AfmoePreTrainedModel { +}; +var AfmoeForCausalLM = class extends AfmoePreTrainedModel { +}; - /** - * Adds the given response to the cache. - * @param {string} request - * @param {Response} response - * @param {(data: {progress: number, loaded: number, total: number}) => void} [progress_callback] Optional. - * The function to call with progress updates - * @returns {Promise} - */ - async put(request, response, progress_callback = undefined) { - let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__.join(this.path, request); +// src/models/arcee/modeling_arcee.js +var ArceePreTrainedModel = class extends PreTrainedModel { +}; +var ArceeModel = class extends ArceePreTrainedModel { +}; +var ArceeForCausalLM = class extends ArceePreTrainedModel { +}; - try { - const contentLength = response.headers.get('Content-Length'); - const total = parseInt(contentLength ?? '0'); - let loaded = 0; - - await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.mkdir(node_path__WEBPACK_IMPORTED_MODULE_1__.dirname(filePath), { recursive: true }); - const fileStream = node_fs__WEBPACK_IMPORTED_MODULE_0__.createWriteStream(filePath); - const reader = response.body.getReader(); - - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } +// src/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.js +var ASTPreTrainedModel = class extends PreTrainedModel { +}; +var ASTModel = class extends ASTPreTrainedModel { +}; +var ASTForAudioClassification = class extends ASTPreTrainedModel { +}; - await new Promise((resolve, reject) => { - fileStream.write(value, (err) => { - if (err) { - reject(err); - return; - } - resolve(); - }); - }); +// src/models/bart/modeling_bart.js +var BartPretrainedModel = class extends PreTrainedModel { +}; +var BartModel = class extends BartPretrainedModel { +}; +var BartForConditionalGeneration = class extends BartPretrainedModel { +}; +var BartForSequenceClassification = class extends BartPretrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - loaded += value.length; - const progress = total ? (loaded / total) * 100 : 0; +// src/models/beit/modeling_beit.js +var BeitPreTrainedModel = class extends PreTrainedModel { +}; +var BeitModel = class extends BeitPreTrainedModel { +}; +var BeitForImageClassification = class extends BeitPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - progress_callback?.({ progress, loaded, total }); - } +// src/models/bert/modeling_bert.js +var BertPreTrainedModel = class extends PreTrainedModel { +}; +var BertModel = class extends BertPreTrainedModel { +}; +var BertForMaskedLM = class extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var BertForSequenceClassification = class extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var BertForTokenClassification = class extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var BertForQuestionAnswering = class extends BertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - fileStream.close(); - } catch (error) { - // Clean up the file if an error occurred during download - try { - await node_fs__WEBPACK_IMPORTED_MODULE_0__.promises.unlink(filePath); - } catch { } - throw error; - } - } +// src/models/blenderbot/modeling_blenderbot.js +var BlenderbotPreTrainedModel = class extends PreTrainedModel { +}; +var BlenderbotModel = class extends BlenderbotPreTrainedModel { +}; +var BlenderbotForConditionalGeneration = class extends BlenderbotPreTrainedModel { +}; - // TODO add the rest? - // addAll(requests: RequestInfo[]): Promise; - // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; - // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise>; -} +// src/models/blenderbot_small/modeling_blenderbot_small.js +var BlenderbotSmallPreTrainedModel = class extends PreTrainedModel { +}; +var BlenderbotSmallModel = class extends BlenderbotSmallPreTrainedModel { +}; +var BlenderbotSmallForConditionalGeneration = class extends BlenderbotSmallPreTrainedModel { +}; -/** - * - * @param {FileCache|Cache} cache The cache to search - * @param {string[]} names The names of the item to search for - * @returns {Promise} The item from the cache, or undefined if not found. - */ -async function tryCache(cache, ...names) { - for (let name of names) { - try { - let result = await cache.match(name); - if (result) return result; - } catch (e) { - continue; - } - } - return undefined; -} - -/** - * Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API. - * If the filesystem is available and `env.useCache = true`, the file will be downloaded and cached. - * - * @param {string} path_or_repo_id This can be either: - * - a string, the *model id* of a model repo on huggingface.co. - * - a path to a *directory* potentially containing the file. - * @param {string} filename The name of the file to locate in `path_or_repo`. - * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. - * @param {PretrainedOptions} [options] An object containing optional parameters. - * @param {boolean} [return_path=false] Whether to return the path of the file instead of the file content. - * - * @throws Will throw an error if the file is not found and `fatal` is true. - * @returns {Promise} A Promise that resolves with the file content as a Uint8Array if `return_path` is false, or the file path as a string if `return_path` is true. - */ -async function getModelFile(path_or_repo_id, filename, fatal = true, options = {}, return_path = false) { +// src/models/bloom/modeling_bloom.js +var BloomPreTrainedModel = class extends PreTrainedModel { +}; +var BloomModel = class extends BloomPreTrainedModel { +}; +var BloomForCausalLM = class extends BloomPreTrainedModel { +}; - if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowLocalModels) { - // User has disabled local models, so we just make sure other settings are correct. +// src/models/camembert/modeling_camembert.js +var CamembertPreTrainedModel = class extends PreTrainedModel { +}; +var CamembertModel = class extends CamembertPreTrainedModel { +}; +var CamembertForMaskedLM = class extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var CamembertForSequenceClassification = class extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var CamembertForTokenClassification = class extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var CamembertForQuestionAnswering = class extends CamembertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - if (options.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`).") - } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) { - throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.") +// src/models/chatterbox/modeling_chatterbox.js +var SILENCE_TOKEN = 4299n; +var START_SPEECH_TOKEN = 6561n; +var ChatterboxPreTrainedModel = class extends PreTrainedModel { + forward_params = [ + "input_ids", + "inputs_embeds", + "attention_mask", + "position_ids", + "audio_values", + "exaggeration", + "audio_features", + "audio_tokens", + "speaker_embeddings", + "speaker_features", + "past_key_values" + ]; + main_input_name = "input_ids"; + _return_dict_in_generate_keys = ["audio_tokens", "speaker_embeddings", "speaker_features"]; +}; +var ChatterboxModel = class extends ChatterboxPreTrainedModel { + /** + * @param {Tensor} audio_values + * @returns {Promise<{audio_features: Tensor, audio_tokens: Tensor, speaker_embeddings: Tensor, speaker_features: Tensor}>} + */ + async encode_speech(audio_values) { + return sessionRun(this.sessions["speech_encoder"], { + audio_values + }); + } + async forward({ + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + audio_values = null, + exaggeration = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + num_logits_to_keep = null, + // Speaker embeddings/features (useful for re-using pre-computed speaker data) + audio_features = null, + // float32[batch_size,sequence_length,1024] + audio_tokens = null, + // int64[batch_size,audio_sequence_length] + speaker_embeddings = null, + // float32[batch_size,192] + speaker_features = null, + // float32[batch_size,feature_dim,80] + // TODO: needed? + ...kwargs + }) { + let speech_encoder_outputs; + if (!inputs_embeds) { + const expected_inputs = this.sessions["embed_tokens"].inputNames; + const embed_model_inputs = { input_ids }; + if (expected_inputs.includes("exaggeration")) { + if (!(exaggeration instanceof Tensor3)) { + const batch_size = input_ids.dims[0]; + if (exaggeration == null) { + exaggeration = full([batch_size], 0.5); + } else if (typeof exaggeration === "number") { + exaggeration = full([batch_size], exaggeration); + } else if (Array.isArray(exaggeration)) { + exaggeration = new Tensor3("float32", exaggeration, [batch_size]); + } else { + throw new Error("Unsupported type for `exaggeration` input"); + } + } + embed_model_inputs.exaggeration = exaggeration; + } + if (expected_inputs.includes("position_ids")) { + embed_model_inputs.position_ids = position_ids; + } + ({ inputs_embeds } = await sessionRun(this.sessions["embed_tokens"], embed_model_inputs)); + if (audio_features && audio_tokens && speaker_embeddings && speaker_features) { + speech_encoder_outputs = { audio_features, audio_tokens, speaker_embeddings, speaker_features }; + } + if (speech_encoder_outputs || audio_values) { + speech_encoder_outputs ??= await this.encode_speech(audio_values); + inputs_embeds = cat([speech_encoder_outputs.audio_features, inputs_embeds], 1); + attention_mask = ones([inputs_embeds.dims[0], inputs_embeds.dims[1]]); + } else { + const target_length = inputs_embeds.dims[1]; + if (!past_key_values || target_length !== 1) { + throw new Error("Incorrect state encountered during generation."); } + const past_length = past_key_values.get_seq_length(); + attention_mask = ones([inputs_embeds.dims[0], past_length + target_length]); + } + } + const outputs = await decoder_forward( + this, + { + inputs_embeds, + past_key_values, + attention_mask, + generation_config, + logits_processor, + num_logits_to_keep + }, + false + ); + return { + ...outputs, + ...speech_encoder_outputs + }; + } + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + if (!model_inputs.position_ids && this.sessions["embed_tokens"].inputNames.includes("position_ids")) { + if (model_inputs.input_ids.dims[1] === 1) { + const position_ids = Array.from( + { + length: input_ids.length + }, + (_, i) => input_ids[i].length - input_ids[i].findLastIndex((x) => x == START_SPEECH_TOKEN) - 1 + ); + model_inputs.position_ids = new Tensor3("int64", position_ids, [input_ids.length, 1]); + } else { + const batched_input_ids = model_inputs.input_ids.tolist(); + const position_ids_list = batched_input_ids.map((ids) => { + let position = 0; + return ids.map((id) => id >= START_SPEECH_TOKEN ? 0 : position++); + }); + model_inputs.position_ids = new Tensor3("int64", position_ids_list.flat(), model_inputs.input_ids.dims); + } + } + if (model_inputs.input_ids.dims[1] === 1) { + delete model_inputs.audio_values; + delete model_inputs.audio_features; + delete model_inputs.audio_tokens; + delete model_inputs.speaker_embeddings; + delete model_inputs.speaker_features; + } + return decoder_prepare_inputs_for_generation(this, input_ids, model_inputs, generation_config); + } + /** @type {PreTrainedModel['generate']} */ + async generate(params) { + const supplied_past_key_values = params.past_key_values; + const { sequences, audio_tokens, speaker_embeddings, speaker_features, past_key_values } = ( + /** @type {any} */ + await super.generate({ + ...params, + return_dict_in_generate: true + }) + ); + try { + const new_tokens = sequences.slice(null, [ + /** @type {Tensor} */ + params.input_ids.dims[1], + // Exclude start of speech token + -1 + // Exclude end of speech token + ]); + const silence_tokens = full([new_tokens.dims[0], 3], SILENCE_TOKEN); + const speech_tokens = cat([audio_tokens, new_tokens, silence_tokens], 1); + const { waveform } = await sessionRun(this.sessions["conditional_decoder"], { + speech_tokens, + speaker_features, + speaker_embeddings + }); + return waveform; + } finally { + if (past_key_values !== supplied_past_key_values) { + await past_key_values?.dispose(); + } } + } +}; - // Initiate file retrieval - (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { - status: 'initiate', - name: path_or_repo_id, - file: filename - }) +// src/models/chinese_clip/modeling_chinese_clip.js +var ChineseCLIPPreTrainedModel = class extends PreTrainedModel { +}; +var ChineseCLIPModel = class extends ChineseCLIPPreTrainedModel { +}; - // First, check if the a caching backend is available - // If no caching mechanism available, will download the file every time - let cache; - if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useCustomCache) { - // Allow the user to specify a custom cache system. - if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache) { - throw Error('`env.useCustomCache=true`, but `env.customCache` is not defined.') - } +// src/models/chmv2/modeling_chmv2.js +var CHMv2PreTrainedModel = class extends PreTrainedModel { +}; +var CHMv2ForDepthEstimation = class extends CHMv2PreTrainedModel { +}; - // Check that the required methods are defined: - if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache.match || !_env_js__WEBPACK_IMPORTED_MODULE_2__.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" - ) - } - cache = _env_js__WEBPACK_IMPORTED_MODULE_2__.env.customCache; - } +// src/models/clap/modeling_clap.js +var ClapPreTrainedModel = class extends PreTrainedModel { +}; +var ClapModel = class extends ClapPreTrainedModel { +}; +var ClapTextModelWithProjection = class extends ClapPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } +}; +var ClapAudioModelWithProjection = class extends ClapPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "audio_model" + }); + } +}; + +// src/models/clip/modeling_clip.js +var CLIPPreTrainedModel = class extends PreTrainedModel { +}; +var CLIPModel = class extends CLIPPreTrainedModel { +}; +var CLIPTextModel = class extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } +}; +var CLIPTextModelWithProjection = class extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } +}; +var CLIPVisionModel = class extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } +}; +var CLIPVisionModelWithProjection = class extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } +}; - if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useBrowserCache) { - if (typeof caches === 'undefined') { - throw Error('Browser cache is not available in this environment.') - } - try { - // In some cases, the browser cache may be visible, but not accessible due to security restrictions. - // For example, when running an application in an iframe, if a user attempts to load the page in - // incognito mode, the following error is thrown: `DOMException: Failed to execute 'open' on 'CacheStorage': - // An attempt was made to break through the security policy of the user agent.` - // So, instead of crashing, we just ignore the error and continue without using the cache. - cache = await caches.open('transformers-cache'); - } catch (e) { - console.warn('An error occurred while opening the browser cache:', e); - } - } +// src/models/clipseg/modeling_clipseg.js +var CLIPSegPreTrainedModel = class extends PreTrainedModel { +}; +var CLIPSegModel = class extends CLIPSegPreTrainedModel { +}; +var CLIPSegForImageSegmentation = class extends CLIPSegPreTrainedModel { +}; - if (!cache && _env_js__WEBPACK_IMPORTED_MODULE_2__.env.useFSCache) { - if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) { - throw Error('File System Cache is not available in this environment.'); - } +// src/models/codegen/modeling_codegen.js +var CodeGenPreTrainedModel = class extends PreTrainedModel { +}; +var CodeGenModel = class extends CodeGenPreTrainedModel { +}; +var CodeGenForCausalLM = class extends CodeGenPreTrainedModel { +}; - // If `cache_dir` is not specified, use the default cache directory - cache = new FileCache(options.cache_dir ?? _env_js__WEBPACK_IMPORTED_MODULE_2__.env.cacheDir); - } +// src/models/cohere/modeling_cohere.js +var CoherePreTrainedModel = class extends PreTrainedModel { +}; +var CohereModel = class extends CoherePreTrainedModel { +}; +var CohereForCausalLM = class extends CoherePreTrainedModel { +}; - const revision = options.revision ?? 'main'; - const requestURL = pathJoin(path_or_repo_id, filename); +// src/models/cohere2/modeling_cohere2.js +var Cohere2PreTrainedModel = class extends PreTrainedModel { +}; +var Cohere2Model = class extends Cohere2PreTrainedModel { +}; +var Cohere2ForCausalLM = class extends Cohere2PreTrainedModel { +}; - const validModelId = isValidHfModelId(path_or_repo_id); - const localPath = validModelId - ? pathJoin(_env_js__WEBPACK_IMPORTED_MODULE_2__.env.localModelPath, requestURL) - : requestURL; - const remoteURL = pathJoin( - _env_js__WEBPACK_IMPORTED_MODULE_2__.env.remoteHost, - _env_js__WEBPACK_IMPORTED_MODULE_2__.env.remotePathTemplate - .replaceAll('{model}', path_or_repo_id) - .replaceAll('{revision}', encodeURIComponent(revision)), - filename - ); +// src/models/cohere_asr/modeling_cohere_asr.js +var CohereAsrPreTrainedModel = class extends PreTrainedModel { + requires_attention_mask = false; + main_input_name = "input_features"; + forward_params = ["input_features", "decoder_input_ids", "decoder_attention_mask", "past_key_values"]; +}; +var CohereAsrModel = class extends CohereAsrPreTrainedModel { +}; +var CohereAsrForConditionalGeneration = class extends CohereAsrPreTrainedModel { +}; - /** @type {string} */ - let cacheKey; - const proposedCacheKey = cache instanceof FileCache - // Choose cache key for filesystem cache - // When using the main revision (default), we use the request URL as the cache key. - // If a specific revision is requested, we account for this in the cache key. - ? revision === 'main' ? requestURL : pathJoin(path_or_repo_id, revision, filename) - : remoteURL; - - // Whether to cache the final response in the end. - let toCacheResponse = false; - - /** @type {Response|FileResponse|undefined} */ - let response; - - if (cache) { - // A caching system is available, so we try to get the file from it. - // 1. We first try to get from cache using the local path. In some environments (like deno), - // non-URL cache keys are not allowed. In these cases, `response` will be undefined. - // 2. If no response is found, we try to get from cache using the remote URL or file system cache. - response = await tryCache(cache, localPath, proposedCacheKey); - } - - const cacheHit = response !== undefined; - if (response === undefined) { - // Caching not available, or file is not cached, so we perform the request - - if (_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowLocalModels) { - // Accessing local models is enabled, so we try to get the file locally. - // If request is a valid HTTP URL, we skip the local file check. Otherwise, we try to get the file locally. - const isURL = isValidUrl(requestURL, ['http:', 'https:']); - if (!isURL) { - try { - response = await getFile(localPath); - cacheKey = localPath; // Update the cache key to be the local path - } catch (e) { - // Something went wrong while trying to get the file locally. - // NOTE: error handling is done in the next step (since `response` will be undefined) - console.warn(`Unable to load from local path "${localPath}": "${e}"`); - } - } else if (options.local_files_only) { - throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`); - } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) { - throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${requestURL}.`); - } - } +// src/models/convbert/modeling_convbert.js +var ConvBertPreTrainedModel = class extends PreTrainedModel { +}; +var ConvBertModel = class extends ConvBertPreTrainedModel { +}; +var ConvBertForMaskedLM = class extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var ConvBertForSequenceClassification = class extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var ConvBertForTokenClassification = class extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var ConvBertForQuestionAnswering = class extends ConvBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - if (response === undefined || response.status === 404) { - // File not found locally. This means either: - // - The user has disabled local file access (`env.allowLocalModels=false`) - // - the path is a valid HTTP url (`response === undefined`) - // - the path is not a valid HTTP url and the file is not present on the file system or local server (`response.status === 404`) - - if (options.local_files_only || !_env_js__WEBPACK_IMPORTED_MODULE_2__.env.allowRemoteModels) { - // User requested local files only, but the file is not found locally. - if (fatal) { - throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`); - } else { - // File not found, but this file is optional. - // TODO in future, cache the response? - return null; - } - } - if (!validModelId) { - // Before making any requests to the remote server, we check if the model ID is valid. - // This prevents unnecessary network requests for invalid model IDs. - throw Error(`Local file missing at "${localPath}" and download aborted due to invalid model ID "${path_or_repo_id}".`); - } +// src/models/convnext/modeling_convnext.js +var ConvNextPreTrainedModel = class extends PreTrainedModel { +}; +var ConvNextModel = class extends ConvNextPreTrainedModel { +}; +var ConvNextForImageClassification = class extends ConvNextPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - // File not found locally, so we try to download it from the remote server - response = await getFile(remoteURL); +// src/models/convnextv2/modeling_convnextv2.js +var ConvNextV2PreTrainedModel = class extends PreTrainedModel { +}; +var ConvNextV2Model = class extends ConvNextV2PreTrainedModel { +}; +var ConvNextV2ForImageClassification = class extends ConvNextV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - if (response.status !== 200) { - return handleError(response.status, remoteURL, fatal); - } +// src/models/rt_detr/modeling_rt_detr.js +var RTDetrPreTrainedModel = class extends PreTrainedModel { +}; +var RTDetrModel = class extends RTDetrPreTrainedModel { +}; +var RTDetrForObjectDetection = class extends RTDetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RTDetrObjectDetectionOutput(await super._call(model_inputs)); + } +}; +var RTDetrObjectDetectionOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } +}; - // Success! We use the proposed cache key from earlier - cacheKey = proposedCacheKey; - } +// src/models/d_fine/modeling_d_fine.js +var DFinePreTrainedModel = class extends PreTrainedModel { +}; +var DFineModel = class extends DFinePreTrainedModel { +}; +var DFineForObjectDetection = class extends DFinePreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RTDetrObjectDetectionOutput(await super._call(model_inputs)); + } +}; - // Only cache the response if: - toCacheResponse = - cache // 1. A caching system is available - && typeof Response !== 'undefined' // 2. `Response` is defined (i.e., we are in a browser-like environment) - && response instanceof Response // 3. result is a `Response` object (i.e., not a `FileResponse`) - && response.status === 200 // 4. request was successful (status code 200) - } +// src/models/dac/modeling_dac.js +var DacEncoderOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_codes Discrete code embeddings, of shape `(batch_size, num_quantizers, codes_length)`. + */ + constructor({ audio_codes }) { + super(); + this.audio_codes = audio_codes; + } +}; +var DacDecoderOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_values Decoded audio values, of shape `(batch_size, num_channels, sequence_length)`. + */ + constructor({ audio_values }) { + super(); + this.audio_values = audio_values; + } +}; +var DacPreTrainedModel = class extends PreTrainedModel { + main_input_name = "input_values"; + forward_params = ["input_values"]; +}; +var DacModel = class extends DacPreTrainedModel { + /** + * Encodes the input audio waveform into discrete codes. + * @param {Object} inputs Model inputs + * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). + * @returns {Promise} The output tensor of shape `(batch_size, num_codebooks, sequence_length)`. + */ + async encode(inputs) { + return new DacEncoderOutput(await sessionRun(this.sessions["encoder_model"], inputs)); + } + /** + * Decodes the given frames into an output audio waveform. + * @param {DacEncoderOutput} inputs The encoded audio codes. + * @returns {Promise} The output tensor of shape `(batch_size, num_channels, sequence_length)`. + */ + async decode(inputs) { + return new DacDecoderOutput(await sessionRun(this.sessions["decoder_model"], inputs)); + } +}; +var DacEncoderModel = class extends DacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "encoder_model" + }); + } +}; +var DacDecoderModel = class extends DacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "decoder_model" + }); + } +}; - // Start downloading - (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { - status: 'download', - name: path_or_repo_id, - file: filename - }) +// src/models/deberta/modeling_deberta.js +var DebertaPreTrainedModel = class extends PreTrainedModel { +}; +var DebertaModel = class extends DebertaPreTrainedModel { +}; +var DebertaForMaskedLM = class extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var DebertaForSequenceClassification = class extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var DebertaForTokenClassification = class extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var DebertaForQuestionAnswering = class extends DebertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - let result; - if (!(_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_NODE_ENV && return_path)) { - /** @type {Uint8Array} */ - let buffer; - - if (!options.progress_callback) { - // If no progress callback is specified, we can use the `.arrayBuffer()` - // method to read the response. - buffer = new Uint8Array(await response.arrayBuffer()); - - } else if ( - cacheHit // The item is being read from the cache - && - typeof navigator !== 'undefined' && /firefox/i.test(navigator.userAgent) // We are in Firefox - ) { - // Due to bug in Firefox, we cannot display progress when loading from cache. - // Fortunately, since this should be instantaneous, this should not impact users too much. - buffer = new Uint8Array(await response.arrayBuffer()); - - // For completeness, we still fire the final progress callback - (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { - status: 'progress', - name: path_or_repo_id, - file: filename, - progress: 100, - loaded: buffer.length, - total: buffer.length, - }) - } else { - buffer = await readResponse(response, data => { - (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { - status: 'progress', - name: path_or_repo_id, - file: filename, - ...data, - }) - }) - } - result = buffer; - } +// src/models/deepseek_v3/modeling_deepseek_v3.js +var DeepseekV3PreTrainedModel = class extends PreTrainedModel { +}; +var DeepseekV3Model = class extends DeepseekV3PreTrainedModel { +}; +var DeepseekV3ForCausalLM = class extends DeepseekV3PreTrainedModel { +}; - if ( - // Only cache web responses - // i.e., do not cache FileResponses (prevents duplication) - toCacheResponse && cacheKey - && - // Check again whether request is in cache. If not, we add the response to the cache - (await cache.match(cacheKey) === undefined) - ) { - if (!result) { - // We haven't yet read the response body, so we need to do so now. - await cache.put(cacheKey, /** @type {Response} */(response), options.progress_callback); - } else { - // NOTE: We use `new Response(buffer, ...)` instead of `response.clone()` to handle LFS files - await cache.put(cacheKey, new Response(result, { - headers: response.headers - })) - .catch(err => { - // Do not crash if unable to add to cache (e.g., QuotaExceededError). - // Rather, log a warning and proceed with execution. - console.warn(`Unable to add response to browser cache: ${err}.`); - }); - } - } - (0,_core_js__WEBPACK_IMPORTED_MODULE_3__.dispatchCallback)(options.progress_callback, { - status: 'done', - name: path_or_repo_id, - file: filename - }); +// src/models/deepseek_v4/modeling_deepseek_v4.js +var DeepseekV4PreTrainedModel = class extends PreTrainedModel { +}; +var DeepseekV4Model = class extends DeepseekV4PreTrainedModel { +}; +var DeepseekV4ForCausalLM = class extends DeepseekV4PreTrainedModel { +}; - if (result) { - if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_NODE_ENV && return_path) { - throw new Error("Cannot return path in a browser environment.") - } - return result; - } - if (response instanceof FileResponse) { - return response.filePath; - } +// src/models/deberta_v2/modeling_deberta_v2.js +var DebertaV2PreTrainedModel = class extends PreTrainedModel { +}; +var DebertaV2Model = class extends DebertaV2PreTrainedModel { +}; +var DebertaV2ForMaskedLM = class extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var DebertaV2ForSequenceClassification = class extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var DebertaV2ForTokenClassification = class extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var DebertaV2ForQuestionAnswering = class extends DebertaV2PreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - // Otherwise, return the cached response (most likely a `FileResponse`). - // NOTE: A custom cache may return a Response, or a string (file path) - const cachedResponse = await cache?.match(cacheKey); - if (cachedResponse instanceof FileResponse) { - return cachedResponse.filePath; - } else if (cachedResponse instanceof Response) { - return new Uint8Array(await cachedResponse.arrayBuffer()); - } else if (typeof cachedResponse === 'string') { - return cachedResponse; - } +// src/models/decision_transformer/modeling_decision_transformer.js +var DecisionTransformerPreTrainedModel = class extends PreTrainedModel { +}; +var DecisionTransformerModel = class extends DecisionTransformerPreTrainedModel { +}; - throw new Error("Unable to get model file path or buffer."); -} +// src/models/deit/modeling_deit.js +var DeiTPreTrainedModel = class extends PreTrainedModel { +}; +var DeiTModel = class extends DeiTPreTrainedModel { +}; +var DeiTForImageClassification = class extends DeiTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; -/** - * Fetches a text file from a given path and file name. - * - * @param {string} modelPath The path to the directory containing the file. - * @param {string} fileName The name of the file to fetch. - * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. - * @param {PretrainedOptions} [options] An object containing optional parameters. - * @returns {Promise} The text content of the file. - * @throws Will throw an error if the file is not found and `fatal` is true. - */ -async function getModelText(modelPath, fileName, fatal = true, options = {}) { - const buffer = await getModelFile(modelPath, fileName, fatal, options, false); - if (buffer === null) { - return null; - } +// src/models/depth_anything/modeling_depth_anything.js +var DepthAnythingPreTrainedModel = class extends PreTrainedModel { +}; +var DepthAnythingForDepthEstimation = class extends DepthAnythingPreTrainedModel { +}; - const decoder = new TextDecoder('utf-8'); - return decoder.decode(/** @type {Uint8Array} */(buffer)); -} +// src/models/depth_pro/modeling_depth_pro.js +var DepthProPreTrainedModel = class extends PreTrainedModel { +}; +var DepthProForDepthEstimation = class extends DepthProPreTrainedModel { +}; -/** - * Fetches a JSON file from a given path and file name. - * - * @param {string} modelPath The path to the directory containing the file. - * @param {string} fileName The name of the file to fetch. - * @param {boolean} [fatal=true] Whether to throw an error if the file is not found. - * @param {PretrainedOptions} [options] An object containing optional parameters. - * @returns {Promise} The JSON data parsed into a JavaScript object. - * @throws Will throw an error if the file is not found and `fatal` is true. - */ -async function getModelJSON(modelPath, fileName, fatal = true, options = {}) { - const text = await getModelText(modelPath, fileName, fatal, options); - if (text === null) { - // Return empty object - return {}; - } +// src/models/detr/modeling_detr.js +var DetrPreTrainedModel = class extends PreTrainedModel { +}; +var DetrModel = class extends DetrPreTrainedModel { +}; +var DetrForObjectDetection = class extends DetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new DetrObjectDetectionOutput(await super._call(model_inputs)); + } +}; +var DetrForSegmentation = class extends DetrPreTrainedModel { + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new DetrSegmentationOutput(await super._call(model_inputs)); + } +}; +var DetrObjectDetectionOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } +}; +var DetrSegmentationOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits The output logits of the model. + * @param {Tensor} output.pred_boxes Predicted boxes. + * @param {Tensor} output.pred_masks Predicted masks. + */ + constructor({ logits, pred_boxes, pred_masks }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + this.pred_masks = pred_masks; + } +}; - return JSON.parse(text); -} -/** - * Read and track progress when reading a Response object - * - * @param {Response|FileResponse} response The Response object to read - * @param {(data: {progress: number, loaded: number, total: number}) => void} progress_callback The function to call with progress updates - * @returns {Promise} A Promise that resolves with the Uint8Array buffer - */ -async function readResponse(response, progress_callback) { +// src/models/dinov2/modeling_dinov2.js +var Dinov2PreTrainedModel = class extends PreTrainedModel { +}; +var Dinov2Model = class extends Dinov2PreTrainedModel { +}; +var Dinov2ForImageClassification = class extends Dinov2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - const contentLength = response.headers.get('Content-Length'); - if (contentLength === null) { - console.warn('Unable to determine content-length from response headers. Will expand buffer when needed.') - } - let total = parseInt(contentLength ?? '0'); - let buffer = new Uint8Array(total); - let loaded = 0; +// src/models/dinov2_with_registers/modeling_dinov2_with_registers.js +var Dinov2WithRegistersPreTrainedModel = class extends PreTrainedModel { +}; +var Dinov2WithRegistersModel = class extends Dinov2WithRegistersPreTrainedModel { +}; +var Dinov2WithRegistersForImageClassification = class extends Dinov2WithRegistersPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - const reader = response.body.getReader(); - async function read() { - const { done, value } = await reader.read(); - if (done) return; +// src/models/dinov3_convnext/modeling_dinov3_convnext.js +var DINOv3ConvNextPreTrainedModel = class extends PreTrainedModel { +}; +var DINOv3ConvNextModel = class extends DINOv3ConvNextPreTrainedModel { +}; - const newLoaded = loaded + value.length; - if (newLoaded > total) { - total = newLoaded; +// src/models/dinov3_vit/modeling_dinov3_vit.js +var DINOv3ViTPreTrainedModel = class extends PreTrainedModel { +}; +var DINOv3ViTModel = class extends DINOv3ViTPreTrainedModel { +}; - // Adding the new data will overflow buffer. - // In this case, we extend the buffer - const newBuffer = new Uint8Array(total); +// src/models/distilbert/modeling_distilbert.js +var DistilBertPreTrainedModel = class extends PreTrainedModel { +}; +var DistilBertModel = class extends DistilBertPreTrainedModel { +}; +var DistilBertForSequenceClassification = class extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var DistilBertForTokenClassification = class extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var DistilBertForQuestionAnswering = class extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; +var DistilBertForMaskedLM = class extends DistilBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; - // copy contents - newBuffer.set(buffer); +// src/models/donut_swin/modeling_donut_swin.js +var DonutSwinPreTrainedModel = class extends PreTrainedModel { +}; +var DonutSwinModel = class extends DonutSwinPreTrainedModel { +}; - buffer = newBuffer; - } - buffer.set(value, loaded); - loaded = newLoaded; +// src/models/dpt/modeling_dpt.js +var DPTPreTrainedModel = class extends PreTrainedModel { +}; +var DPTModel = class extends DPTPreTrainedModel { +}; +var DPTForDepthEstimation = class extends DPTPreTrainedModel { +}; - const progress = (loaded / total) * 100; +// src/models/efficientnet/modeling_efficientnet.js +var EfficientNetPreTrainedModel = class extends PreTrainedModel { +}; +var EfficientNetModel = class extends EfficientNetPreTrainedModel { +}; +var EfficientNetForImageClassification = class extends EfficientNetPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - // Call your function here - progress_callback({ progress, loaded, total }); +// src/models/electra/modeling_electra.js +var ElectraPreTrainedModel = class extends PreTrainedModel { +}; +var ElectraModel = class extends ElectraPreTrainedModel { +}; +var ElectraForMaskedLM = class extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var ElectraForSequenceClassification = class extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var ElectraForTokenClassification = class extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var ElectraForQuestionAnswering = class extends ElectraPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - return read(); +// src/models/embedding_gemma2/modeling_embedding_gemma2.js +var EmbeddingGemma2PreTrainedModel = class extends PreTrainedModel { +}; +var EmbeddingGemma2Model = class extends EmbeddingGemma2PreTrainedModel { + async forward({ + input_ids, + attention_mask, + pixel_values = null, + image_position_ids = null, + pixel_values_videos = null, + video_position_ids = null, + input_features = null, + input_features_mask = null + }) { + const features = { + image_features: pixel_values && await this.encode_image({ pixel_values, pixel_position_ids: image_position_ids }), + video_features: pixel_values_videos && await this.encode_image({ + pixel_values: pixel_values_videos, + pixel_position_ids: video_position_ids + }), + audio_features: input_features && await this.encode_audio({ input_features, input_features_mask }) + }; + const { image_token_id, video_token_id, audio_token_id, text_config } = ( + /** @type {any} */ + this.config + ); + const token_ids = { image: image_token_id, video: video_token_id, audio: audio_token_id }; + for (const [modality, token_id] of Object.entries(token_ids)) { + const name = `${modality}_features`; + features[name] ??= new Tensor3("float32", new Float32Array(0), [0, text_config.hidden_size]); + let num_tokens = 0; + for (const id of input_ids.data) { + if (Number(id) === token_id) ++num_tokens; + } + if (num_tokens !== features[name].dims[0]) { + throw new Error( + `The number of ${modality} tokens (${num_tokens}) and ${modality} features (${features[name].dims[0]}) do not match.` + ); + } } + return await sessionRun(this.sessions["model"], { input_ids, attention_mask, ...features }); + } +}; - // Actually read - await read(); - - return buffer; -} - -/** - * Joins multiple parts of a path into a single path, while handling leading and trailing slashes. - * - * @param {...string} parts Multiple parts of a path. - * @returns {string} A string representing the joined path. - */ -function pathJoin(...parts) { - // https://stackoverflow.com/a/55142565 - parts = parts.map((part, index) => { - if (index) { - part = part.replace(new RegExp('^/'), ''); - } - if (index !== parts.length - 1) { - part = part.replace(new RegExp('/$'), ''); - } - return part; - }) - return parts.join('/'); -} - - -/***/ }), - -/***/ "./src/utils/image.js": -/*!****************************!*\ - !*** ./src/utils/image.js ***! - \****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ RawImage: () => (/* binding */ RawImage), -/* harmony export */ load_image: () => (/* binding */ load_image) -/* harmony export */ }); -/* harmony import */ var _core_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./core.js */ "./src/utils/core.js"); -/* harmony import */ var _hub_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hub.js */ "./src/utils/hub.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); -/* harmony import */ var _tensor_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var sharp__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! sharp */ "?2b25"); - -/** - * @file Helper module for image processing. - * - * These functions and classes are only used internally, - * meaning an end-user shouldn't need to access anything here. - * - * @module utils/image - */ - +// src/models/ernie4_5/modeling_ernie4_5.js +var Ernie4_5PretrainedModel = class extends PreTrainedModel { +}; +var Ernie4_5Model = class extends Ernie4_5PretrainedModel { +}; +var Ernie4_5ForCausalLM = class extends Ernie4_5PretrainedModel { +}; +// src/models/esm/modeling_esm.js +var EsmPreTrainedModel = class extends PreTrainedModel { +}; +var EsmModel = class extends EsmPreTrainedModel { +}; +var EsmForMaskedLM = class extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var EsmForSequenceClassification = class extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var EsmForTokenClassification = class extends EsmPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +// src/models/eurobert/modeling_eurobert.js +var EuroBertPreTrainedModel = class extends PreTrainedModel { +}; +var EuroBertModel = class extends EuroBertPreTrainedModel { +}; +var EuroBertForMaskedLM = class extends EuroBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var EuroBertForSequenceClassification = class extends EuroBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var EuroBertForTokenClassification = class extends EuroBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +// src/models/exaone/modeling_exaone.js +var ExaonePreTrainedModel = class extends PreTrainedModel { +}; +var ExaoneModel = class extends ExaonePreTrainedModel { +}; +var ExaoneForCausalLM = class extends ExaonePreTrainedModel { +}; +// src/models/falcon/modeling_falcon.js +var FalconPreTrainedModel = class extends PreTrainedModel { +}; +var FalconModel = class extends FalconPreTrainedModel { +}; +var FalconForCausalLM = class extends FalconPreTrainedModel { +}; -// Will be empty (or not used) if running in browser or web-worker +// src/models/falcon_h1/modeling_falcon_h1.js +var FalconH1PreTrainedModel = class extends PreTrainedModel { +}; +var FalconH1Model = class extends FalconH1PreTrainedModel { +}; +var FalconH1ForCausalLM = class extends FalconH1PreTrainedModel { +}; +// src/models/fastvit/modeling_fastvit.js +var FastViTPreTrainedModel = class extends PreTrainedModel { +}; +var FastViTModel = class extends FastViTPreTrainedModel { +}; +var FastViTForImageClassification = class extends FastViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; -let createCanvasFunction; -let ImageDataClass; -let loadImageFunction; -const IS_BROWSER_OR_WEBWORKER = _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_BROWSER_ENV || _env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV; -if (IS_BROWSER_OR_WEBWORKER) { - // Running in browser or web-worker - createCanvasFunction = (/** @type {number} */ width, /** @type {number} */ height) => { - if (!self.OffscreenCanvas) { - throw new Error('OffscreenCanvas not supported by this browser.'); - } - return new self.OffscreenCanvas(width, height) +// src/models/florence2/modeling_florence2.js +var Florence2PreTrainedModel = class extends PreTrainedModel { + forward_params = [ + // Encoder inputs + "input_ids", + "inputs_embeds", + "attention_mask", + "pixel_values", + // Decoder inputs + "encoder_outputs", + "decoder_input_ids", + "decoder_inputs_embeds", + "decoder_attention_mask", + "past_key_values" + ]; + main_input_name = "inputs_embeds"; +}; +var Florence2ForConditionalGeneration = class extends Florence2PreTrainedModel { + _merge_input_ids_with_image_features({ inputs_embeds, image_features, input_ids, attention_mask }) { + return { + inputs_embeds: cat( + [ + image_features, + // image embeds + inputs_embeds + // task prefix embeds + ], + 1 + ), + attention_mask: cat( + [ + ones(image_features.dims.slice(0, 2)), + // image attention mask + attention_mask + // task prefix attention mask + ], + 1 + ) + }; + } + async _prepare_inputs_embeds({ input_ids, pixel_values, inputs_embeds, attention_mask }) { + if (!input_ids && !pixel_values) { + throw new Error("Either `input_ids` or `pixel_values` should be provided."); + } + let text_features, image_features; + if (input_ids) { + text_features = await this.encode_text({ input_ids }); + } + if (pixel_values) { + image_features = await this.encode_image({ pixel_values }); + } + if (text_features && image_features) { + ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({ + inputs_embeds: text_features, + image_features, + input_ids, + attention_mask + })); + } else { + inputs_embeds = text_features || image_features; + } + return { inputs_embeds, attention_mask }; + } + async forward({ + input_ids, + pixel_values, + attention_mask, + decoder_input_ids, + decoder_attention_mask, + encoder_outputs, + past_key_values, + inputs_embeds, + decoder_inputs_embeds, + num_logits_to_keep = null + }) { + if (!inputs_embeds) { + ({ inputs_embeds, attention_mask } = await this._prepare_inputs_embeds({ + input_ids, + pixel_values, + inputs_embeds, + attention_mask + })); + } + if (!encoder_outputs) { + let { last_hidden_state } = await encoder_forward(this, { inputs_embeds, attention_mask }); + encoder_outputs = last_hidden_state; + } + if (!decoder_inputs_embeds) { + if (!decoder_input_ids) { + throw new Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided."); + } + decoder_inputs_embeds = await this.encode_text({ input_ids: decoder_input_ids }); + } + const decoderFeeds = { + inputs_embeds: decoder_inputs_embeds, + attention_mask: decoder_attention_mask, + encoder_attention_mask: attention_mask, + encoder_hidden_states: encoder_outputs, + past_key_values, + num_logits_to_keep }; - loadImageFunction = self.createImageBitmap; - ImageDataClass = self.ImageData; + return await decoder_forward(this, decoderFeeds, true); + } +}; + +// src/models/gemma/modeling_gemma.js +var GemmaPreTrainedModel = class extends PreTrainedModel { +}; +var GemmaModel = class extends GemmaPreTrainedModel { +}; +var GemmaForCausalLM = class extends GemmaPreTrainedModel { +}; -} else if (sharp__WEBPACK_IMPORTED_MODULE_4__) { - // Running in Node.js, electron, or other non-browser environment +// src/models/gemma2/modeling_gemma2.js +var Gemma2PreTrainedModel = class extends PreTrainedModel { +}; +var Gemma2Model = class extends Gemma2PreTrainedModel { +}; +var Gemma2ForCausalLM = class extends Gemma2PreTrainedModel { +}; - loadImageFunction = async (/**@type {sharp.Sharp}*/img) => { - const metadata = await img.metadata(); - const rawChannels = metadata.channels; +// src/models/llava/modeling_llava.js +var LlavaPreTrainedModel = class extends PreTrainedModel { + forward_params = ["input_ids", "attention_mask", "pixel_values", "position_ids", "past_key_values"]; +}; +var LlavaForConditionalGeneration = class extends LlavaPreTrainedModel { + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_index ?? this.config.image_token_id, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } +}; +var Moondream1ForConditionalGeneration = class extends LlavaForConditionalGeneration { +}; +var LlavaQwen2ForCausalLM = class extends LlavaForConditionalGeneration { +}; - const { data, info } = await img.rotate().raw().toBuffer({ resolveWithObject: true }); +// src/models/gemma3/modeling_gemma3.js +var Gemma3PreTrainedModel = class extends PreTrainedModel { +}; +var Gemma3Model = class extends Gemma3PreTrainedModel { +}; +var Gemma3ForConditionalGeneration = class extends LlavaForConditionalGeneration { +}; +var Gemma3ForCausalLM = class extends Gemma3ForConditionalGeneration { +}; - const newImage = new RawImage(new Uint8ClampedArray(data), info.width, info.height, info.channels); - if (rawChannels !== undefined && rawChannels !== info.channels) { - // Make sure the new image has the same number of channels as the input image. - // This is necessary for grayscale images. - newImage.convert(rawChannels); +// src/models/gemma3n/modeling_gemma3n.js +var Gemma3nPreTrainedModel = class extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "inputs_embeds", + "per_layer_inputs", + "position_ids", + "pixel_values", + "input_features", + "input_features_mask", + "past_key_values" + ]; +}; +var Gemma3nForConditionalGeneration = class extends Gemma3nPreTrainedModel { + async forward({ + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + pixel_values = null, + input_features = null, + input_features_mask = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + per_layer_inputs = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + num_logits_to_keep = null, + // TODO: needed? + ...kwargs + }) { + if (!inputs_embeds || !per_layer_inputs) { + ({ inputs_embeds, per_layer_inputs } = await sessionRun(this.sessions["embed_tokens"], { + input_ids + })); + if (input_ids.dims[1] !== 1) { + if (pixel_values) { + const { image_features } = await this._encode_vision({ pixel_values, ...kwargs }); + ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_image_features({ + image_features, + inputs_embeds, + input_ids, + attention_mask + })); + } + if (input_features) { + const { audio_features } = await sessionRun(this.sessions["audio_encoder"], { + input_features, + input_features_mask + }); + ({ inputs_embeds, attention_mask } = this._merge_input_ids_with_audio_features({ + audio_features, + inputs_embeds, + input_ids, + attention_mask + })); } - return newImage; + } } + const outputs = await decoder_forward( + this, + { + inputs_embeds, + per_layer_inputs, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor, + num_logits_to_keep + }, + true + ); + return outputs; + } + _encode_vision(kwargs) { + return sessionRun(this.sessions["vision_encoder"], { pixel_values: kwargs.pixel_values }); + } + _merge_input_ids_with_image_features(kwargs) { + const vision_hidden_size = kwargs.image_features.dims.at(-1); + const reshaped_image_hidden_states = kwargs.image_features.view(-1, vision_hidden_size); + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_id, + ...kwargs, + image_features: reshaped_image_hidden_states + }); + } + _merge_input_ids_with_audio_features(kwargs) { + const audio_hidden_size = kwargs.audio_features.dims.at(-1); + const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); + return default_merge_input_ids_with_audio_features({ + // @ts-ignore + audio_token_id: this.config.audio_token_id, + ...kwargs, + audio_features: reshaped_audio_features + }); + } +}; +var Gemma3nForCausalLM = class extends Gemma3nForConditionalGeneration { +}; -} else { - throw new Error('Unable to load image processing library.'); -} - - -// Defined here: https://github.com/python-pillow/Pillow/blob/a405e8406b83f8bfb8916e93971edc7407b8b1ff/src/libImaging/Imaging.h#L262-L268 -const RESAMPLING_MAPPING = { - 0: 'nearest', - 1: 'lanczos', - 2: 'bilinear', - 3: 'bicubic', - 4: 'box', - 5: 'hamming', -} - -/** - * Mapping from file extensions to MIME types. - */ -const CONTENT_TYPE_MAP = new Map([ - ['png', 'image/png'], - ['jpg', 'image/jpeg'], - ['jpeg', 'image/jpeg'], - ['gif', 'image/gif'], -]); +// src/models/gemma4/modeling_gemma4.js +var Gemma4ForConditionalGeneration = class extends Gemma3nForConditionalGeneration { + forward_params = [ + "input_ids", + "attention_mask", + "inputs_embeds", + "per_layer_inputs", + "position_ids", + "pixel_values", + "image_position_ids", + "input_features", + "input_features_mask", + "past_key_values" + ]; + _encode_vision(kwargs) { + return sessionRun(this.sessions["vision_encoder"], { + pixel_values: kwargs.pixel_values, + pixel_position_ids: kwargs.image_position_ids + }); + } +}; +var Gemma4ForCausalLM = class extends Gemma4ForConditionalGeneration { +}; -class RawImage { +// src/models/glm/modeling_glm.js +var GlmPreTrainedModel = class extends PreTrainedModel { +}; +var GlmModel = class extends GlmPreTrainedModel { +}; +var GlmForCausalLM = class extends GlmPreTrainedModel { +}; - /** - * Create a new `RawImage` object. - * @param {Uint8ClampedArray|Uint8Array} data The pixel data. - * @param {number} width The width of the image. - * @param {number} height The height of the image. - * @param {1|2|3|4} channels The number of channels. - */ - constructor(data, width, height, channels) { - this.data = data; - this.width = width; - this.height = height; - this.channels = channels; - } +// src/models/glm_moe_dsa/modeling_glm_moe_dsa.js +var GlmMoeDsaPreTrainedModel = class extends PreTrainedModel { +}; +var GlmMoeDsaModel = class extends GlmMoeDsaPreTrainedModel { +}; +var GlmMoeDsaForCausalLM = class extends GlmMoeDsaPreTrainedModel { +}; - /** - * Returns the size of the image (width, height). - * @returns {[number, number]} The size of the image (width, height). - */ - get size() { - return [this.width, this.height]; +// src/models/qwen2_vl/modeling_qwen2_vl.js +var Qwen2VLPreTrainedModel = class extends PreTrainedModel { + forward_params = [ + // Text inputs + "input_ids", + "attention_mask", + "position_ids", + "past_key_values", + // Vision inputs + "pixel_values", + "image_grid_thw" + ]; +}; +var Qwen2VLForConditionalGeneration = class extends Qwen2VLPreTrainedModel { + // NOTE: This is used as the base class for all Qwen VL models and their CausalLM variants. + // CausalLM variants (e.g., Qwen2VLForCausalLM) extend this class but load only + // embed_tokens + decoder_model_merged (no vision_encoder) via MultimodalLanguageModelOnly type. + image_grid_thw_name = "grid_thw"; + /** + * Compute text-only 3D rope position IDs (all 3 dims get the same 1D positions). + * @param {Tensor} input_ids + * @param {Tensor} attention_mask + * @returns {[Tensor, Tensor]} [position_ids, mrope_position_deltas] + */ + _get_text_only_rope_index(input_ids, attention_mask) { + if (attention_mask) { + const { data, dims } = cumsum_masked_fill(attention_mask); + const position_ids = BigInt64Array.from({ length: 3 * data.length }, (_, i) => data[i % data.length]); + const mrope_position_deltas = Array.from( + { length: dims[0] }, + (_, i) => max(data.subarray(dims[1] * i, dims[1] * (i + 1)))[0] + 1n + BigInt(dims[1]) + ); + return [ + new Tensor3("int64", position_ids, [3, ...dims]), + new Tensor3("int64", mrope_position_deltas, [mrope_position_deltas.length, 1]) + ]; + } else { + const [batch_size, seq_length] = input_ids.dims; + const position_ids = BigInt64Array.from( + { length: 3 * batch_size * seq_length }, + (_, i) => BigInt(Math.floor(i % seq_length / batch_size)) + ); + return [new Tensor3("int64", position_ids, [3, ...input_ids.dims]), zeros([batch_size, 1])]; } - - /** - * Helper method for reading an image from a variety of input types. - * @param {RawImage|string|URL|Blob|HTMLCanvasElement|OffscreenCanvas} input - * @returns The image object. - * - * **Example:** Read image from a URL. - * ```javascript - * let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg'); - * // RawImage { - * // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ], - * // "width": 800, - * // "height": 533, - * // "channels": 3 - * // } - * ``` - */ - static async read(input) { - if (input instanceof RawImage) { - return input; - } else if (typeof input === 'string' || input instanceof URL) { - return await this.fromURL(input); - } else if (input instanceof Blob) { - return await this.fromBlob(input); - } else if ( - (typeof HTMLCanvasElement !== "undefined" && input instanceof HTMLCanvasElement) - || - (typeof OffscreenCanvas !== "undefined" && input instanceof OffscreenCanvas) - ) { - return this.fromCanvas(input); - } else { - throw new Error(`Unsupported input type: ${typeof input}`); + } + /** + * Reorder per-segment position ID lists from [seg1[t,h,w], seg2[t,h,w], ...] into + * global [all_t, all_h, all_w] order, then write back into the position_ids array + * respecting attention mask. + * @param {number[][]} llm_pos_ids_list List of per-segment position arrays, each of length 3*seg_len + * @param {number[]} attn_mask Attention mask for this batch element + * @param {number[][][]} position_ids_list [3][batch][seq] output array to write into + * @param {number} batch_idx Current batch index + * @returns {number[]} Flat reordered positions of length total_len + */ + _reorder_and_write_positions(llm_pos_ids_list, attn_mask, position_ids_list, batch_idx) { + const total_len = llm_pos_ids_list.reduce((acc, x) => acc + x.length, 0); + const llm_positions = new Array(total_len); + let index = 0; + for (let x = 0; x < 3; ++x) { + for (const val of llm_pos_ids_list) { + const seg_len = val.length / 3; + for (let z = x * seg_len; z < (x + 1) * seg_len; ++z) { + llm_positions[index++] = val[z]; } + } } - - /** - * Read an image from a canvas. - * @param {HTMLCanvasElement|OffscreenCanvas} canvas The canvas to read the image from. - * @returns {RawImage} The image object. - */ - static fromCanvas(canvas) { - if (!IS_BROWSER_OR_WEBWORKER) { - throw new Error('fromCanvas() is only supported in browser environments.') + let count2 = 0; + for (let y = 0; y < attn_mask.length; ++y) { + if (attn_mask[y] == 1) { + for (let x = 0; x < 3; ++x) { + position_ids_list[x][batch_idx][y] = llm_positions[x * total_len / 3 + count2]; } - - const ctx = /** @type {CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D} */ (canvas.getContext('2d')); - const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data; - return new RawImage(data, canvas.width, canvas.height, 4); + ++count2; + } } - - /** - * Read an image from a URL or file path. - * @param {string|URL} url The URL or file path to read the image from. - * @returns {Promise} The image object. - */ - static async fromURL(url) { - const response = await (0,_hub_js__WEBPACK_IMPORTED_MODULE_1__.getFile)(url); - if (response.status !== 200) { - throw new Error(`Unable to read image from "${url}" (${response.status} ${response.statusText})`); - } - const blob = await response.blob(); - return this.fromBlob(blob); + return llm_positions; + } + /** + * Build per-batch position ID segments for multimodal rope. + * Override this in subclasses to change how vision/text segments are identified and positioned. + * @param {object} params + * @param {any[]} params.filtered_ids - attention-masked token IDs for this batch element + * @param {any[][]} params.image_grid_thw_list - all image grid dimensions + * @param {any[][]} params.video_grid_thw_list - all video grid dimensions + * @param {number} params.spatial_merge_size + * @param {{image_index: number, video_index: number}} params.state - mutable counters shared across batches + * @returns {number[][]} llm_pos_ids_list - segments of [t..., h..., w...] positions + */ + _get_multimodal_rope_positions({ + filtered_ids, + image_grid_thw_list, + video_grid_thw_list, + spatial_merge_size, + state + }) { + const { image_token_id, video_token_id, vision_start_token_id } = this.config; + const ids = filtered_ids; + const vision_start_indices = ids.reduce((acc, x, idx) => { + if (x == vision_start_token_id) acc.push(idx); + return acc; + }, []); + const vision_tokens = vision_start_indices.map((x) => ids[x + 1]); + const image_nums = vision_tokens.filter((x) => x == image_token_id).length; + const video_nums = vision_tokens.filter((x) => x == video_token_id).length; + const llm_pos_ids_list = []; + let st = 0; + let remain_images = image_nums; + let remain_videos = video_nums; + for (let j2 = 0; j2 < vision_tokens.length; ++j2) { + const next_image_token = ids.findIndex((x, i) => i > st && x == image_token_id); + const next_video_token = ids.findIndex((x, i) => i > st && x == video_token_id); + const ed_image = remain_images > 0 && next_image_token !== -1 ? next_image_token : ids.length + 1; + const ed_video = remain_videos > 0 && next_video_token !== -1 ? next_video_token : ids.length + 1; + let ed; + let t, h, w; + if (ed_image < ed_video) { + [t, h, w] = image_grid_thw_list[state.image_index]; + ++state.image_index; + --remain_images; + ed = ed_image; + } else { + [t, h, w] = video_grid_thw_list[state.video_index]; + ++state.video_index; + --remain_videos; + ed = ed_video; + } + const [llm_grid_t, llm_grid_h, llm_grid_w] = [ + Number(t), + Math.floor(Number(h) / spatial_merge_size), + Math.floor(Number(w) / spatial_merge_size) + ]; + const text_len = ed - st; + const st_idx = llm_pos_ids_list.length > 0 ? max(llm_pos_ids_list.at(-1))[0] + 1 : 0; + llm_pos_ids_list.push(Array.from({ length: 3 * text_len }, (_, i) => st_idx + i % text_len)); + const offset = text_len + st_idx; + const grid_size = llm_grid_t * llm_grid_h * llm_grid_w; + const t_index = Array.from( + { length: grid_size }, + (_, i) => offset + Math.floor(i / (llm_grid_h * llm_grid_w)) + ); + const h_index = Array.from( + { length: grid_size }, + (_, i) => offset + Math.floor(i / llm_grid_w) % llm_grid_h + ); + const w_index = Array.from({ length: grid_size }, (_, i) => offset + i % llm_grid_w); + llm_pos_ids_list.push([t_index, h_index, w_index].flat()); + st = ed + grid_size; + } + if (st < ids.length) { + const st_idx = llm_pos_ids_list.length > 0 ? max(llm_pos_ids_list.at(-1))[0] + 1 : 0; + const text_len = ids.length - st; + llm_pos_ids_list.push(Array.from({ length: 3 * text_len }, (_, i) => st_idx + i % text_len)); + } + return llm_pos_ids_list; + } + /** + * Calculate the 3D rope index based on image and video's temporal, height and width in LLM. + * + * Explanation: + * Each embedding sequence contains vision embedding and text embedding or just contains text embedding. + * + * For pure text embedding sequence, the rotary position embedding has no difference with mordern LLMs. + * Examples: + * input_ids: [T T T T T], here T is for text. + * temporal position_ids: [0, 1, 2, 3, 4] + * height position_ids: [0, 1, 2, 3, 4] + * width position_ids: [0, 1, 2, 3, 4] + * + * For vision and text embedding sequence, we calculate 3D rotary position embedding for vision part + * and 1D rotary position embeddin for text part. + * Examples: + * Assume we have a video input with 3 temporal patches, 2 height patches and 2 width patches. + * input_ids: [V V V V V V V V V V V V T T T T T], here V is for vision. + * vision temporal position_ids: [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2] + * vision height position_ids: [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1] + * vision width position_ids: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + * text temporal position_ids: [3, 4, 5, 6, 7] + * text height position_ids: [3, 4, 5, 6, 7] + * text width position_ids: [3, 4, 5, 6, 7] + * Here we calculate the text start position_ids as the max vision position_ids plus 1. + * + * @param {Tensor} input_ids Indices of input sequence tokens in the vocabulary. Tensor of shape `(batch_size, sequence_length)`. + * @param {Tensor} image_grid_thw (Optional) The temporal, height and width of feature shape of each image in LLM. Tensor of shape `(num_images, 3)`. + * @param {Tensor} video_grid_thw (Optional) The temporal, height and width of feature shape of each video in LLM. Tensor of shape `(num_videos, 3)`. + * @param {Tensor} attention_mask (Optional) Mask to avoid performing attention on padding token indices. Tensor of shape `(batch_size, sequence_length)`. + * @returns {[Tensor, Tensor]} [position_ids, mrope_position_deltas] + */ + get_rope_index(input_ids, image_grid_thw, video_grid_thw, attention_mask) { + const { vision_config } = this.config; + const spatial_merge_size = vision_config.spatial_merge_size ?? 2; + if (image_grid_thw || video_grid_thw) { + const total_input_ids = input_ids.tolist(); + if (!attention_mask) { + attention_mask = ones_like(input_ids); + } + const attention_mask_list = attention_mask.tolist(); + const position_ids_list = Array.from( + { length: 3 }, + () => Array.from({ length: input_ids.dims[0] }, () => Array.from({ length: input_ids.dims[1] }, () => 0)) + ); + const image_grid_thw_list = image_grid_thw ? image_grid_thw.tolist() : []; + const video_grid_thw_list = video_grid_thw ? video_grid_thw.tolist() : []; + const state = { image_index: 0, video_index: 0 }; + const mrope_position_deltas = []; + for (let i = 0; i < total_input_ids.length; ++i) { + const filtered_ids = total_input_ids[i].filter((_, j2) => attention_mask_list[i][j2] == 1); + const llm_pos_ids_list = this._get_multimodal_rope_positions({ + filtered_ids, + image_grid_thw_list, + video_grid_thw_list, + spatial_merge_size, + state + }); + const llm_positions = this._reorder_and_write_positions( + llm_pos_ids_list, + attention_mask_list[i], + position_ids_list, + i + ); + mrope_position_deltas.push(max(llm_positions)[0] + 1 - total_input_ids[i].length); + } + return [ + new Tensor3("int64", position_ids_list.flat(Infinity), [3, input_ids.dims[0], input_ids.dims[1]]), + new Tensor3("int64", mrope_position_deltas, [mrope_position_deltas.length, 1]) + ]; + } else { + return this._get_text_only_rope_index(input_ids, attention_mask); } - - /** - * Helper method to create a new Image from a blob. - * @param {Blob} blob The blob to read the image from. - * @returns {Promise} The image object. - */ - static async fromBlob(blob) { - if (IS_BROWSER_OR_WEBWORKER) { - // Running in environment with canvas - const img = await loadImageFunction(blob); - - const ctx = createCanvasFunction(img.width, img.height).getContext('2d'); - - // Draw image to context - ctx.drawImage(img, 0, 0); - - return new this(ctx.getImageData(0, 0, img.width, img.height).data, img.width, img.height, 4); - - } else { - // Use sharp.js to read (and possible resize) the image. - const img = sharp__WEBPACK_IMPORTED_MODULE_4__(await blob.arrayBuffer()); - - return await loadImageFunction(img); - } + } + async encode_image({ pixel_values, image_grid_thw }) { + const features = (await sessionRun(this.sessions["vision_encoder"], { + pixel_values, + [this.image_grid_thw_name]: image_grid_thw + })).image_features; + return features; + } + _merge_input_ids_with_image_features(kwargs) { + return default_merge_input_ids_with_image_features({ + // @ts-ignore + image_token_id: this.config.image_token_id, + ...kwargs + }); + } + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + setNumLogitsToKeep(this, model_inputs, 1n); + if (!model_inputs.attention_mask || model_inputs.position_ids) { + return model_inputs; + } + const session = this.sessions["decoder_model_merged"] ?? this.sessions["model"]; + if (!session.inputNames.includes("position_ids")) { + return model_inputs; + } + if (!model_inputs.past_key_values) { + [model_inputs.position_ids, model_inputs.rope_deltas] = this.get_rope_index( + model_inputs.input_ids, + model_inputs.image_grid_thw, + model_inputs.video_grid_thw, + model_inputs.attention_mask + ); + } else { + model_inputs.pixel_values = null; + const past_length = model_inputs.past_key_values.get_seq_length(); + if (past_length < model_inputs.input_ids.dims[1]) { + const [full_position_ids, rope_deltas] = this.get_rope_index( + model_inputs.input_ids, + model_inputs.image_grid_thw, + model_inputs.video_grid_thw, + model_inputs.attention_mask + ); + model_inputs.rope_deltas = rope_deltas; + model_inputs.position_ids = full_position_ids.slice(null, null, [past_length, null]); + model_inputs.input_ids = model_inputs.input_ids.slice(null, [past_length, null]); + } else { + if (!model_inputs.rope_deltas) { + [, model_inputs.rope_deltas] = this.get_rope_index( + model_inputs.input_ids, + model_inputs.image_grid_thw, + model_inputs.video_grid_thw, + model_inputs.attention_mask + ); + } + const delta = BigInt(past_length); + const rope_deltas_list = model_inputs.rope_deltas.map((x) => delta + x); + model_inputs.position_ids = stack([rope_deltas_list, rope_deltas_list, rope_deltas_list], 0); + } } + return model_inputs; + } +}; +var Qwen2VLForCausalLM = class extends Qwen2VLForConditionalGeneration { +}; - /** - * Helper method to create a new Image from a tensor - * @param {Tensor} tensor - */ - static fromTensor(tensor, channel_format = 'CHW') { - if (tensor.dims.length !== 3) { - throw new Error(`Tensor should have 3 dimensions, but has ${tensor.dims.length} dimensions.`); - } +// src/models/qwen2_5_vl/modeling_qwen2_5_vl.js +var Qwen2_5_VLForConditionalGeneration = class extends Qwen2VLForConditionalGeneration { + image_grid_thw_name = "image_grid_thw"; +}; +var Qwen2_5_VLForCausalLM = class extends Qwen2VLForCausalLM { + image_grid_thw_name = "image_grid_thw"; +}; - if (channel_format === 'CHW') { - tensor = tensor.transpose(1, 2, 0); - } else if (channel_format === 'HWC') { - // Do nothing - } else { - throw new Error(`Unsupported channel format: ${channel_format}`); - } - if (!(tensor.data instanceof Uint8ClampedArray || tensor.data instanceof Uint8Array)) { - throw new Error(`Unsupported tensor type: ${tensor.type}`); - } - switch (tensor.dims[2]) { - case 1: - case 2: - case 3: - case 4: - return new RawImage(tensor.data, tensor.dims[1], tensor.dims[0], tensor.dims[2]); - default: - throw new Error(`Unsupported number of channels: ${tensor.dims[2]}`); - } +// src/models/glm_ocr/modeling_glm_ocr.js +var GlmOcrForConditionalGeneration = class extends Qwen2_5_VLForConditionalGeneration { + /** + * Compute 3D positional indices for vision tokens. + * Temporal is constant, height is repeat-interleaved, width tiles. + * @param {number} start_position + * @param {number[]} grid_thw [T, H, W] + * @param {number} temp_merge_size + * @param {number} spatial_merge_size + * @returns {number[]} Flat array of length 3 * seq_len: [temporal..., height..., width...] + */ + get_vision_position_ids(start_position, grid_thw, temp_merge_size, spatial_merge_size) { + const llm_grid_t = Math.floor(grid_thw[0] / temp_merge_size); + const llm_grid_h = Math.floor(grid_thw[1] / spatial_merge_size); + const llm_grid_w = Math.floor(grid_thw[2] / spatial_merge_size); + const seq_len = llm_grid_h * llm_grid_w * llm_grid_t; + const t_pos = Array.from({ length: seq_len }, () => start_position); + const h_pos = Array.from( + { length: seq_len }, + (_, i) => start_position + Math.floor(i / (llm_grid_w * llm_grid_t)) + ); + const w_pos = Array.from({ length: seq_len }, (_, i) => start_position + i % llm_grid_w); + return [...t_pos, ...h_pos, ...w_pos]; + } + /** + * GlmOcr uses mm_token_type_ids-style grouping (image tokens identified by image_token_id) + * instead of vision_start_token_id scanning used by Qwen2VL. + * After a vision segment, position advances by max(h, w) / spatial_merge_size. + */ + _get_multimodal_rope_positions({ + filtered_ids, + image_grid_thw_list, + video_grid_thw_list, + spatial_merge_size, + state + }) { + const { image_token_id } = this.config; + const groups = []; + let group_start = 0; + let current_type = filtered_ids[0] == image_token_id ? 1 : 0; + for (let j2 = 1; j2 <= filtered_ids.length; ++j2) { + const t = j2 < filtered_ids.length ? filtered_ids[j2] == image_token_id ? 1 : 0 : -1; + if (t !== current_type) { + groups.push([current_type, group_start, j2]); + group_start = j2; + current_type = t; + } } - - /** - * Convert the image to grayscale format. - * @returns {RawImage} `this` to support chaining. - */ - grayscale() { - if (this.channels === 1) { - return this; - } - - const newData = new Uint8ClampedArray(this.width * this.height * 1); - switch (this.channels) { - case 3: // rgb to grayscale - case 4: // rgba to grayscale - for (let i = 0, offset = 0; i < this.data.length; i += this.channels) { - const red = this.data[i]; - const green = this.data[i + 1]; - const blue = this.data[i + 2]; - - newData[offset++] = Math.round(0.2989 * red + 0.5870 * green + 0.1140 * blue); - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(newData, this.width, this.height, 1); + let current_pos = 0; + const llm_pos_ids_list = []; + for (const [modality_type, start_idx, end_idx] of groups) { + if (modality_type === 0) { + const text_len = end_idx - start_idx; + llm_pos_ids_list.push(Array.from({ length: 3 * text_len }, (_, i) => current_pos + i % text_len)); + current_pos += text_len; + } else { + const grid_thw = image_grid_thw_list[state.image_index++].map(Number); + const temp_merge_size = grid_thw[0]; + llm_pos_ids_list.push( + this.get_vision_position_ids(current_pos, grid_thw, temp_merge_size, spatial_merge_size) + ); + current_pos += Math.max(grid_thw[1], grid_thw[2]) / spatial_merge_size; + } } + return llm_pos_ids_list; + } +}; - /** - * Convert the image to RGB format. - * @returns {RawImage} `this` to support chaining. - */ - rgb() { - if (this.channels === 3) { - return this; - } - - const newData = new Uint8ClampedArray(this.width * this.height * 3); - - switch (this.channels) { - case 1: // grayscale to rgb - for (let i = 0, offset = 0; i < this.data.length; ++i) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - } - break; - case 4: // rgba to rgb - for (let i = 0, offset = 0; i < this.data.length; i += 4) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i + 1]; - newData[offset++] = this.data[i + 2]; - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } - return this._update(newData, this.width, this.height, 3); +// src/models/glpn/modeling_glpn.js +var GLPNPreTrainedModel = class extends PreTrainedModel { +}; +var GLPNModel = class extends GLPNPreTrainedModel { +}; +var GLPNForDepthEstimation = class extends GLPNPreTrainedModel { +}; - } +// src/models/gpt_bigcode/modeling_gpt_bigcode.js +var GPTBigCodePreTrainedModel = class extends PreTrainedModel { +}; +var GPTBigCodeModel = class extends GPTBigCodePreTrainedModel { +}; +var GPTBigCodeForCausalLM = class extends GPTBigCodePreTrainedModel { +}; - /** - * Convert the image to RGBA format. - * @returns {RawImage} `this` to support chaining. - */ - rgba() { - if (this.channels === 4) { - return this; - } +// src/models/gpt_neo/modeling_gpt_neo.js +var GPTNeoPreTrainedModel = class extends PreTrainedModel { +}; +var GPTNeoModel = class extends GPTNeoPreTrainedModel { +}; +var GPTNeoForCausalLM = class extends GPTNeoPreTrainedModel { +}; - const newData = new Uint8ClampedArray(this.width * this.height * 4); +// src/models/gpt_neox/modeling_gpt_neox.js +var GPTNeoXPreTrainedModel = class extends PreTrainedModel { +}; +var GPTNeoXModel = class extends GPTNeoXPreTrainedModel { +}; +var GPTNeoXForCausalLM = class extends GPTNeoXPreTrainedModel { +}; - switch (this.channels) { - case 1: // grayscale to rgba - for (let i = 0, offset = 0; i < this.data.length; ++i) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i]; - newData[offset++] = 255; - } - break; - case 3: // rgb to rgba - for (let i = 0, offset = 0; i < this.data.length; i += 3) { - newData[offset++] = this.data[i]; - newData[offset++] = this.data[i + 1]; - newData[offset++] = this.data[i + 2]; - newData[offset++] = 255; - } - break; - default: - throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`); - } +// src/models/gpt_oss/modeling_gpt_oss.js +var GptOssPreTrainedModel = class extends PreTrainedModel { +}; +var GptOssModel = class extends GptOssPreTrainedModel { +}; +var GptOssForCausalLM = class extends GptOssPreTrainedModel { +}; - return this._update(newData, this.width, this.height, 4); - } +// src/models/gpt2/modeling_gpt2.js +var GPT2PreTrainedModel = class extends PreTrainedModel { +}; +var GPT2Model = class extends GPT2PreTrainedModel { +}; +var GPT2LMHeadModel = class extends GPT2PreTrainedModel { +}; - /** - * Apply an alpha mask to the image. Operates in place. - * @param {RawImage} mask The mask to apply. It should have a single channel. - * @returns {RawImage} The masked image. - * @throws {Error} If the mask is not the same size as the image. - * @throws {Error} If the image does not have 4 channels. - * @throws {Error} If the mask is not a single channel. - */ - putAlpha(mask) { - if (mask.width !== this.width || mask.height !== this.height) { - throw new Error(`Expected mask size to be ${this.width}x${this.height}, but got ${mask.width}x${mask.height}`); - } - if (mask.channels !== 1) { - throw new Error(`Expected mask to have 1 channel, but got ${mask.channels}`); - } - - const this_data = this.data; - const mask_data = mask.data; - const num_pixels = this.width * this.height; - if (this.channels === 3) { - // Convert to RGBA and simultaneously apply mask to alpha channel - const newData = new Uint8ClampedArray(num_pixels * 4); - for (let i = 0, in_offset = 0, out_offset = 0; i < num_pixels; ++i) { - newData[out_offset++] = this_data[in_offset++]; - newData[out_offset++] = this_data[in_offset++]; - newData[out_offset++] = this_data[in_offset++]; - newData[out_offset++] = mask_data[i]; - } - return this._update(newData, this.width, this.height, 4); +// src/models/gptj/modeling_gptj.js +var GPTJPreTrainedModel = class extends PreTrainedModel { +}; +var GPTJModel = class extends GPTJPreTrainedModel { +}; +var GPTJForCausalLM = class extends GPTJPreTrainedModel { +}; - } else if (this.channels === 4) { - // Apply mask to alpha channel in place - for (let i = 0; i < num_pixels; ++i) { - this_data[4 * i + 3] = mask_data[i]; - } - return this; - } - throw new Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`); - } +// src/models/granite/modeling_granite.js +var GranitePreTrainedModel = class extends PreTrainedModel { +}; +var GraniteModel = class extends GranitePreTrainedModel { +}; +var GraniteForCausalLM = class extends GranitePreTrainedModel { +}; - /** - * Resize the image to the given dimensions. This method uses the canvas API to perform the resizing. - * @param {number} width The width of the new image. `null` or `-1` will preserve the aspect ratio. - * @param {number} height The height of the new image. `null` or `-1` will preserve the aspect ratio. - * @param {Object} options Additional options for resizing. - * @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use. - * @returns {Promise} `this` to support chaining. - */ - async resize(width, height, { - resample = 2, - } = {}) { +// src/models/granitemoehybrid/modeling_granitemoehybrid.js +var GraniteMoeHybridPreTrainedModel = class extends PreTrainedModel { +}; +var GraniteMoeHybridModel = class extends GraniteMoeHybridPreTrainedModel { +}; +var GraniteMoeHybridForCausalLM = class extends GraniteMoeHybridPreTrainedModel { +}; - // Do nothing if the image already has the desired size - if (this.width === width && this.height === height) { - return this; - } +// src/models/ultravox/modeling_ultravox.js +var UltravoxPreTrainedModel = class extends PreTrainedModel { + forward_params = ["input_ids", "attention_mask", "position_ids", "audio_values", "past_key_values"]; +}; +var UltravoxModel = class extends UltravoxPreTrainedModel { + _merge_input_ids_with_audio_features(kwargs) { + const audio_hidden_size = kwargs.audio_features.dims.at(-1); + const reshaped_audio_features = kwargs.audio_features.view(-1, audio_hidden_size); + return default_merge_input_ids_with_audio_features({ + // @ts-ignore + audio_token_id: this.config.ignore_index ?? this.config.audio_token_id ?? this.config.audio_token_index, + ...kwargs, + audio_features: reshaped_audio_features + }); + } +}; - // Ensure resample method is a string - let resampleMethod = RESAMPLING_MAPPING[resample] ?? resample; +// src/models/granite_speech/modeling_granite_speech.js +var GraniteSpeechForConditionalGeneration = class extends UltravoxModel { + forward_params = ["input_ids", "attention_mask", "input_features", "past_key_values"]; +}; - // Calculate width / height to maintain aspect ratio, in the event that - // the user passed a null value in. - // This allows users to pass in something like `resize(320, null)` to - // resize to 320 width, but maintain aspect ratio. - const nullish_width = (0,_core_js__WEBPACK_IMPORTED_MODULE_0__.isNullishDimension)(width); - const nullish_height = (0,_core_js__WEBPACK_IMPORTED_MODULE_0__.isNullishDimension)(height); - if (nullish_width && nullish_height) { - return this; - } else if (nullish_width) { - width = (height / this.height) * this.width; - } else if (nullish_height) { - height = (width / this.width) * this.height; - } +// src/models/grounding_dino/modeling_grounding_dino.js +var GroundingDinoPreTrainedModel = class extends PreTrainedModel { +}; +var GroundingDinoForObjectDetection = class extends GroundingDinoPreTrainedModel { +}; - if (IS_BROWSER_OR_WEBWORKER) { - // TODO use `resample` in browser environment +// src/models/groupvit/modeling_groupvit.js +var GroupViTPreTrainedModel = class extends PreTrainedModel { +}; +var GroupViTModel = class extends GroupViTPreTrainedModel { +}; - // Store number of channels before resizing - const numChannels = this.channels; +// src/models/helium/modeling_helium.js +var HeliumPreTrainedModel = class extends PreTrainedModel { +}; +var HeliumModel = class extends HeliumPreTrainedModel { +}; +var HeliumForCausalLM = class extends HeliumPreTrainedModel { +}; - // Create canvas object for this image - const canvas = this.toCanvas(); +// src/models/hiera/modeling_hiera.js +var HieraPreTrainedModel = class extends PreTrainedModel { +}; +var HieraModel = class extends HieraPreTrainedModel { +}; +var HieraForImageClassification = class extends HieraPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - // Actually perform resizing using the canvas API - const ctx = createCanvasFunction(width, height).getContext('2d'); +// src/models/hrm_text/modeling_hrm_text.js +var HrmTextPreTrainedModel = class extends PreTrainedModel { +}; +var HrmTextModel = class extends HrmTextPreTrainedModel { +}; +var HrmTextForCausalLM = class extends HrmTextPreTrainedModel { + forward_params = ["input_ids", "attention_mask", "token_type_ids", "past_key_values"]; + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + const prepared = decoder_prepare_inputs_for_generation(this, input_ids, model_inputs, generation_config); + prepared.token_type_ids = (prepared.past_key_values ? zeros_like : ones_like)(prepared.input_ids); + return prepared; + } +}; - // Draw image to context, resizing in the process - ctx.drawImage(canvas, 0, 0, width, height); +// src/models/wav2vec2/modeling_wav2vec2.js +var Wav2Vec2PreTrainedModel = class extends PreTrainedModel { +}; +var Wav2Vec2Model = class extends Wav2Vec2PreTrainedModel { +}; +var Wav2Vec2ForCTC = class extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; +var Wav2Vec2ForSequenceClassification = class extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var Wav2Vec2ForAudioFrameClassification = class extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; - // Create image from the resized data - const resizedImage = new RawImage(ctx.getImageData(0, 0, width, height).data, width, height, 4); +// src/models/hubert/modeling_hubert.js +var HubertPreTrainedModel = class extends PreTrainedModel { +}; +var HubertModel = class extends Wav2Vec2PreTrainedModel { +}; +var HubertForCTC = class extends Wav2Vec2PreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; +var HubertForSequenceClassification = class extends Wav2Vec2PreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - // Convert back so that image has the same number of channels as before - return resizedImage.convert(numChannels); +// src/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.js +var HunYuanDenseV1PreTrainedModel = class extends PreTrainedModel { +}; +var HunYuanDenseV1Model = class extends HunYuanDenseV1PreTrainedModel { +}; +var HunYuanDenseV1ForCausalLM = class extends HunYuanDenseV1PreTrainedModel { +}; - } else { - // Create sharp image from raw data, and resize - let img = this.toSharp(); - - switch (resampleMethod) { - case 'box': - case 'hamming': - if (resampleMethod === 'box' || resampleMethod === 'hamming') { - console.warn(`Resampling method ${resampleMethod} is not yet supported. Using bilinear instead.`); - resampleMethod = 'bilinear'; - } +// src/models/idefics3/modeling_idefics3.js +var Idefics3ForConditionalGeneration = class extends LlavaForConditionalGeneration { + forward_params = [ + "input_ids", + "attention_mask", + "pixel_values", + "pixel_attention_mask", + "position_ids", + "past_key_values" + ]; +}; - case 'nearest': - case 'bilinear': - case 'bicubic': - // Perform resizing using affine transform. - // This matches how the python Pillow library does it. - img = img.affine([width / this.width, 0, 0, height / this.height], { - interpolator: resampleMethod - }); - break; - - case 'lanczos': - // https://github.com/python-pillow/Pillow/discussions/5519 - // https://github.com/lovell/sharp/blob/main/docs/api-resize.md - img = img.resize({ - width, height, - fit: 'fill', - kernel: 'lanczos3', // PIL Lanczos uses a kernel size of 3 - }); - break; - - default: - throw new Error(`Resampling method ${resampleMethod} is not supported.`); - } +// src/models/ijepa/modeling_ijepa.js +var IJepaPreTrainedModel = class extends PreTrainedModel { +}; +var IJepaModel = class extends IJepaPreTrainedModel { +}; +var IJepaForImageClassification = class extends IJepaPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - return await loadImageFunction(img); - } +// src/models/jais/modeling_jais.js +var JAISPreTrainedModel = class extends PreTrainedModel { +}; +var JAISModel = class extends JAISPreTrainedModel { +}; +var JAISLMHeadModel = class extends JAISPreTrainedModel { +}; +// src/models/jina_clip/modeling_jina_clip.js +var JinaCLIPPreTrainedModel = class extends PreTrainedModel { +}; +var JinaCLIPModel = class extends JinaCLIPPreTrainedModel { + async forward(model_inputs) { + const missing_text_inputs = !model_inputs.input_ids; + const missing_image_inputs = !model_inputs.pixel_values; + if (missing_text_inputs && missing_image_inputs) { + throw new Error("Either `input_ids` or `pixel_values` should be provided."); + } + if (missing_text_inputs) { + model_inputs.input_ids = ones([model_inputs.pixel_values.dims[0], 1]); + } + if (missing_image_inputs) { + const { image_size } = this.config.vision_config; + model_inputs.pixel_values = full([0, 3, image_size, image_size], 0); + } + const { text_embeddings, image_embeddings, l2norm_text_embeddings, l2norm_image_embeddings } = await super.forward(model_inputs); + const result = {}; + if (!missing_text_inputs) { + result.text_embeddings = text_embeddings; + result.l2norm_text_embeddings = l2norm_text_embeddings; + } + if (!missing_image_inputs) { + result.image_embeddings = image_embeddings; + result.l2norm_image_embeddings = l2norm_image_embeddings; } + return result; + } +}; +var JinaCLIPTextModel = class extends JinaCLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } +}; +var JinaCLIPVisionModel = class extends JinaCLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } +}; - async pad([left, right, top, bottom]) { - left = Math.max(left, 0); - right = Math.max(right, 0); - top = Math.max(top, 0); - bottom = Math.max(bottom, 0); - - if (left === 0 && right === 0 && top === 0 && bottom === 0) { - // No padding needed - return this; - } +// src/models/lfm2/modeling_lfm2.js +var Lfm2PreTrainedModel = class extends PreTrainedModel { +}; +var Lfm2Model = class extends Lfm2PreTrainedModel { +}; +var Lfm2ForCausalLM = class extends Lfm2PreTrainedModel { +}; - if (IS_BROWSER_OR_WEBWORKER) { - // Store number of channels before padding - const numChannels = this.channels; +// src/models/lighton_ocr/modeling_lighton_ocr.js +var LightOnOcrForConditionalGeneration = class extends LlavaForConditionalGeneration { +}; - // Create canvas object for this image - const canvas = this.toCanvas(); +// src/models/lfm2_moe/modeling_lfm2_moe.js +var Lfm2MoePreTrainedModel = class extends PreTrainedModel { +}; +var Lfm2MoeModel = class extends Lfm2MoePreTrainedModel { +}; +var Lfm2MoeForCausalLM = class extends Lfm2MoePreTrainedModel { +}; - const newWidth = this.width + left + right; - const newHeight = this.height + top + bottom; +// src/models/lfm2_vl/modeling_lfm2_vl.js +var Lfm2VlForConditionalGeneration = class extends LlavaForConditionalGeneration { + forward_params = [ + "input_ids", + "attention_mask", + "pixel_values", + "pixel_attention_mask", + "spatial_shapes", + "position_ids", + "past_key_values" + ]; +}; - // Create a new canvas of the desired size. - const ctx = createCanvasFunction(newWidth, newHeight).getContext('2d'); +// src/models/lfm3/modeling_lfm3.js +var Lfm3PreTrainedModel = class extends PreTrainedModel { +}; +var Lfm3Model = class extends Lfm3PreTrainedModel { +}; +var Lfm3ForCausalLM = class extends Lfm3PreTrainedModel { +}; - // Draw image to context, padding in the process - ctx.drawImage(canvas, - 0, 0, this.width, this.height, - left, top, this.width, this.height - ); +// src/models/lfm3_vl/modeling_lfm3_vl.js +var Lfm3VlForConditionalGeneration = class extends LlavaForConditionalGeneration { + forward_params = [ + "input_ids", + "attention_mask", + "pixel_values", + "image_grid_thw", + "position_ids", + "past_key_values" + ]; +}; - // Create image from the padded data - const paddedImage = new RawImage( - ctx.getImageData(0, 0, newWidth, newHeight).data, - newWidth, newHeight, 4 - ); +// src/models/llama/modeling_llama.js +var LlamaPreTrainedModel = class extends PreTrainedModel { +}; +var LlamaModel = class extends LlamaPreTrainedModel { +}; +var LlamaForCausalLM = class extends LlamaPreTrainedModel { +}; - // Convert back so that image has the same number of channels as before - return paddedImage.convert(numChannels); +// src/models/llama4/modeling_llama4.js +var Llama4PreTrainedModel = class extends PreTrainedModel { +}; +var Llama4ForCausalLM = class extends Llama4PreTrainedModel { +}; - } else { - const img = this.toSharp().extend({ left, right, top, bottom }); - return await loadImageFunction(img); - } - } +// src/models/longt5/modeling_longt5.js +var LongT5PreTrainedModel = class extends PreTrainedModel { +}; +var LongT5Model = class extends LongT5PreTrainedModel { +}; +var LongT5ForConditionalGeneration = class extends LongT5PreTrainedModel { +}; - async crop([x_min, y_min, x_max, y_max]) { - // Ensure crop bounds are within the image - x_min = Math.max(x_min, 0); - y_min = Math.max(y_min, 0); - x_max = Math.min(x_max, this.width - 1); - y_max = Math.min(y_max, this.height - 1); +// src/models/m2m_100/modeling_m2m_100.js +var M2M100PreTrainedModel = class extends PreTrainedModel { +}; +var M2M100Model = class extends M2M100PreTrainedModel { +}; +var M2M100ForConditionalGeneration = class extends M2M100PreTrainedModel { +}; - // Do nothing if the crop is the entire image - if (x_min === 0 && y_min === 0 && x_max === this.width - 1 && y_max === this.height - 1) { - return this; - } +// src/models/marian/modeling_marian.js +var MarianPreTrainedModel = class extends PreTrainedModel { +}; +var MarianModel = class extends MarianPreTrainedModel { +}; +var MarianMTModel = class extends MarianPreTrainedModel { +}; - const crop_width = x_max - x_min + 1; - const crop_height = y_max - y_min + 1; +// src/models/maskformer/modeling_maskformer.js +var MaskFormerPreTrainedModel = class extends PreTrainedModel { +}; +var MaskFormerModel = class extends MaskFormerPreTrainedModel { +}; +var MaskFormerForInstanceSegmentation = class extends MaskFormerPreTrainedModel { +}; - if (IS_BROWSER_OR_WEBWORKER) { - // Store number of channels before resizing - const numChannels = this.channels; +// src/models/mbart/modeling_mbart.js +var MBartPreTrainedModel = class extends PreTrainedModel { +}; +var MBartModel = class extends MBartPreTrainedModel { +}; +var MBartForConditionalGeneration = class extends MBartPreTrainedModel { +}; +var MBartForSequenceClassification = class extends MBartPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MBartForCausalLM = class extends MBartPreTrainedModel { +}; - // Create canvas object for this image - const canvas = this.toCanvas(); +// src/models/metric3d/modeling_metric3d.js +var Metric3DPreTrainedModel = class extends PreTrainedModel { +}; +var Metric3DForDepthEstimation = class extends Metric3DPreTrainedModel { +}; - // Create a new canvas of the desired size. This is needed since if the - // image is too small, we need to pad it with black pixels. - const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d'); +// src/models/metric3dv2/modeling_metric3dv2.js +var Metric3Dv2PreTrainedModel = class extends PreTrainedModel { +}; +var Metric3Dv2ForDepthEstimation = class extends Metric3Dv2PreTrainedModel { +}; - // Draw image to context, cropping in the process - ctx.drawImage(canvas, - x_min, y_min, crop_width, crop_height, - 0, 0, crop_width, crop_height - ); +// src/models/mgp_str/modeling_mgp_str.js +var MgpstrModelOutput = class extends ModelOutput { + constructor({ char_logits, bpe_logits, wp_logits }) { + super(); + this.char_logits = char_logits; + this.bpe_logits = bpe_logits; + this.wp_logits = wp_logits; + } + get logits() { + return [this.char_logits, this.bpe_logits, this.wp_logits]; + } +}; +var MgpstrPreTrainedModel = class extends PreTrainedModel { +}; +var MgpstrForSceneTextRecognition = class extends MgpstrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new MgpstrModelOutput(await super._call(model_inputs)); + } +}; - // Create image from the resized data - const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); +// src/models/mimi/modeling_mimi.js +var MimiEncoderOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_codes Discrete code embeddings, of shape `(batch_size, num_quantizers, codes_length)`. + */ + constructor({ audio_codes }) { + super(); + this.audio_codes = audio_codes; + } +}; +var MimiDecoderOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.audio_values Decoded audio values, of shape `(batch_size, num_channels, sequence_length)`. + */ + constructor({ audio_values }) { + super(); + this.audio_values = audio_values; + } +}; +var MimiPreTrainedModel = class extends PreTrainedModel { + main_input_name = "input_values"; + forward_params = ["input_values"]; +}; +var MimiModel = class extends MimiPreTrainedModel { + /** + * Encodes the input audio waveform into discrete codes. + * @param {Object} inputs Model inputs + * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). + * @returns {Promise} The output tensor of shape `(batch_size, num_codebooks, sequence_length)`. + */ + async encode(inputs) { + return new MimiEncoderOutput(await sessionRun(this.sessions["encoder_model"], inputs)); + } + /** + * Decodes the given frames into an output audio waveform. + * @param {MimiEncoderOutput} inputs The encoded audio codes. + * @returns {Promise} The output tensor of shape `(batch_size, num_channels, sequence_length)`. + */ + async decode(inputs) { + return new MimiDecoderOutput(await sessionRun(this.sessions["decoder_model"], inputs)); + } +}; +var MimiEncoderModel = class extends MimiPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "encoder_model" + }); + } +}; +var MimiDecoderModel = class extends MimiPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "decoder_model" + }); + } +}; - // Convert back so that image has the same number of channels as before - return resizedImage.convert(numChannels); +// src/models/ministral/modeling_ministral.js +var MinistralPreTrainedModel = class extends PreTrainedModel { +}; +var MinistralModel = class extends MinistralPreTrainedModel { +}; +var MinistralForCausalLM = class extends MinistralPreTrainedModel { +}; - } else { - // Create sharp image from raw data - const img = this.toSharp().extract({ - left: x_min, - top: y_min, - width: crop_width, - height: crop_height, - }); +// src/models/ministral3/modeling_ministral3.js +var Ministral3PreTrainedModel = class extends PreTrainedModel { +}; +var Ministral3Model = class extends Ministral3PreTrainedModel { +}; +var Ministral3ForCausalLM = class extends Ministral3PreTrainedModel { +}; - return await loadImageFunction(img); - } +// src/models/mistral/modeling_mistral.js +var MistralPreTrainedModel = class extends PreTrainedModel { +}; +var MistralModel = class extends MistralPreTrainedModel { +}; +var MistralForCausalLM = class extends MistralPreTrainedModel { +}; - } +// src/models/mistral3/modeling_mistral3.js +var Mistral3ForConditionalGeneration = class extends LlavaForConditionalGeneration { +}; - async center_crop(crop_width, crop_height) { - // If the image is already the desired size, return it - if (this.width === crop_width && this.height === crop_height) { - return this; - } +// src/models/mistral4/modeling_mistral4.js +var Mistral4PreTrainedModel = class extends PreTrainedModel { +}; +var Mistral4Model = class extends Mistral4PreTrainedModel { +}; +var Mistral4ForCausalLM = class extends Mistral4PreTrainedModel { +}; - // Determine bounds of the image in the new canvas - const width_offset = (this.width - crop_width) / 2; - const height_offset = (this.height - crop_height) / 2; +// src/models/mobilebert/modeling_mobilebert.js +var MobileBertPreTrainedModel = class extends PreTrainedModel { +}; +var MobileBertModel = class extends MobileBertPreTrainedModel { +}; +var MobileBertForMaskedLM = class extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var MobileBertForSequenceClassification = class extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MobileBertForQuestionAnswering = class extends MobileBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; +// src/models/mobilellm/modeling_mobilellm.js +var MobileLLMPreTrainedModel = class extends PreTrainedModel { +}; +var MobileLLMModel = class extends MobileLLMPreTrainedModel { +}; +var MobileLLMForCausalLM = class extends MobileLLMPreTrainedModel { +}; - if (IS_BROWSER_OR_WEBWORKER) { - // Store number of channels before resizing - const numChannels = this.channels; +// src/models/mobilenet_v1/modeling_mobilenet_v1.js +var MobileNetV1PreTrainedModel = class extends PreTrainedModel { +}; +var MobileNetV1Model = class extends MobileNetV1PreTrainedModel { +}; +var MobileNetV1ForImageClassification = class extends MobileNetV1PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MobileNetV1ForSemanticSegmentation = class extends MobileNetV1PreTrainedModel { +}; - // Create canvas object for this image - const canvas = this.toCanvas(); +// src/models/mobilenet_v2/modeling_mobilenet_v2.js +var MobileNetV2PreTrainedModel = class extends PreTrainedModel { +}; +var MobileNetV2Model = class extends MobileNetV2PreTrainedModel { +}; +var MobileNetV2ForImageClassification = class extends MobileNetV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MobileNetV2ForSemanticSegmentation = class extends MobileNetV2PreTrainedModel { +}; - // Create a new canvas of the desired size. This is needed since if the - // image is too small, we need to pad it with black pixels. - const ctx = createCanvasFunction(crop_width, crop_height).getContext('2d'); +// src/models/mobilenet_v3/modeling_mobilenet_v3.js +var MobileNetV3PreTrainedModel = class extends PreTrainedModel { +}; +var MobileNetV3Model = class extends MobileNetV3PreTrainedModel { +}; +var MobileNetV3ForImageClassification = class extends MobileNetV3PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MobileNetV3ForSemanticSegmentation = class extends MobileNetV3PreTrainedModel { +}; - let sourceX = 0; - let sourceY = 0; - let destX = 0; - let destY = 0; +// src/models/mobilenet_v4/modeling_mobilenet_v4.js +var MobileNetV4PreTrainedModel = class extends PreTrainedModel { +}; +var MobileNetV4Model = class extends MobileNetV4PreTrainedModel { +}; +var MobileNetV4ForImageClassification = class extends MobileNetV4PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MobileNetV4ForSemanticSegmentation = class extends MobileNetV4PreTrainedModel { +}; - if (width_offset >= 0) { - sourceX = width_offset; - } else { - destX = -width_offset; - } +// src/models/mobilevit/modeling_mobilevit.js +var MobileViTPreTrainedModel = class extends PreTrainedModel { +}; +var MobileViTModel = class extends MobileViTPreTrainedModel { +}; +var MobileViTForImageClassification = class extends MobileViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - if (height_offset >= 0) { - sourceY = height_offset; - } else { - destY = -height_offset; - } +// src/models/mobilevitv2/modeling_mobilevitv2.js +var MobileViTV2PreTrainedModel = class extends PreTrainedModel { +}; +var MobileViTV2Model = class extends MobileViTV2PreTrainedModel { +}; +var MobileViTV2ForImageClassification = class extends MobileViTV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - // Draw image to context, cropping in the process - ctx.drawImage(canvas, - sourceX, sourceY, crop_width, crop_height, - destX, destY, crop_width, crop_height - ); +// src/models/modernbert/modeling_modernbert.js +var ModernBertPreTrainedModel = class extends PreTrainedModel { +}; +var ModernBertModel = class extends ModernBertPreTrainedModel { +}; +var ModernBertForMaskedLM = class extends ModernBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var ModernBertForSequenceClassification = class extends ModernBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var ModernBertForTokenClassification = class extends ModernBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; - // Create image from the resized data - const resizedImage = new RawImage(ctx.getImageData(0, 0, crop_width, crop_height).data, crop_width, crop_height, 4); +// src/models/modernbert_decoder/modeling_modernbert_decoder.js +var ModernBertDecoderPreTrainedModel = class extends PreTrainedModel { +}; +var ModernBertDecoderModel = class extends ModernBertDecoderPreTrainedModel { +}; +var ModernBertDecoderForCausalLM = class extends ModernBertDecoderPreTrainedModel { +}; - // Convert back so that image has the same number of channels as before - return resizedImage.convert(numChannels); +// src/models/moonshine/modeling_moonshine.js +var MoonshinePreTrainedModel = class extends PreTrainedModel { + requires_attention_mask = false; + main_input_name = "input_values"; + forward_params = ["input_values", "decoder_input_ids", "past_key_values"]; +}; +var MoonshineModel = class extends MoonshinePreTrainedModel { +}; +var MoonshineForConditionalGeneration = class extends MoonshinePreTrainedModel { +}; - } else { - // Create sharp image from raw data - let img = this.toSharp(); - - if (width_offset >= 0 && height_offset >= 0) { - // Cropped image lies entirely within the original image - img = img.extract({ - left: Math.floor(width_offset), - top: Math.floor(height_offset), - width: crop_width, - height: crop_height, - }) - } else if (width_offset <= 0 && height_offset <= 0) { - // Cropped image lies entirely outside the original image, - // so we add padding - const top = Math.floor(-height_offset); - const left = Math.floor(-width_offset); - img = img.extend({ - top: top, - left: left, - - // Ensures the resulting image has the desired dimensions - right: crop_width - this.width - left, - bottom: crop_height - this.height - top, - }); - } else { - // Cropped image lies partially outside the original image. - // We first pad, then crop. - - let y_padding = [0, 0]; - let y_extract = 0; - if (height_offset < 0) { - y_padding[0] = Math.floor(-height_offset); - y_padding[1] = crop_height - this.height - y_padding[0]; - } else { - y_extract = Math.floor(height_offset); - } +// src/models/mpnet/modeling_mpnet.js +var MPNetPreTrainedModel = class extends PreTrainedModel { +}; +var MPNetModel = class extends MPNetPreTrainedModel { +}; +var MPNetForMaskedLM = class extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var MPNetForSequenceClassification = class extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var MPNetForTokenClassification = class extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var MPNetForQuestionAnswering = class extends MPNetPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - let x_padding = [0, 0]; - let x_extract = 0; - if (width_offset < 0) { - x_padding[0] = Math.floor(-width_offset); - x_padding[1] = crop_width - this.width - x_padding[0]; - } else { - x_extract = Math.floor(width_offset); - } +// src/models/mpt/modeling_mpt.js +var MptPreTrainedModel = class extends PreTrainedModel { +}; +var MptModel = class extends MptPreTrainedModel { +}; +var MptForCausalLM = class extends MptPreTrainedModel { +}; - img = img.extend({ - top: y_padding[0], - bottom: y_padding[1], - left: x_padding[0], - right: x_padding[1], - }).extract({ - left: x_extract, - top: y_extract, - width: crop_width, - height: crop_height, - }) - } +// src/models/mt5/modeling_mt5.js +var MT5PreTrainedModel = class extends PreTrainedModel { +}; +var MT5Model = class extends MT5PreTrainedModel { +}; +var MT5ForConditionalGeneration = class extends MT5PreTrainedModel { +}; - return await loadImageFunction(img); - } +// src/models/multi_modality/modeling_multi_modality.js +var MultiModalityPreTrainedModel = class extends PreTrainedModel { +}; +var MultiModalityCausalLM = class extends MultiModalityPreTrainedModel { + forward_params = [ + // prepare_inputs_embeds + "input_ids", + "pixel_values", + "images_seq_mask", + "images_emb_mask", + // language_model + "attention_mask", + "position_ids", + "past_key_values" + ]; + /** + * @param {ConstructorParameters} args + */ + constructor(...args) { + super(...args); + this._generation_mode = "text"; + } + async forward(model_inputs) { + const mode = this._generation_mode ?? "text"; + let output_1; + if (mode === "text" || !model_inputs.past_key_values) { + const session = this.sessions["prepare_inputs_embeds"]; + const prep_inputs = pick(model_inputs, session.inputNames); + output_1 = await sessionRun(session, prep_inputs); + } else { + const session = this.sessions["gen_img_embeds"]; + const prep_inputs = pick( + { + image_ids: model_inputs.input_ids + }, + session.inputNames + ); + output_1 = await sessionRun(session, prep_inputs); } - - async toBlob(type = 'image/png', quality = 1) { - if (!IS_BROWSER_OR_WEBWORKER) { - throw new Error('toBlob() is only supported in browser environments.') - } - - const canvas = this.toCanvas(); - return await canvas.convertToBlob({ type, quality }); + const input_2 = { ...model_inputs, ...output_1 }; + const output_2 = await decoder_forward(this, input_2); + const head = this.sessions[mode === "text" ? "lm_head" : "gen_head"]; + if (!head) { + throw new Error(`Unable to find "${head}" generation head`); } - - toTensor(channel_format = 'CHW') { - let tensor = new _tensor_js__WEBPACK_IMPORTED_MODULE_3__.Tensor( - 'uint8', - new Uint8Array(this.data), - [this.height, this.width, this.channels] + const output_3 = await sessionRun(head, pick(output_2, head.inputNames)); + return { + ...output_1, + ...output_2, + ...output_3 + }; + } + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + const has_past_key_values = !!model_inputs.past_key_values; + setNumLogitsToKeep(this, model_inputs, 1n); + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + if (has_past_key_values) { + model_inputs.input_ids = cat([model_inputs.input_ids, model_inputs.input_ids], 0); + } else { + model_inputs.input_ids = cat( + [model_inputs.input_ids, full_like(model_inputs.input_ids, BigInt(generation_config.pad_token_id))], + 0 ); - - if (channel_format === 'HWC') { - // Do nothing - } else if (channel_format === 'CHW') { // hwc -> chw - tensor = tensor.permute(2, 0, 1); - } else { - throw new Error(`Unsupported channel format: ${channel_format}`); - } - return tensor; - } - - toCanvas() { - if (!IS_BROWSER_OR_WEBWORKER) { - throw new Error('toCanvas() is only supported in browser environments.') - } - - // Clone, and convert data to RGBA before drawing to canvas. - // This is because the canvas API only supports RGBA - const cloned = this.clone().rgba(); - - // Create canvas object for the cloned image - const clonedCanvas = createCanvasFunction(cloned.width, cloned.height); - - // Draw image to context - const data = new ImageDataClass(cloned.data, cloned.width, cloned.height); - clonedCanvas.getContext('2d').putImageData(data, 0, 0); - - return clonedCanvas; - } - - /** - * Split this image into individual bands. This method returns an array of individual image bands from an image. - * For example, splitting an "RGB" image creates three new images each containing a copy of one of the original bands (red, green, blue). - * - * Inspired by PIL's `Image.split()` [function](https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.split). - * @returns {RawImage[]} An array containing bands. - */ - split() { - const { data, width, height, channels } = this; - - /** @type {typeof Uint8Array | typeof Uint8ClampedArray} */ - const data_type = /** @type {any} */(data.constructor); - const per_channel_length = data.length / channels; - - // Pre-allocate buffers for each channel - const split_data = Array.from( - { length: channels }, - () => new data_type(per_channel_length), + model_inputs.attention_mask = cat( + [model_inputs.attention_mask, full_like(model_inputs.attention_mask, 0n)], + 0 ); - - // Write pixel data - for (let i = 0; i < per_channel_length; ++i) { - const data_offset = channels * i; - for (let j = 0; j < channels; ++j) { - split_data[j][i] = data[data_offset + j]; - } - } - return split_data.map((data) => new RawImage(data, width, height, 1)); - } - - /** - * Helper method to update the image data. - * @param {Uint8ClampedArray} data The new image data. - * @param {number} width The new width of the image. - * @param {number} height The new height of the image. - * @param {1|2|3|4|null} [channels] The new number of channels of the image. - * @private - */ - _update(data, width, height, channels = null) { - this.data = data; - this.width = width; - this.height = height; - if (channels !== null) { - this.channels = channels; - } - return this; + } } - - /** - * Clone the image - * @returns {RawImage} The cloned image - */ - clone() { - return new RawImage(this.data.slice(), this.width, this.height, this.channels); + if (has_past_key_values || !model_inputs.pixel_values) { + model_inputs.pixel_values = full([0, 0, 3, 384, 384], 1); } - - /** - * Helper method for converting image to have a certain number of channels - * @param {number} numChannels The number of channels. Must be 1, 3, or 4. - * @returns {RawImage} `this` to support chaining. - */ - convert(numChannels) { - if (this.channels === numChannels) return this; // Already correct number of channels - - switch (numChannels) { - 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; + if (has_past_key_values) { + const num_img_tokens = 0; + const num_text_tokens = 1; + const has_image = num_img_tokens > 0 ? 1 : 0; + const batch_size = 1; + model_inputs.images_seq_mask = new Tensor3( + "bool", + new Array(num_img_tokens + num_text_tokens).fill(true).fill(false, 0, num_text_tokens), + [batch_size, num_img_tokens + num_text_tokens] + ); + model_inputs.images_emb_mask = new Tensor3("bool", new Array(num_img_tokens).fill(!!has_image), [ + batch_size, + 1, + num_img_tokens + ]); } - - /** - * Save the image to the given path. - * @param {string} path The path to save the image to. - */ - async save(path) { - - if (IS_BROWSER_OR_WEBWORKER) { - if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) { - throw new Error('Unable to save an image from a Web Worker.') - } - - const extension = path.split('.').pop().toLowerCase(); - const mime = CONTENT_TYPE_MAP.get(extension) ?? 'image/png'; - - // Convert image to Blob - const blob = await this.toBlob(mime); - - (0,_core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path, blob) - - } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) { - throw new Error('Unable to save the image because filesystem is disabled in this environment.') - - } else { - const img = this.toSharp(); - return await img.toFile(path); - } + return model_inputs; + } + /** + * @param {import('../../generation/parameters.js').GenerationFunctionParameters} options + */ + async generate(options) { + this._generation_mode = "text"; + return super.generate(options); + } + /** + * @param {import('../../generation/parameters.js').GenerationFunctionParameters} options + */ + async generate_images(options) { + this._generation_mode = "image"; + const start_num_tokens = ( + /** @type {Tensor} */ + (options.inputs ?? options[this.main_input_name]).dims[1] + ); + const all_tokens = await super.generate(options); + const generated_tokens = ( + /** @type {Tensor} */ + all_tokens.slice(null, [start_num_tokens, null]) + ); + const image_decode = this.sessions["image_decode"]; + const { decoded_image } = await sessionRun(image_decode, { + generated_tokens + }); + const clamped = decoded_image.add_(1).mul_(255 / 2).clamp_(0, 255).to("uint8"); + const images = []; + for (const tensor of clamped) { + const img = RawImage.fromTensor(tensor); + images.push(img); } + return images; + } +}; - toSharp() { - if (IS_BROWSER_OR_WEBWORKER) { - throw new Error('toSharp() is only supported in server-side environments.') - } - - return sharp__WEBPACK_IMPORTED_MODULE_4__(this.data, { - raw: { - width: this.width, - height: this.height, - channels: this.channels - } - }); +// src/models/musicgen/modeling_musicgen.js +var MusicgenPreTrainedModel = class extends PreTrainedModel { +}; +var MusicgenModel = class extends MusicgenPreTrainedModel { +}; +var MusicgenForCausalLM = class extends MusicgenPreTrainedModel { +}; +var MusicgenForConditionalGeneration = class extends PreTrainedModel { + // NOTE: not MusicgenPreTrainedModel + forward_params = [ + "input_ids", + "attention_mask", + "encoder_outputs", + "decoder_input_ids", + "decoder_attention_mask", + "past_key_values" + ]; + /** + * Apply the pattern mask to the final ids, + * then revert the pattern delay mask by filtering the pad token id in a single step. + * @param {Tensor} outputs The output tensor from the model. + * @returns {Tensor} The filtered output tensor. + */ + _apply_and_filter_by_delay_pattern_mask(outputs) { + const [bs_x_codebooks, seqLength] = outputs.dims; + const num_codebooks = this.config.decoder.num_codebooks; + const upperBound = seqLength - num_codebooks; + let newDataSize = 0; + for (let i = 0; i < outputs.size; ++i) { + if (outputs.data[i] == this.config.decoder.pad_token_id) { + continue; + } + const row = i % seqLength; + const col = Math.floor(i / seqLength) % num_codebooks; + const diff = row - col; + if (diff > 0 && diff <= upperBound) { + outputs.data[newDataSize++] = outputs.data[i]; + } } -} - -/** - * Helper function to load an image from a URL, path, etc. - */ -const load_image = RawImage.read.bind(RawImage); - - - -/***/ }), - -/***/ "./src/utils/maths.js": -/*!****************************!*\ - !*** ./src/utils/maths.js ***! - \****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ FFT: () => (/* binding */ FFT), -/* harmony export */ bankers_round: () => (/* binding */ bankers_round), -/* harmony export */ cos_sim: () => (/* binding */ cos_sim), -/* harmony export */ dot: () => (/* binding */ dot), -/* harmony export */ dynamic_time_warping: () => (/* binding */ dynamic_time_warping), -/* harmony export */ interpolate_data: () => (/* binding */ interpolate_data), -/* harmony export */ log_softmax: () => (/* binding */ log_softmax), -/* harmony export */ magnitude: () => (/* binding */ magnitude), -/* harmony export */ max: () => (/* binding */ max), -/* harmony export */ medianFilter: () => (/* binding */ medianFilter), -/* harmony export */ min: () => (/* binding */ min), -/* harmony export */ permute_data: () => (/* binding */ permute_data), -/* harmony export */ round: () => (/* binding */ round), -/* harmony export */ softmax: () => (/* binding */ softmax) -/* harmony export */ }); - -/** - * @file Helper module for mathematical processing. - * - * These functions and classes are only used internally, - * meaning an end-user shouldn't need to access anything here. - * - * @module utils/maths - */ - -/** - * @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float16Array | Float32Array | Float64Array} TypedArray - * @typedef {BigInt64Array | BigUint64Array} BigTypedArray - * @typedef {TypedArray | BigTypedArray} AnyTypedArray - */ - -/** - * @param {TypedArray} input - */ -function interpolate_data(input, [in_channels, in_height, in_width], [out_height, out_width], mode = 'bilinear', align_corners = false) { - // TODO use mode and align_corners - - // Output image dimensions - const x_scale = out_width / in_width; - const y_scale = out_height / in_height; - - // Output image - // @ts-ignore - const out_img = new input.constructor(out_height * out_width * in_channels); - - // Pre-calculate strides - const inStride = in_height * in_width; - const outStride = out_height * out_width; - - for (let i = 0; i < out_height; ++i) { - for (let j = 0; j < out_width; ++j) { - // Calculate output offset - const outOffset = i * out_width + j; - - // Calculate input pixel coordinates - const x = (j + 0.5) / x_scale - 0.5; - const y = (i + 0.5) / y_scale - 0.5; - - // Calculate the four nearest input pixels - // We also check if the input pixel coordinates are within the image bounds - let x1 = Math.floor(x); - let y1 = Math.floor(y); - const x2 = Math.min(x1 + 1, in_width - 1); - const y2 = Math.min(y1 + 1, in_height - 1); - - x1 = Math.max(x1, 0); - y1 = Math.max(y1, 0); - - - // Calculate the fractional distances between the input pixel and the four nearest pixels - const s = x - x1; - const t = y - y1; - - // Perform bilinear interpolation - const w1 = (1 - s) * (1 - t); - const w2 = s * (1 - t); - const w3 = (1 - s) * t; - const w4 = s * t; - - // Calculate the four nearest input pixel indices - const yStride = y1 * in_width; - const xStride = y2 * in_width; - const idx1 = yStride + x1; - const idx2 = yStride + x2; - const idx3 = xStride + x1; - const idx4 = xStride + x2; - - for (let k = 0; k < in_channels; ++k) { - // Calculate channel offset - const cOffset = k * inStride; - - out_img[k * outStride + outOffset] = - w1 * input[cOffset + idx1] + - w2 * input[cOffset + idx2] + - w3 * input[cOffset + idx3] + - w4 * input[cOffset + idx4]; - } + const batch_size = Math.floor(bs_x_codebooks / num_codebooks); + const inferred = newDataSize / (batch_size * num_codebooks); + return new Tensor3(outputs.type, outputs.data.slice(0, newDataSize), [batch_size, num_codebooks, inferred]); + } + prepare_inputs_for_generation(input_ids, model_inputs, generation_config) { + const pad_token_id = BigInt(this.config.decoder.pad_token_id); + let clonedInputIds = structuredClone(input_ids); + for (let i = 0; i < clonedInputIds.length; ++i) { + for (let j2 = 0; j2 < clonedInputIds[i].length; ++j2) { + if (i % this.config.decoder.num_codebooks >= j2) { + clonedInputIds[i][j2] = pad_token_id; } + } + } + if (generation_config.guidance_scale !== null && generation_config.guidance_scale > 1) { + clonedInputIds = clonedInputIds.concat(clonedInputIds); } + return encoder_decoder_prepare_inputs_for_generation(this, clonedInputIds, model_inputs, generation_config); + } + /** + * Generates sequences of token ids for models with a language modeling head. + * @param {import('../../generation/parameters.js').GenerationFunctionParameters} options + * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. + */ + async generate(options) { + const output_ids = await super.generate(options); + const audio_codes = this._apply_and_filter_by_delay_pattern_mask( + /** @type {Tensor} */ + output_ids + ).unsqueeze_( + 0 + ); + const { audio_values } = await sessionRun(this.sessions["encodec_decode"], { audio_codes }); + return audio_values; + } +}; - return out_img; -} +// src/models/nanochat/modeling_nanochat.js +var NanoChatPreTrainedModel = class extends PreTrainedModel { +}; +var NanoChatModel = class extends NanoChatPreTrainedModel { +}; +var NanoChatForCausalLM = class extends NanoChatPreTrainedModel { +}; +// src/models/nemotron_h/modeling_nemotron_h.js +var NemotronHPreTrainedModel = class extends PreTrainedModel { +}; +var NemotronHModel = class extends NemotronHPreTrainedModel { +}; +var NemotronHForCausalLM = class extends NemotronHPreTrainedModel { +}; -/** - * Helper method to permute a `AnyTypedArray` directly - * @template {AnyTypedArray} T - * @param {T} array - * @param {number[]} dims - * @param {number[]} axes - * @returns {[T, number[]]} The permuted array and the new shape. - */ -function permute_data(array, dims, axes) { - // Calculate the new shape of the permuted array - // and the stride of the original array - const shape = new Array(axes.length); - const stride = new Array(axes.length); +// src/models/neobert/modeling_neobert.js +var NeoBertPreTrainedModel = class extends PreTrainedModel { +}; +var NeoBertModel = class extends NeoBertPreTrainedModel { +}; +var NeoBertForMaskedLM = class extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var NeoBertForSequenceClassification = class extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var NeoBertForTokenClassification = class extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var NeoBertForQuestionAnswering = class extends NeoBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - for (let i = axes.length - 1, s = 1; i >= 0; --i) { - stride[i] = s; - shape[i] = dims[axes[i]]; - s *= shape[i]; - } +// src/models/nomic_bert/modeling_nomic_bert.js +var NomicBertPreTrainedModel = class extends PreTrainedModel { +}; +var NomicBertModel = class extends NomicBertPreTrainedModel { +}; - // Precompute inverse mapping of stride - const invStride = axes.map((_, i) => stride[axes.indexOf(i)]); +// src/models/olmo/modeling_olmo.js +var OlmoPreTrainedModel = class extends PreTrainedModel { +}; +var OlmoModel = class extends OlmoPreTrainedModel { +}; +var OlmoForCausalLM = class extends OlmoPreTrainedModel { +}; - // Create the permuted array with the new shape - // @ts-ignore - const permutedData = new array.constructor(array.length); +// src/models/olmo2/modeling_olmo2.js +var Olmo2PreTrainedModel = class extends PreTrainedModel { +}; +var Olmo2Model = class extends Olmo2PreTrainedModel { +}; +var Olmo2ForCausalLM = class extends Olmo2PreTrainedModel { +}; - // Permute the original array to the new array - for (let i = 0; i < array.length; ++i) { - let newIndex = 0; - for (let j = dims.length - 1, k = i; j >= 0; --j) { - newIndex += (k % dims[j]) * invStride[j]; - k = Math.floor(k / dims[j]); - } - permutedData[newIndex] = array[i]; - } +// src/models/olmo3/modeling_olmo3.js +var Olmo3PreTrainedModel = class extends PreTrainedModel { +}; +var Olmo3Model = class extends Olmo3PreTrainedModel { +}; +var Olmo3ForCausalLM = class extends Olmo3PreTrainedModel { +}; - return [permutedData, shape]; -} +// src/models/olmo_hybrid/modeling_olmo_hybrid.js +var OlmoHybridPreTrainedModel = class extends PreTrainedModel { +}; +var OlmoHybridModel = class extends OlmoHybridPreTrainedModel { +}; +var OlmoHybridForCausalLM = class extends OlmoHybridPreTrainedModel { +}; +// src/models/openai_privacy_filter/modeling_openai_privacy_filter.js +var OpenAIPrivacyFilterPreTrainedModel = class extends PreTrainedModel { +}; +var OpenAIPrivacyFilterModel = class extends OpenAIPrivacyFilterPreTrainedModel { +}; +var OpenAIPrivacyFilterForTokenClassification = class extends OpenAIPrivacyFilterPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; -/** - * Compute the softmax of an array of numbers. - * @template {TypedArray|number[]} T - * @param {T} arr The array of numbers to compute the softmax of. - * @returns {T} The softmax array. - */ -function softmax(arr) { - // Compute the maximum value in the array - const maxVal = max(arr)[0]; +// src/models/openelm/modeling_openelm.js +var OpenELMPreTrainedModel = class extends PreTrainedModel { +}; +var OpenELMModel = class extends OpenELMPreTrainedModel { +}; +var OpenELMForCausalLM = class extends OpenELMPreTrainedModel { +}; - // Compute the exponentials of the array values - const exps = arr.map(x => Math.exp(x - maxVal)); +// src/models/opt/modeling_opt.js +var OPTPreTrainedModel = class extends PreTrainedModel { +}; +var OPTModel = class extends OPTPreTrainedModel { +}; +var OPTForCausalLM = class extends OPTPreTrainedModel { +}; - // Compute the sum of the exponentials - // @ts-ignore - const sumExps = exps.reduce((acc, val) => acc + val, 0); +// src/models/owlv2/modeling_owlv2.js +var Owlv2PreTrainedModel = class extends PreTrainedModel { +}; +var Owlv2Model = class extends Owlv2PreTrainedModel { +}; +var Owlv2ForObjectDetection = class extends Owlv2PreTrainedModel { +}; - // Compute the softmax values - const softmaxArr = exps.map(x => x / sumExps); +// src/models/owlvit/modeling_owlvit.js +var OwlViTPreTrainedModel = class extends PreTrainedModel { +}; +var OwlViTModel = class extends OwlViTPreTrainedModel { +}; +var OwlViTForObjectDetection = class extends OwlViTPreTrainedModel { +}; - return /** @type {T} */(softmaxArr); -} +// src/models/paligemma/modeling_paligemma.js +var PaliGemmaForConditionalGeneration = class extends LlavaForConditionalGeneration { +}; -/** - * Calculates the logarithm of the softmax function for the input array. - * @template {TypedArray|number[]} T - * @param {T} arr The input array to calculate the log_softmax function for. - * @returns {T} The resulting log_softmax array. - */ -function log_softmax(arr) { - // Compute the maximum value in the array - const maxVal = max(arr)[0]; +// src/models/parakeet/modeling_parakeet.js +var ParakeetPreTrainedModel = class extends PreTrainedModel { +}; +var ParakeetForCTC = class extends ParakeetPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; - // Compute the sum of the exponentials - let sumExps = 0; - for(let i = 0; i < arr.length; ++i) { - sumExps += Math.exp(arr[i] - maxVal); - } +// src/models/patchtsmixer/modeling_patchtsmixer.js +var PatchTSMixerPreTrainedModel = class extends PreTrainedModel { +}; +var PatchTSMixerModel = class extends PatchTSMixerPreTrainedModel { +}; +var PatchTSMixerForPrediction = class extends PatchTSMixerPreTrainedModel { +}; - // Compute the log of the sum - const logSum = Math.log(sumExps); +// src/models/patchtst/modeling_patchtst.js +var PatchTSTPreTrainedModel = class extends PreTrainedModel { +}; +var PatchTSTModel = class extends PatchTSTPreTrainedModel { +}; +var PatchTSTForPrediction = class extends PatchTSTPreTrainedModel { +}; - // Compute the softmax values - const logSoftmaxArr = arr.map(x => x - maxVal - logSum); +// src/models/phi/modeling_phi.js +var PhiPreTrainedModel = class extends PreTrainedModel { +}; +var PhiModel = class extends PhiPreTrainedModel { +}; +var PhiForCausalLM = class extends PhiPreTrainedModel { +}; - return /** @type {T} */(logSoftmaxArr); -} +// src/models/phi3/modeling_phi3.js +var Phi3PreTrainedModel = class extends PreTrainedModel { +}; +var Phi3Model = class extends Phi3PreTrainedModel { +}; +var Phi3ForCausalLM = class extends Phi3PreTrainedModel { +}; -/** - * Calculates the dot product of two arrays. - * @param {number[]} arr1 The first array. - * @param {number[]} arr2 The second array. - * @returns {number} The dot product of arr1 and arr2. - */ -function dot(arr1, arr2) { - let result = 0; - for (let i = 0; i < arr1.length; ++i) { - result += arr1[i] * arr2[i]; +// src/models/phi3_v/modeling_phi3_v.js +var Phi3VPreTrainedModel = class extends PreTrainedModel { + forward_params = [ + "input_ids", + "inputs_embeds", + "attention_mask", + "position_ids", + "pixel_values", + "image_sizes", + "past_key_values" + ]; +}; +var Phi3VForCausalLM = class extends Phi3VPreTrainedModel { + async forward({ + // Produced by the tokenizer/processor: + input_ids = null, + attention_mask = null, + pixel_values = null, + image_sizes = null, + // Used during generation: + position_ids = null, + inputs_embeds = null, + past_key_values = null, + // Generic generation parameters + generation_config = null, + logits_processor = null, + num_logits_to_keep = null, + // TODO: needed? + ...kwargs + }) { + if (!inputs_embeds) { + let image_features; + if (pixel_values && input_ids.dims[1] !== 1) { + if (!image_sizes) { + throw new Error("`image_sizes` must be provided when `pixel_values` is provided."); + } + ({ image_features } = await sessionRun(this.sessions["vision_encoder"], { + pixel_values, + image_sizes + })); + } else { + const hidden_size = this.config.normalized_config.hidden_size; + image_features = new Tensor3("float32", [], [0, hidden_size]); + } + ({ inputs_embeds } = await sessionRun(this.sessions["prepare_inputs_embeds"], { + input_ids, + image_features + })); } - return result; -} + const outputs = await decoder_forward( + this, + { + inputs_embeds, + past_key_values, + attention_mask, + position_ids, + generation_config, + logits_processor, + num_logits_to_keep + }, + false + ); + return outputs; + } +}; -/** - * Computes the cosine similarity between two arrays. - * - * @param {number[]} arr1 The first array. - * @param {number[]} arr2 The second array. - * @returns {number} The cosine similarity between the two arrays. - */ -function cos_sim(arr1, arr2) { - // Calculate dot product of the two arrays - const dotProduct = dot(arr1, arr2); +// src/models/pvt/modeling_pvt.js +var PvtPreTrainedModel = class extends PreTrainedModel { +}; +var PvtModel = class extends PvtPreTrainedModel { +}; +var PvtForImageClassification = class extends PvtPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - // Calculate the magnitude of the first array - const magnitudeA = magnitude(arr1); +// src/models/pyannote/modeling_pyannote.js +var PyAnnotePreTrainedModel = class extends PreTrainedModel { +}; +var PyAnnoteModel = class extends PyAnnotePreTrainedModel { +}; +var PyAnnoteForAudioFrameClassification = class extends PyAnnotePreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; - // Calculate the magnitude of the second array - const magnitudeB = magnitude(arr2); +// src/models/qwen2/modeling_qwen2.js +var Qwen2PreTrainedModel = class extends PreTrainedModel { +}; +var Qwen2Model = class extends Qwen2PreTrainedModel { +}; +var Qwen2ForCausalLM = class extends Qwen2PreTrainedModel { +}; - // Calculate the cosine similarity - const cosineSimilarity = dotProduct / (magnitudeA * magnitudeB); +// src/models/qwen2_moe/modeling_qwen2_moe.js +var Qwen2MoePreTrainedModel = class extends PreTrainedModel { +}; +var Qwen2MoeModel = class extends Qwen2MoePreTrainedModel { +}; +var Qwen2MoeForCausalLM = class extends Qwen2MoePreTrainedModel { +}; - return cosineSimilarity; -} +// src/models/qwen3/modeling_qwen3.js +var Qwen3PreTrainedModel = class extends PreTrainedModel { +}; +var Qwen3Model = class extends Qwen3PreTrainedModel { +}; +var Qwen3ForCausalLM = class extends Qwen3PreTrainedModel { +}; -/** - * Calculates the magnitude of a given array. - * @param {number[]} arr The array to calculate the magnitude of. - * @returns {number} The magnitude of the array. - */ -function magnitude(arr) { - return Math.sqrt(arr.reduce((acc, val) => acc + val * val, 0)); -} +// src/models/qwen3_moe/modeling_qwen3_moe.js +var Qwen3MoePreTrainedModel = class extends PreTrainedModel { +}; +var Qwen3MoeModel = class extends Qwen3MoePreTrainedModel { +}; +var Qwen3MoeForCausalLM = class extends Qwen3MoePreTrainedModel { +}; +// src/models/qwen3_next/modeling_qwen3_next.js +var Qwen3NextPreTrainedModel = class extends PreTrainedModel { +}; +var Qwen3NextModel = class extends Qwen3NextPreTrainedModel { +}; +var Qwen3NextForCausalLM = class extends Qwen3NextPreTrainedModel { +}; -/** - * Returns the value and index of the minimum element in an array. - * @template {number[]|bigint[]|AnyTypedArray} T - * @param {T} arr array of numbers. - * @returns {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} the value and index of the minimum element, of the form: [valueOfMin, indexOfMin] - * @throws {Error} If array is empty. - */ -function min(arr) { - if (arr.length === 0) throw Error('Array must not be empty'); - let min = arr[0]; - let indexOfMin = 0; - for (let i = 1; i < arr.length; ++i) { - if (arr[i] < min) { - min = arr[i]; - indexOfMin = i; - } - } - return /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */([min, indexOfMin]); -} +// src/models/qwen3_vl/modeling_qwen3_vl.js +var Qwen3VLForConditionalGeneration = class extends Qwen2_5_VLForConditionalGeneration { +}; +var Qwen3VLForCausalLM = class extends Qwen2_5_VLForCausalLM { +}; +// src/models/qwen3_vl_moe/modeling_qwen3_vl_moe.js +var Qwen3VLMoeForConditionalGeneration = class extends Qwen3VLForConditionalGeneration { +}; +var Qwen3VLMoeForCausalLM = class extends Qwen3VLForCausalLM { +}; -/** - * Returns the value and index of the maximum element in an array. - * @template {number[]|bigint[]|AnyTypedArray} T - * @param {T} arr array of numbers. - * @returns {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} the value and index of the maximum element, of the form: [valueOfMax, indexOfMax] - * @throws {Error} If array is empty. - */ -function max(arr) { - if (arr.length === 0) throw Error('Array must not be empty'); - let max = arr[0]; - let indexOfMax = 0; - for (let i = 1; i < arr.length; ++i) { - if (arr[i] > max) { - max = arr[i]; - indexOfMax = i; - } - } - return /** @type {T extends bigint[]|BigTypedArray ? [bigint, number] : [number, number]} */([max, indexOfMax]); -} +// src/models/qwen3_5/modeling_qwen3_5.js +var Qwen3_5ForConditionalGeneration = class extends Qwen3VLForConditionalGeneration { +}; +var Qwen3_5ForCausalLM = class extends Qwen3_5ForConditionalGeneration { +}; -function isPowerOfTwo(number) { - // Check if the number is greater than 0 and has only one bit set to 1 - return (number > 0) && ((number & (number - 1)) === 0); -} - -/** - * Implementation of Radix-4 FFT. - * - * P2FFT class provides functionality for performing Fast Fourier Transform on arrays - * which are a power of two in length. - * Code adapted from https://www.npmjs.com/package/fft.js - */ -class P2FFT { - /** - * @param {number} size The size of the input array. Must be a power of two larger than 1. - * @throws {Error} FFT size must be a power of two larger than 1. - */ - constructor(size) { - this.size = size | 0; // convert to a 32-bit signed integer - if (this.size <= 1 || !isPowerOfTwo(this.size)) - throw new Error('FFT size must be a power of two larger than 1'); - - this._csize = size << 1; - - this.table = new Float64Array(this.size * 2); - for (let i = 0; i < this.table.length; i += 2) { - const angle = Math.PI * i / this.size; - this.table[i] = Math.cos(angle); - this.table[i + 1] = -Math.sin(angle); - } - - // Find size's power of two - let power = 0; - for (let t = 1; this.size > t; t <<= 1) - ++power; - - // Calculate initial step's width: - // * If we are full radix-4, it is 2x smaller to give inital len=8 - // * Otherwise it is the same as `power` to give len=4 - this._width = power % 2 === 0 ? power - 1 : power; - - // Pre-compute bit-reversal patterns - this._bitrev = new Int32Array(1 << this._width); - for (let j = 0; j < this._bitrev.length; ++j) { - this._bitrev[j] = 0; - for (let shift = 0; shift < this._width; shift += 2) { - const revShift = this._width - shift - 2; - this._bitrev[j] |= ((j >>> shift) & 3) << revShift; - } - } - } +// src/models/qwen3_5_moe/modeling_qwen3_5_moe.js +var Qwen3_5MoeForConditionalGeneration = class extends Qwen3_5ForConditionalGeneration { +}; +var Qwen3_5MoeForCausalLM = class extends Qwen3_5ForCausalLM { +}; - /** - * Create a complex number array with size `2 * size` - * - * @returns {Float64Array} A complex number array with size `2 * size` - */ - createComplexArray() { - return new Float64Array(this._csize); - } +// src/models/resnet/modeling_resnet.js +var ResNetPreTrainedModel = class extends PreTrainedModel { +}; +var ResNetModel = class extends ResNetPreTrainedModel { +}; +var ResNetForImageClassification = class extends ResNetPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - /** - * Converts a complex number representation stored in a Float64Array to an array of real numbers. - * - * @param {Float64Array} complex The complex number representation to be converted. - * @param {number[]} [storage] An optional array to store the result in. - * @returns {number[]} An array of real numbers representing the input complex number representation. - */ - fromComplexArray(complex, storage) { - const res = storage || new Array(complex.length >>> 1); - for (let i = 0; i < complex.length; i += 2) - res[i >>> 1] = complex[i]; - return res; - } +// src/models/rf_detr/modeling_rf_detr.js +var RFDetrPreTrainedModel = class extends PreTrainedModel { +}; +var RFDetrModel = class extends RFDetrPreTrainedModel { +}; +var RFDetrForObjectDetection = class extends RFDetrPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RFDetrObjectDetectionOutput(await super._call(model_inputs)); + } +}; +var RFDetrObjectDetectionOutput = class extends RTDetrObjectDetectionOutput { +}; - /** - * Convert a real-valued input array to a complex-valued output array. - * @param {Float64Array} input The real-valued input array. - * @param {Float64Array} [storage] Optional buffer to store the output array. - * @returns {Float64Array} The complex-valued output array. - */ - toComplexArray(input, storage) { - const res = storage || this.createComplexArray(); - for (let i = 0; i < res.length; i += 2) { - res[i] = input[i >>> 1]; - res[i + 1] = 0; - } - return res; - } +// src/models/roberta/modeling_roberta.js +var RobertaPreTrainedModel = class extends PreTrainedModel { +}; +var RobertaModel = class extends RobertaPreTrainedModel { +}; +var RobertaForMaskedLM = class extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var RobertaForSequenceClassification = class extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var RobertaForTokenClassification = class extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var RobertaForQuestionAnswering = class extends RobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - /** - * Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer. - * - * @param {Float64Array} out The output buffer to store the result. - * @param {Float64Array} data The input data to transform. - * - * @throws {Error} Input and output buffers must be different. - * - * @returns {void} - */ - transform(out, data) { - if (out === data) - throw new Error('Input and output buffers must be different'); +// src/models/roformer/modeling_roformer.js +var RoFormerPreTrainedModel = class extends PreTrainedModel { +}; +var RoFormerModel = class extends RoFormerPreTrainedModel { +}; +var RoFormerForMaskedLM = class extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for masked language modeling. + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var RoFormerForSequenceClassification = class extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var RoFormerForTokenClassification = class extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var RoFormerForQuestionAnswering = class extends RoFormerPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for question answering. + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; + +// src/models/rt_detr_v2/modeling_rt_detr_v2.js +var RTDetrV2PreTrainedModel = class extends PreTrainedModel { +}; +var RTDetrV2Model = class extends RTDetrV2PreTrainedModel { +}; +var RTDetrV2ForObjectDetection = class extends RTDetrV2PreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new RTDetrV2ObjectDetectionOutput(await super._call(model_inputs)); + } +}; +var RTDetrV2ObjectDetectionOutput = class extends RTDetrObjectDetectionOutput { +}; - this._transform4(out, data, 1 /* DONE */); +// src/models/sam/modeling_sam.js +var SamImageSegmentationOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.iou_scores The output logits of the model. + * @param {Tensor} output.pred_masks Predicted boxes. + */ + constructor({ iou_scores, pred_masks }) { + super(); + this.iou_scores = iou_scores; + this.pred_masks = pred_masks; + } +}; +var SamPreTrainedModel = class extends PreTrainedModel { +}; +var SamModel = class extends SamPreTrainedModel { + /** + * Compute image embeddings and positional image embeddings, given the pixel values of an image. + * @param {Object} model_inputs Object containing the model inputs. + * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`. + * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings. + */ + async get_image_embeddings({ pixel_values }) { + return await encoder_forward(this, { pixel_values }); + } + /** + * @typedef {Object} SamModelInputs Object containing the model inputs. + * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`. + * These can be obtained using a `SamProcessor`. + * @property {Tensor} [input_points] Input 2D spatial points with shape `(batch_size, num_points, 2)`. + * This is used by the prompt encoder to encode the prompt. + * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`. + * This is used by the prompt encoder to encode the prompt. There are 4 types of labels: + * - `1`: the point is a point that contains the object of interest + * - `0`: the point is a point that does not contain the object of interest + * - `-1`: the point corresponds to the background + * - `-10`: the point is a padding point, thus should be ignored by the prompt encoder + * @property {Tensor} [input_boxes] Input bounding boxes with shape `(batch_size, num_boxes, 4)`. + * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder. + * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder. + */ + /** + * @param {SamModelInputs} model_inputs Object containing the model inputs. + * @returns {Promise} The output of the model. + */ + async forward(model_inputs) { + if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) { + model_inputs = { + ...model_inputs, + ...await this.get_image_embeddings(model_inputs) + }; + } else { + model_inputs = { ...model_inputs }; } - - /** - * Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer. - * The input buffer must contain real values only, while the output buffer will contain complex values. The input and - * output buffers must be different. - * - * @param {Float64Array} out The output buffer. - * @param {Float64Array} data The input buffer containing real values. - * - * @throws {Error} If the input and output buffers are the same. - */ - realTransform(out, data) { - if (out === data) - throw new Error('Input and output buffers must be different'); - - this._realTransform4(out, data, 1 /* DONE */); + model_inputs.input_labels ??= ones(model_inputs.input_points.dims.slice(0, -1)); + const decoder_inputs = { + image_embeddings: model_inputs.image_embeddings, + image_positional_embeddings: model_inputs.image_positional_embeddings + }; + if (model_inputs.input_points) { + decoder_inputs.input_points = model_inputs.input_points; } - - /** - * Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`. - * The `out` array must be a different buffer than the `data` array. The `out` array will contain the - * result of the transformation. The `data` array will not be modified. - * - * @param {Float64Array} out The output buffer for the transformed data. - * @param {Float64Array} data The input data to transform. - * @throws {Error} If `out` and `data` refer to the same buffer. - * @returns {void} - */ - inverseTransform(out, data) { - if (out === data) - throw new Error('Input and output buffers must be different'); - - this._transform4(out, data, -1 /* DONE */); - for (let i = 0; i < out.length; ++i) - out[i] /= this.size; + if (model_inputs.input_labels) { + decoder_inputs.input_labels = model_inputs.input_labels; } - - /** - * Performs a radix-4 implementation of a discrete Fourier transform on a given set of data. - * - * @param {Float64Array} out The output buffer for the transformed data. - * @param {Float64Array} data The input buffer of data to be transformed. - * @param {number} inv A scaling factor to apply to the transform. - * @returns {void} - */ - _transform4(out, data, inv) { - // radix-4 implementation - - const size = this._csize; - - // Initial step (permute and transform) - const width = this._width; - let step = 1 << width; - let len = (size / step) << 1; - - let outOff; - let t; - const bitrev = this._bitrev; - if (len === 4) { - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleTransform2(data, out, outOff, off, step); - } - } else { - // len === 8 - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleTransform4(data, out, outOff, off, step, inv); - } - } - - // Loop through steps in decreasing order - const table = this.table; - for (step >>= 2; step >= 2; step >>= 2) { - len = (size / step) << 1; - const quarterLen = len >>> 2; - - // Loop through offsets in the data - for (outOff = 0; outOff < size; outOff += len) { - // Full case - const limit = outOff + quarterLen - 1; - for (let i = outOff, k = 0; i < limit; i += 2, k += step) { - const A = i; - const B = A + quarterLen; - const C = B + quarterLen; - const D = C + quarterLen; - - // Original values - const Ar = out[A]; - const Ai = out[A + 1]; - const Br = out[B]; - const Bi = out[B + 1]; - const Cr = out[C]; - const Ci = out[C + 1]; - const Dr = out[D]; - const Di = out[D + 1]; - - const tableBr = table[k]; - const tableBi = inv * table[k + 1]; - const MBr = Br * tableBr - Bi * tableBi; - const MBi = Br * tableBi + Bi * tableBr; - - const tableCr = table[2 * k]; - const tableCi = inv * table[2 * k + 1]; - const MCr = Cr * tableCr - Ci * tableCi; - const MCi = Cr * tableCi + Ci * tableCr; - - const tableDr = table[3 * k]; - const tableDi = inv * table[3 * k + 1]; - const MDr = Dr * tableDr - Di * tableDi; - const MDi = Dr * tableDi + Di * tableDr; - - // Pre-Final values - const T0r = Ar + MCr; - const T0i = Ai + MCi; - const T1r = Ar - MCr; - const T1i = Ai - MCi; - const T2r = MBr + MDr; - const T2i = MBi + MDi; - const T3r = inv * (MBr - MDr); - const T3i = inv * (MBi - MDi); - - // Final values - out[A] = T0r + T2r; - out[A + 1] = T0i + T2i; - out[B] = T1r + T3i; - out[B + 1] = T1i - T3r; - out[C] = T0r - T2r; - out[C + 1] = T0i - T2i; - out[D] = T1r - T3i; - out[D + 1] = T1i + T3r; - } - } - } + if (model_inputs.input_boxes) { + decoder_inputs.input_boxes = model_inputs.input_boxes; } + return await sessionRun(this.sessions["prompt_encoder_mask_decoder"], decoder_inputs); + } + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new SamImageSegmentationOutput(await super._call(model_inputs)); + } +}; - /** - * Performs a radix-2 implementation of a discrete Fourier transform on a given set of data. - * - * @param {Float64Array} data The input buffer of data to be transformed. - * @param {Float64Array} out The output buffer for the transformed data. - * @param {number} outOff The offset at which to write the output data. - * @param {number} off The offset at which to begin reading the input data. - * @param {number} step The step size for indexing the input data. - * @returns {void} - */ - _singleTransform2(data, out, outOff, off, step) { - // radix-2 implementation - // NOTE: Only called for len=4 - - const evenR = data[off]; - const evenI = data[off + 1]; - const oddR = data[off + step]; - const oddI = data[off + step + 1]; - - out[outOff] = evenR + oddR; - out[outOff + 1] = evenI + oddI; - out[outOff + 2] = evenR - oddR; - out[outOff + 3] = evenI - oddI; +// src/models/sam2/modeling_sam2.js +var Sam2ImageSegmentationOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.iou_scores The output logits of the model. + * @param {Tensor} output.pred_masks Predicted boxes. + * @param {Tensor} output.object_score_logits Logits for the object score, indicating if an object is present. + */ + constructor({ iou_scores, pred_masks, object_score_logits }) { + super(); + this.iou_scores = iou_scores; + this.pred_masks = pred_masks; + this.object_score_logits = object_score_logits; + } +}; +var Sam2PreTrainedModel = class extends PreTrainedModel { +}; +var Sam2Model = class extends Sam2PreTrainedModel { + /** + * Compute image embeddings and positional image embeddings, given the pixel values of an image. + * @param {Object} model_inputs Object containing the model inputs. + * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `Sam2Processor`. + * @returns {Promise>} The image embeddings. + */ + async get_image_embeddings({ pixel_values }) { + return await encoder_forward(this, { pixel_values }); + } + async forward(model_inputs) { + const { num_feature_levels } = this.config.vision_config; + const image_embeddings_name = Array.from({ length: num_feature_levels }, (_, i) => `image_embeddings.${i}`); + if (image_embeddings_name.some((name) => !model_inputs[name])) { + model_inputs = { + ...model_inputs, + ...await this.get_image_embeddings(model_inputs) + }; + } else { + model_inputs = { ...model_inputs }; } - - /** - * Performs radix-4 transformation on input data of length 8 - * - * @param {Float64Array} data Input data array of length 8 - * @param {Float64Array} out Output data array of length 8 - * @param {number} outOff Index of output array to start writing from - * @param {number} off Index of input array to start reading from - * @param {number} step Step size between elements in input array - * @param {number} inv Scaling factor for inverse transform - * - * @returns {void} - */ - _singleTransform4(data, out, outOff, off, step, inv) { - // radix-4 - // NOTE: Only called for len=8 - const step2 = step * 2; - const step3 = step * 3; - - // Original values - const Ar = data[off]; - const Ai = data[off + 1]; - const Br = data[off + step]; - const Bi = data[off + step + 1]; - const Cr = data[off + step2]; - const Ci = data[off + step2 + 1]; - const Dr = data[off + step3]; - const Di = data[off + step3 + 1]; - - // Pre-Final values - const T0r = Ar + Cr; - const T0i = Ai + Ci; - const T1r = Ar - Cr; - const T1i = Ai - Ci; - const T2r = Br + Dr; - const T2i = Bi + Di; - const T3r = inv * (Br - Dr); - const T3i = inv * (Bi - Di); - - // Final values - out[outOff] = T0r + T2r; - out[outOff + 1] = T0i + T2i; - out[outOff + 2] = T1r + T3i; - out[outOff + 3] = T1i - T3r; - out[outOff + 4] = T0r - T2r; - out[outOff + 5] = T0i - T2i; - out[outOff + 6] = T1r - T3i; - out[outOff + 7] = T1i + T3r; + if (model_inputs.input_points) { + if (model_inputs.input_boxes && model_inputs.input_boxes.dims[1] !== 1) { + throw new Error( + "When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1." + ); + } + const shape = model_inputs.input_points.dims; + model_inputs.input_labels ??= ones(shape.slice(0, -1)); + model_inputs.input_boxes ??= full([shape[0], 0, 4], 0); + } else if (model_inputs.input_boxes) { + const shape = model_inputs.input_boxes.dims; + model_inputs.input_labels = full([shape[0], shape[1], 0], -1n); + model_inputs.input_points = full([shape[0], 1, 0, 2], 0); + } else { + throw new Error("At least one of `input_points` or `input_boxes` must be provided."); } + const prompt_encoder_mask_decoder_session = this.sessions["prompt_encoder_mask_decoder"]; + const decoder_inputs = pick(model_inputs, prompt_encoder_mask_decoder_session.inputNames); + return await sessionRun(prompt_encoder_mask_decoder_session, decoder_inputs); + } + /** + * Runs the model with the provided inputs + * @param {Object} model_inputs Model inputs + * @returns {Promise} Object containing segmentation outputs + */ + async _call(model_inputs) { + return new Sam2ImageSegmentationOutput(await super._call(model_inputs)); + } +}; +var EdgeTamModel = class extends Sam2Model { +}; +var Sam3TrackerModel = class extends Sam2Model { +}; - /** - * Real input radix-4 implementation - * @param {Float64Array} out Output array for the transformed data - * @param {Float64Array} data Input array of real data to be transformed - * @param {number} inv The scale factor used to normalize the inverse transform - */ - _realTransform4(out, data, inv) { - // Real input radix-4 implementation - const size = this._csize; - - // Initial step (permute and transform) - const width = this._width; - let step = 1 << width; - let len = (size / step) << 1; - - let outOff; - let t; - const bitrev = this._bitrev; - if (len === 4) { - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleRealTransform2(data, out, outOff, off >>> 1, step >>> 1); - } - } else { - // len === 8 - for (outOff = 0, t = 0; outOff < size; outOff += len, ++t) { - const off = bitrev[t]; - this._singleRealTransform4(data, out, outOff, off >>> 1, step >>> 1, inv); - } - } - - // Loop through steps in decreasing order - const table = this.table; - for (step >>= 2; step >= 2; step >>= 2) { - len = (size / step) << 1; - const halfLen = len >>> 1; - const quarterLen = halfLen >>> 1; - const hquarterLen = quarterLen >>> 1; - - // Loop through offsets in the data - for (outOff = 0; outOff < size; outOff += len) { - for (let i = 0, k = 0; i <= hquarterLen; i += 2, k += step) { - const A = outOff + i; - const B = A + quarterLen; - const C = B + quarterLen; - const D = C + quarterLen; - - // Original values - const Ar = out[A]; - const Ai = out[A + 1]; - const Br = out[B]; - const Bi = out[B + 1]; - const Cr = out[C]; - const Ci = out[C + 1]; - const Dr = out[D]; - const Di = out[D + 1]; - - // Middle values - const MAr = Ar; - const MAi = Ai; - - const tableBr = table[k]; - const tableBi = inv * table[k + 1]; - const MBr = Br * tableBr - Bi * tableBi; - const MBi = Br * tableBi + Bi * tableBr; - - const tableCr = table[2 * k]; - const tableCi = inv * table[2 * k + 1]; - const MCr = Cr * tableCr - Ci * tableCi; - const MCi = Cr * tableCi + Ci * tableCr; - - const tableDr = table[3 * k]; - const tableDi = inv * table[3 * k + 1]; - const MDr = Dr * tableDr - Di * tableDi; - const MDi = Dr * tableDi + Di * tableDr; - - // Pre-Final values - const T0r = MAr + MCr; - const T0i = MAi + MCi; - const T1r = MAr - MCr; - const T1i = MAi - MCi; - const T2r = MBr + MDr; - const T2i = MBi + MDi; - const T3r = inv * (MBr - MDr); - const T3i = inv * (MBi - MDi); - - // Final values - out[A] = T0r + T2r; - out[A + 1] = T0i + T2i; - out[B] = T1r + T3i; - out[B + 1] = T1i - T3r; - - // Output final middle point - if (i === 0) { - out[C] = T0r - T2r; - out[C + 1] = T0i - T2i; - continue; - } +// src/models/sapiens/modeling_sapiens.js +var SapiensPreTrainedModel = class extends PreTrainedModel { +}; +var SapiensForSemanticSegmentation = class extends SapiensPreTrainedModel { +}; +var SapiensForDepthEstimation = class extends SapiensPreTrainedModel { +}; +var SapiensForNormalEstimation = class extends SapiensPreTrainedModel { +}; - // Do not overwrite ourselves - if (i === hquarterLen) - continue; +// src/models/segformer/modeling_segformer.js +var SegformerPreTrainedModel = class extends PreTrainedModel { +}; +var SegformerModel = class extends SegformerPreTrainedModel { +}; +var SegformerForImageClassification = class extends SegformerPreTrainedModel { +}; +var SegformerForSemanticSegmentation = class extends SegformerPreTrainedModel { +}; - const SA = outOff + quarterLen - i; - const SB = outOff + halfLen - i; +// src/models/siglip/modeling_siglip.js +var SiglipPreTrainedModel = class extends PreTrainedModel { +}; +var SiglipModel = class extends SiglipPreTrainedModel { +}; +var SiglipTextModel = class extends SiglipPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "text_model" + }); + } +}; +var SiglipVisionModel = class extends CLIPPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "vision_model" + }); + } +}; - out[SA] = T1r - inv * T3i; - out[SA + 1] = -T1i - inv * T3r; - out[SB] = T0r - inv * T2r; - out[SB + 1] = -T0i + inv * T2i; - } - } - } +// src/models/smollm3/modeling_smollm3.js +var SmolLM3PreTrainedModel = class extends PreTrainedModel { +}; +var SmolLM3Model = class extends SmolLM3PreTrainedModel { +}; +var SmolLM3ForCausalLM = class extends SmolLM3PreTrainedModel { +}; - // Complete the spectrum by adding its mirrored negative frequency components. - const half = size >>> 1; - for (let i = 2; i < half; i += 2) { - out[size - i] = out[i]; - out[size - i + 1] = -out[i + 1]; - } - } +// src/models/smolvlm/modeling_smolvlm.js +var SmolVLMForConditionalGeneration = class extends Idefics3ForConditionalGeneration { +}; - /** - * Performs a single real input radix-2 transformation on the provided data - * - * @param {Float64Array} data The input data array - * @param {Float64Array} out The output data array - * @param {number} outOff The output offset - * @param {number} off The input offset - * @param {number} step The step - * - * @returns {void} - */ - _singleRealTransform2(data, out, outOff, off, step) { - // radix-2 implementation - // NOTE: Only called for len=4 +// src/models/snac/modeling_snac.js +var SnacPreTrainedModel = class extends PreTrainedModel { + main_input_name = "input_values"; + forward_params = ["input_values"]; +}; +var SnacModel = class extends SnacPreTrainedModel { + /** + * Encodes the input audio waveform into discrete codes. + * @param {Object} inputs Model inputs + * @param {Tensor} [inputs.input_values] Float values of the input audio waveform, of shape `(batch_size, channels, sequence_length)`). + * @returns {Promise>} The output tensors of shape `(batch_size, num_codebooks, sequence_length)`. + */ + async encode(inputs) { + return await sessionRun(this.sessions["encoder_model"], inputs); + } + /** + * Decodes the given frames into an output audio waveform. + * @param {Record} inputs The encoded audio codes. + * @returns {Promise<{audio_values: Tensor}>} The output tensor of shape `(batch_size, num_channels, sequence_length)`. + */ + async decode(inputs) { + return await sessionRun(this.sessions["decoder_model"], inputs); + } +}; +var SnacEncoderModel = class extends SnacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "encoder_model" + }); + } +}; +var SnacDecoderModel = class extends SnacPreTrainedModel { + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, options = {}) { + return super.from_pretrained(pretrained_model_name_or_path, { + ...options, + // Update default model file name if not provided + model_file_name: options.model_file_name ?? "decoder_model" + }); + } +}; - const evenR = data[off]; - const oddR = data[off + step]; +// src/models/solar_open/modeling_solar_open.js +var SolarOpenPreTrainedModel = class extends PreTrainedModel { +}; +var SolarOpenModel = class extends SolarOpenPreTrainedModel { +}; +var SolarOpenForCausalLM = class extends SolarOpenPreTrainedModel { +}; - out[outOff] = evenR + oddR; - out[outOff + 1] = 0; - out[outOff + 2] = evenR - oddR; - out[outOff + 3] = 0; +// src/models/speecht5/modeling_speecht5.js +var SpeechT5PreTrainedModel = class extends PreTrainedModel { +}; +var SpeechT5Model = class extends SpeechT5PreTrainedModel { +}; +var SpeechT5ForSpeechToText = class extends SpeechT5PreTrainedModel { +}; +var SpeechT5ForTextToSpeech = class extends SpeechT5PreTrainedModel { + /** + * @typedef {Object} SpeechOutput + * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape + * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided + * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided. + * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape + * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`. + */ + /** + * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder. + * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary. + * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings. + * @param {Object} options Optional parameters for generating speech. + * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value. + * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence. + * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence. + * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram. + * @param {boolean} [options.output_cross_attentions=false] Whether to return attention tensors from the decoder's cross-attention layers. + * @returns {Promise} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors. + */ + async generate_speech(input_values, speaker_embeddings, { + threshold = 0.5, + minlenratio = 0, + maxlenratio = 20, + vocoder = null + // output_cross_attentions = false, // TODO add + } = {}) { + const model_inputs = { + input_ids: input_values + }; + const { encoder_outputs, encoder_attention_mask } = await encoder_forward(this, model_inputs); + const r = encoder_outputs.dims[1] / this.config.reduction_factor; + const maxlen = Math.floor(r * maxlenratio); + const minlen = Math.floor(r * minlenratio); + const num_mel_bins = this.config.num_mel_bins; + let spectrogramParts = []; + let past_key_values = null; + let decoder_outputs = null; + let idx = 0; + while (true) { + ++idx; + const use_cache_branch = boolTensor(!!decoder_outputs); + let output_sequence; + if (decoder_outputs) { + output_sequence = decoder_outputs.output_sequence_out; + } else { + output_sequence = new Tensor3("float32", new Float32Array(num_mel_bins), [1, 1, num_mel_bins]); + } + let decoderFeeds = { + use_cache_branch, + output_sequence, + encoder_attention_mask, + speaker_embeddings, + encoder_hidden_states: encoder_outputs + }; + addPastKeyValues(this, decoderFeeds, past_key_values); + decoder_outputs = await sessionRun(this.sessions["decoder_model_merged"], decoderFeeds); + past_key_values = getPastKeyValues(decoder_outputs, past_key_values); + const { prob, spectrum } = decoder_outputs; + spectrogramParts.push(spectrum); + if (idx >= minlen && // Finished when stop token or maximum length is reached. + (Array.from(prob.data).filter((p) => p >= threshold).length > 0 || idx >= maxlen)) { + break; + } } + const spectrogram2 = cat(spectrogramParts); + const { waveform } = await sessionRun(vocoder.sessions["model"], { spectrogram: spectrogram2 }); + return { + spectrogram: spectrogram2, + waveform + // cross_attentions: null, // TODO add + }; + } +}; +var SpeechT5HifiGan = class extends PreTrainedModel { + main_input_name = "spectrogram"; +}; - /** - * Computes a single real-valued transform using radix-4 algorithm. - * This method is only called for len=8. - * - * @param {Float64Array} data The input data array. - * @param {Float64Array} out The output data array. - * @param {number} outOff The offset into the output array. - * @param {number} off The offset into the input array. - * @param {number} step The step size for the input array. - * @param {number} inv The value of inverse. - */ - _singleRealTransform4(data, out, outOff, off, step, inv) { - // radix-4 - // NOTE: Only called for len=8 - const step2 = step * 2; - const step3 = step * 3; - - // Original values - const Ar = data[off]; - const Br = data[off + step]; - const Cr = data[off + step2]; - const Dr = data[off + step3]; - - // Pre-Final values - const T0r = Ar + Cr; - const T1r = Ar - Cr; - const T2r = Br + Dr; - const T3r = inv * (Br - Dr); - - // Final values - out[outOff] = T0r + T2r; - out[outOff + 1] = 0; - out[outOff + 2] = T1r; - out[outOff + 3] = -T3r; - out[outOff + 4] = T0r - T2r; - out[outOff + 5] = 0; - out[outOff + 6] = T1r; - out[outOff + 7] = T3r; - } -} - -/** - * NP2FFT class provides functionality for performing Fast Fourier Transform on arrays - * which are not a power of two in length. In such cases, the chirp-z transform is used. - * - * For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156 - */ -class NP2FFT { - - /** - * Constructs a new NP2FFT object. - * @param {number} fft_length The length of the FFT - */ - constructor(fft_length) { - // Helper variables - const a = 2 * (fft_length - 1); - const b = 2 * (2 * fft_length - 1); - const nextP2 = 2 ** (Math.ceil(Math.log2(b))) - this.bufferSize = nextP2; - this._a = a; - - // Define buffers - // Compute chirp for transform - const chirp = new Float64Array(b); - const ichirp = new Float64Array(nextP2); - this._chirpBuffer = new Float64Array(nextP2); - this._buffer1 = new Float64Array(nextP2); - this._buffer2 = new Float64Array(nextP2); - this._outBuffer1 = new Float64Array(nextP2); - this._outBuffer2 = new Float64Array(nextP2); - - // Compute complex exponentiation - const theta = -2 * Math.PI / fft_length; - const baseR = Math.cos(theta); - const baseI = Math.sin(theta); - - // Precompute helper for chirp-z transform - for (let i = 0; i < b >> 1; ++i) { - // Compute complex power: - const e = (i + 1 - fft_length) ** 2 / 2.0; - - // Compute the modulus and argument of the result - const result_mod = Math.sqrt(baseR ** 2 + baseI ** 2) ** e; - const result_arg = e * Math.atan2(baseI, baseR); - - // Convert the result back to rectangular form - // and assign to chirp and ichirp - const i2 = 2 * i; - chirp[i2] = result_mod * Math.cos(result_arg); - chirp[i2 + 1] = result_mod * Math.sin(result_arg); - - // conjugate - ichirp[i2] = chirp[i2]; - ichirp[i2 + 1] = - chirp[i2 + 1]; - } - this._slicedChirpBuffer = chirp.subarray(a, b); - - // create object to perform Fast Fourier Transforms - // with `nextP2` complex numbers - this._f = new P2FFT(nextP2 >> 1); - this._f.transform(this._chirpBuffer, ichirp); - } - - _transform(output, input, real) { - const ib1 = this._buffer1; - const ib2 = this._buffer2; - const ob2 = this._outBuffer1; - const ob3 = this._outBuffer2; - const cb = this._chirpBuffer; - const sb = this._slicedChirpBuffer; - const a = this._a; - - if (real) { - // Real multiplication - for (let j = 0; j < sb.length; j += 2) { - const j2 = j + 1 - const j3 = j >> 1; - - const a_real = input[j3]; - ib1[j] = a_real * sb[j]; - ib1[j2] = a_real * sb[j2]; - } - } else { - // Complex multiplication - for (let j = 0; j < sb.length; j += 2) { - const j2 = j + 1 - ib1[j] = input[j] * sb[j] - input[j2] * sb[j2]; - ib1[j2] = input[j] * sb[j2] + input[j2] * sb[j]; - } - } - this._f.transform(ob2, ib1); +// src/models/squeezebert/modeling_squeezebert.js +var SqueezeBertPreTrainedModel = class extends PreTrainedModel { +}; +var SqueezeBertModel = class extends SqueezeBertPreTrainedModel { +}; +var SqueezeBertForMaskedLM = class extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var SqueezeBertForSequenceClassification = class extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var SqueezeBertForQuestionAnswering = class extends SqueezeBertPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - for (let j = 0; j < cb.length; j += 2) { - const j2 = j + 1; +// src/models/stablelm/modeling_stablelm.js +var StableLmPreTrainedModel = class extends PreTrainedModel { +}; +var StableLmModel = class extends StableLmPreTrainedModel { +}; +var StableLmForCausalLM = class extends StableLmPreTrainedModel { +}; - ib2[j] = ob2[j] * cb[j] - ob2[j2] * cb[j2]; - ib2[j2] = ob2[j] * cb[j2] + ob2[j2] * cb[j]; - } - this._f.inverseTransform(ob3, ib2); +// src/models/starcoder2/modeling_starcoder2.js +var Starcoder2PreTrainedModel = class extends PreTrainedModel { +}; +var Starcoder2Model = class extends Starcoder2PreTrainedModel { +}; +var Starcoder2ForCausalLM = class extends Starcoder2PreTrainedModel { +}; - for (let j = 0; j < ob3.length; j += 2) { - const a_real = ob3[j + a]; - const a_imag = ob3[j + a + 1]; - const b_real = sb[j]; - const b_imag = sb[j + 1]; +// src/models/style_text_to_speech_2/modeling_style_text_to_speech_2.js +var StyleTextToSpeech2PreTrainedModel = class extends PreTrainedModel { +}; +var StyleTextToSpeech2Model = class extends StyleTextToSpeech2PreTrainedModel { +}; - output[j] = a_real * b_real - a_imag * b_imag; - output[j + 1] = a_real * b_imag + a_imag * b_real; - } +// src/models/supertonic/modeling_supertonic.js +var SupertonicPreTrainedModel = class extends PreTrainedModel { +}; +var SupertonicForConditionalGeneration = class extends SupertonicPreTrainedModel { + async generate_speech({ + // Required inputs + input_ids, + attention_mask, + style, + // Optional inputs + num_inference_steps = 5, + speed = 1.05 + }) { + const { sampling_rate, chunk_compress_factor, base_chunk_size, latent_dim } = this.config; + const { last_hidden_state, durations: raw_durations } = await sessionRun(this.sessions["text_encoder"], { + input_ids, + attention_mask, + style + }); + const durations = raw_durations.div(speed).mul_(sampling_rate); + const latent_size = base_chunk_size * chunk_compress_factor; + const durationsData = ( + /** @type {Float32Array} */ + durations.data + ); + const latentLengths = Int32Array.from(durationsData, (d) => Math.ceil(d / latent_size)); + const maxLatentLen = Math.max(...latentLengths); + const batch_size = input_ids.dims[0]; + const latentMaskData = new BigInt64Array(batch_size * maxLatentLen); + for (let i = 0; i < batch_size; ++i) { + latentMaskData.fill(1n, i * maxLatentLen, i * maxLatentLen + latentLengths[i]); + } + const latent_mask = new Tensor3("int64", latentMaskData, [batch_size, maxLatentLen]); + const latentChannels = latent_dim * chunk_compress_factor; + const latentStride = latentChannels * maxLatentLen; + let noisy_latents = randn([batch_size, latentChannels, maxLatentLen]); + const latentsData = ( + /** @type {Float32Array} */ + noisy_latents.data + ); + for (let i = 0; i < batch_size; ++i) { + if (latentLengths[i] === maxLatentLen) continue; + for (let c = 0; c < latentChannels; ++c) { + latentsData.fill( + 0, + i * latentStride + c * maxLatentLen + latentLengths[i], + i * latentStride + (c + 1) * maxLatentLen + ); + } } - - transform(output, input) { - this._transform(output, input, false); + const num_steps = full([batch_size], num_inference_steps); + for (let step = 0; step < num_inference_steps; ++step) { + const timestep = full([batch_size], step); + ({ denoised_latents: noisy_latents } = await sessionRun(this.sessions["latent_denoiser"], { + style, + noisy_latents, + latent_mask, + encoder_outputs: last_hidden_state, + attention_mask, + timestep, + num_inference_steps: num_steps + })); } + const { waveform } = await sessionRun(this.sessions["voice_decoder"], { + latents: noisy_latents + }); + return { + waveform, + durations + }; + } +}; - realTransform(output, input) { - this._transform(output, input, true); - } -} +// src/models/swin/modeling_swin.js +var SwinPreTrainedModel = class extends PreTrainedModel { +}; +var SwinModel = class extends SwinPreTrainedModel { +}; +var SwinForImageClassification = class extends SwinPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var SwinForSemanticSegmentation = class extends SwinPreTrainedModel { +}; -class FFT { - constructor(fft_length) { - this.fft_length = fft_length; - this.isPowerOfTwo = isPowerOfTwo(fft_length); - if (this.isPowerOfTwo) { - this.fft = new P2FFT(fft_length); - this.outputBufferSize = 2 * fft_length; - } else { - this.fft = new NP2FFT(fft_length); - this.outputBufferSize = this.fft.bufferSize; - } - } +// src/models/swin2sr/modeling_swin2sr.js +var Swin2SRPreTrainedModel = class extends PreTrainedModel { +}; +var Swin2SRModel = class extends Swin2SRPreTrainedModel { +}; +var Swin2SRForImageSuperResolution = class extends Swin2SRPreTrainedModel { +}; - realTransform(out, input) { - this.fft.realTransform(out, input); - } +// src/models/t5/modeling_t5.js +var T5PreTrainedModel = class extends PreTrainedModel { + forward_params = [ + "input_ids", + "attention_mask", + "encoder_outputs", + "decoder_input_ids", + "decoder_attention_mask", + "past_key_values" + ]; +}; +var T5Model = class extends T5PreTrainedModel { +}; +var T5ForConditionalGeneration = class extends T5PreTrainedModel { +}; - transform(out, input) { - this.fft.transform(out, input); - } -} +// src/models/table_transformer/modeling_table_transformer.js +var TableTransformerPreTrainedModel = class extends PreTrainedModel { +}; +var TableTransformerModel = class extends TableTransformerPreTrainedModel { +}; +var TableTransformerForObjectDetection = class extends TableTransformerPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new TableTransformerObjectDetectionOutput(await super._call(model_inputs)); + } +}; +var TableTransformerObjectDetectionOutput = class extends DetrObjectDetectionOutput { +}; +// src/models/trocr/modeling_trocr.js +var TrOCRPreTrainedModel = class extends PreTrainedModel { +}; +var TrOCRForCausalLM = class extends TrOCRPreTrainedModel { +}; -/** - * Performs median filter on the provided data. Padding is done by mirroring the data. - * @param {AnyTypedArray} data The input array - * @param {number} windowSize The window size - */ -function medianFilter(data, windowSize) { +// src/models/unispeech/modeling_unispeech.js +var UniSpeechPreTrainedModel = class extends PreTrainedModel { +}; +var UniSpeechModel = class extends UniSpeechPreTrainedModel { +}; +var UniSpeechForCTC = class extends UniSpeechPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; +var UniSpeechForSequenceClassification = class extends UniSpeechPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; + +// src/models/unispeech_sat/modeling_unispeech_sat.js +var UniSpeechSatPreTrainedModel = class extends PreTrainedModel { +}; +var UniSpeechSatModel = class extends UniSpeechSatPreTrainedModel { +}; +var UniSpeechSatForCTC = class extends UniSpeechSatPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; +var UniSpeechSatForSequenceClassification = class extends UniSpeechSatPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var UniSpeechSatForAudioFrameClassification = class extends UniSpeechSatPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; - if (windowSize % 2 === 0 || windowSize <= 0) { - throw new Error('Window size must be a positive odd number'); - } +// src/models/vaultgemma/modeling_vaultgemma.js +var VaultGemmaPreTrainedModel = class extends PreTrainedModel { +}; +var VaultGemmaModel = class extends VaultGemmaPreTrainedModel { +}; +var VaultGemmaForCausalLM = class extends VaultGemmaPreTrainedModel { +}; - // @ts-ignore - const outputArray = new data.constructor(data.length); +// src/models/vision_encoder_decoder/modeling_vision_encoder_decoder.js +var VisionEncoderDecoderModel = class extends PreTrainedModel { + main_input_name = "pixel_values"; + forward_params = [ + // Encoder inputs + "pixel_values", + // Decoder inpputs + "decoder_input_ids", + "encoder_hidden_states", + "past_key_values" + ]; +}; - // @ts-ignore - const buffer = new data.constructor(windowSize); // Reusable array for storing values +// src/models/vit/modeling_vit.js +var ViTPreTrainedModel = class extends PreTrainedModel { +}; +var ViTModel = class extends ViTPreTrainedModel { +}; +var ViTForImageClassification = class extends ViTPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - const halfWindowSize = Math.floor(windowSize / 2); +// src/models/vit_mae/modeling_vit_mae.js +var ViTMAEPreTrainedModel = class extends PreTrainedModel { +}; +var ViTMAEModel = class extends ViTMAEPreTrainedModel { +}; - for (let i = 0; i < data.length; ++i) { - let valuesIndex = 0; +// src/models/vit_msn/modeling_vit_msn.js +var ViTMSNPreTrainedModel = class extends PreTrainedModel { +}; +var ViTMSNModel = class extends ViTMSNPreTrainedModel { +}; +var ViTMSNForImageClassification = class extends ViTMSNPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; - for (let j = -halfWindowSize; j <= halfWindowSize; ++j) { - let index = i + j; - if (index < 0) { - index = Math.abs(index); - } else if (index >= data.length) { - index = 2 * (data.length - 1) - index; - } +// src/models/vitmatte/modeling_vitmatte.js +var VitMattePreTrainedModel = class extends PreTrainedModel { +}; +var VitMatteForImageMatting = class extends VitMattePreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new ImageMattingOutput(await super._call(model_inputs)); + } +}; - buffer[valuesIndex++] = data[index]; - } +// src/models/vitpose/modeling_vitpose.js +var VitPosePreTrainedModel = class extends PreTrainedModel { +}; +var VitPoseForPoseEstimation = class extends VitPosePreTrainedModel { +}; - buffer.sort(); - outputArray[i] = buffer[halfWindowSize]; - } +// src/models/vits/modeling_vits.js +var VitsModelOutput = class extends ModelOutput { + /** + * @typedef {import('../../utils/tensor.js').Tensor} Tensor + */ + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`. + * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model. + * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform. + */ + constructor({ waveform, spectrogram: spectrogram2 }) { + super(); + this.waveform = waveform; + this.spectrogram = spectrogram2; + } +}; +var VitsPreTrainedModel = class extends PreTrainedModel { +}; +var VitsModel = class extends VitsPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} The outputs for the VITS model. + */ + async _call(model_inputs) { + return new VitsModelOutput(await super._call(model_inputs)); + } +}; - return outputArray; -} +// src/models/voxtral/modeling_voxtral.js +var VoxtralForConditionalGeneration = class extends UltravoxModel { +}; -/** - * Helper function to round a number to a given number of decimals - * @param {number} num The number to round - * @param {number} decimals The number of decimals - * @returns {number} The rounded number - */ -function round(num, decimals) { - const pow = Math.pow(10, decimals); - return Math.round(num * pow) / pow; -} - -/** - * Helper function to round a number to the nearest integer, with ties rounded to the nearest even number. - * Also known as "bankers' rounding". This is the default rounding mode in python. For example: - * 1.5 rounds to 2 and 2.5 rounds to 2. - * - * @param {number} x The number to round - * @returns {number} The rounded number - */ -function bankers_round(x) { - const r = Math.round(x); - const br = Math.abs(x) % 1 === 0.5 ? (r % 2 === 0 ? r : r - 1) : r; - return br; +// src/models/voxtral_realtime/modeling_voxtral_realtime.js +var CONV1_LEFT_PAD = 2; +var CONV2_LEFT_PAD = 1; +var states = /* @__PURE__ */ new WeakMap(); +function createEncoderState(model, input_features) { + const { text_config, audio_config } = ( + /** @type {any} */ + model.config + ); + const encoder_session = model.sessions["audio_encoder"]; + const { num_mel_bins, hidden_size: enc_hidden_size } = audio_config; + const PADDING_CACHE_CHANNELS = num_mel_bins + enc_hidden_size; + const enc_kv_cache = new DynamicCache(); + const enc_names = getCacheNames(audio_config); + const enc_symbols = { batch_size: 1 }; + let padding_type = "float32"; + for (const meta of encoder_session.inputMetadata) { + if (meta.name === "past_padding_cache") { + padding_type = meta.type; + continue; + } + if (!enc_names.has(meta.name)) continue; + const shape = resolveCacheShape(meta.shape, enc_symbols); + const size = shape.reduce((a, b) => a * b, 1); + const cls = DataTypeMap[meta.type]; + enc_kv_cache[meta.name] = new Tensor3(meta.type, new cls(size), shape); + } + const padding_cls = DataTypeMap[padding_type]; + const enc_padding_cache = new Tensor3(padding_type, new padding_cls(PADDING_CACHE_CHANNELS * CONV1_LEFT_PAD), [ + 1, + PADDING_CACHE_CHANNELS, + CONV1_LEFT_PAD + ]); + const chunks_iter = input_features[Symbol.asyncIterator]?.() ?? input_features[Symbol.iterator]?.(); + if (!chunks_iter) { + throw new Error("input_features must be iterable or async iterable"); + } + return { + encoder_session, + enc_kv_cache, + enc_padding_cache, + enc_past_seq_len: 0, + audio_embed_queue: [], + audio_embed_total_tokens: 0, + audio_queue_offset: 0, + audio_consumed: 0, + stream_exhausted: false, + chunks_iter, + text_hidden_size: text_config.hidden_size + }; } - - -/** - * Measures similarity between two temporal sequences (e.g., input audio and output tokens - * to generate token-level timestamps). - * @param {number[][]} matrix - * @returns {number[][]} - */ -function dynamic_time_warping(matrix) { - const output_length = matrix.length; - const input_length = matrix[0].length; - - const outputShape = [output_length + 1, input_length + 1]; - - const cost = Array.from( - { length: outputShape[0] }, - () => Array(outputShape[1]).fill(Infinity) - ); - cost[0][0] = 0; - - const trace = Array.from( - { length: outputShape[0] }, - () => Array(outputShape[1]).fill(-1) - ); - - for (let j = 1; j < outputShape[1]; ++j) { - for (let i = 1; i < outputShape[0]; ++i) { - const c0 = cost[i - 1][j - 1]; - const c1 = cost[i - 1][j]; - const c2 = cost[i][j - 1]; - - let c, t; - if (c0 < c1 && c0 < c2) { - c = c0; - t = 0; - } else if (c1 < c0 && c1 < c2) { - c = c1; - t = 1; - } else { - c = c2; - t = 2; - } - cost[i][j] = matrix[i - 1][j - 1] + c; - trace[i][j] = t; - } +async function encodeChunk(s, chunk_features) { + const audio_seq_len = chunk_features.dims[2]; + const conv2_output_len = Math.floor((CONV2_LEFT_PAD + audio_seq_len - 3) / 2) + 1; + const position_ids = new Tensor3( + "int64", + BigInt64Array.from({ length: conv2_output_len }, (_, i) => BigInt(s.enc_past_seq_len + i)), + [1, conv2_output_len] + ); + const total_seq_len = s.enc_past_seq_len + conv2_output_len; + const attention_mask = ones([1, total_seq_len]); + const { audio_embeds, present_padding_cache, ...present_cache } = await sessionRun(s.encoder_session, { + input_features: chunk_features, + attention_mask, + position_ids, + past_padding_cache: s.enc_padding_cache, + ...s.enc_kv_cache + }); + if (s.enc_padding_cache.location === "gpu-buffer") { + s.enc_padding_cache.dispose(); + } + s.enc_padding_cache = present_padding_cache; + for (const name in present_cache) { + if (name.startsWith("present.")) { + const pastName = name.replace("present", "past_key_values"); + const prev = s.enc_kv_cache[pastName]; + if (prev?.location === "gpu-buffer") { + prev.dispose(); + } + s.enc_kv_cache[pastName] = present_cache[name]; } - - for (let i = 0; i < outputShape[1]; ++i) { // trace[0, :] = 2 - trace[0][i] = 2; + } + s.enc_past_seq_len = total_seq_len; + return audio_embeds; +} +async function fillAudioBuffer(s, needed) { + while (s.audio_embed_total_tokens < needed && !s.stream_exhausted) { + const result = await s.chunks_iter.next(); + if (result.done) { + s.stream_exhausted = true; + break; } - for (let i = 0; i < outputShape[0]; ++i) { // trace[:, 0] = 1 - trace[i][0] = 1; + const new_embeds = await encodeChunk(s, result.value); + s.audio_embed_queue.push({ data: new_embeds.data, tokens: new_embeds.dims[1] }); + s.audio_embed_total_tokens += new_embeds.dims[1]; + } +} +function addAudioEmbeddings(s, inputs_embeds, current_len) { + if (s.audio_embed_queue.length === 0) return; + const embed_data = inputs_embeds.data; + let embed_write_pos = 0; + let remaining = current_len; + while (remaining > 0 && s.audio_embed_queue.length > 0) { + const front = s.audio_embed_queue[0]; + const available = front.tokens - s.audio_queue_offset; + const n = Math.min(remaining, available); + const src_offset = s.audio_queue_offset * s.text_hidden_size; + for (let i = 0; i < n * s.text_hidden_size; ++i) { + embed_data[embed_write_pos * s.text_hidden_size + i] += front.data[src_offset + i]; + } + embed_write_pos += n; + remaining -= n; + s.audio_queue_offset += n; + if (s.audio_queue_offset >= front.tokens) { + s.audio_embed_queue.shift(); + s.audio_queue_offset = 0; } - - // backtrace - let i = output_length; - let j = input_length; - let text_indices = []; - let time_indices = []; - while (i > 0 || j > 0) { - text_indices.push(i - 1); - time_indices.push(j - 1); - - switch (trace[i][j]) { - case 0: - --i; --j; - break; - case 1: - --i; - break; - case 2: - --j; - break; - default: - throw new Error( - `Internal error in dynamic time warping. Unexpected trace[${i}, ${j}]. Please file a bug report.` - ) - } + } + s.audio_consumed += current_len - remaining; +} +var AudioExhaustedCriteria = class extends StoppingCriteria { + constructor(enc_state) { + super(); + this._s = enc_state; + } + _call(input_ids) { + const done = this._s.stream_exhausted && this._s.audio_embed_queue.length === 0; + return input_ids.map(() => done); + } +}; +var VoxtralRealtimePreTrainedModel = class extends PreTrainedModel { + forward_params = ["input_ids", "attention_mask", "position_ids", "past_key_values"]; +}; +var VoxtralRealtimeForConditionalGeneration = class extends VoxtralRealtimePreTrainedModel { + async forward({ input_ids, past_key_values, ...kwargs }) { + const current_len = input_ids.dims[1]; + const enc = states.get(this); + if (enc) { + await fillAudioBuffer(enc, enc.audio_consumed + current_len); + } + const { inputs_embeds } = await sessionRun(this.sessions["embed_tokens"], { input_ids }); + if (enc) { + addAudioEmbeddings(enc, inputs_embeds, current_len); + } + const decoder_feeds = { inputs_embeds, ...kwargs }; + addPastKeyValues(this, decoder_feeds, past_key_values); + const session = this.sessions["decoder_model_merged"]; + const fixed = pick(decoder_feeds, session.inputNames); + return await sessionRun(session, fixed); + } + async generate({ input_features, stopping_criteria: userStoppingCriteria, ...kwargs }) { + if (!input_features) { + throw new Error("input_features (generator/iterable) must be provided"); + } + const enc_state = createEncoderState(this, input_features); + states.set(this, enc_state); + const stopping_criteria = new StoppingCriteriaList(); + stopping_criteria.push(new AudioExhaustedCriteria(enc_state)); + if (userStoppingCriteria) stopping_criteria.extend(userStoppingCriteria); + try { + return await super.generate({ ...kwargs, stopping_criteria }); + } finally { + enc_state.enc_kv_cache.dispose(); + states.delete(this); } + } +}; - text_indices.reverse(); - time_indices.reverse(); - - return [text_indices, time_indices]; - -} - - -/***/ }), - -/***/ "./src/utils/tensor.js": -/*!*****************************!*\ - !*** ./src/utils/tensor.js ***! - \*****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ DataTypeMap: () => (/* binding */ DataTypeMap), -/* harmony export */ Tensor: () => (/* binding */ Tensor), -/* harmony export */ cat: () => (/* binding */ cat), -/* harmony export */ full: () => (/* binding */ full), -/* harmony export */ full_like: () => (/* binding */ full_like), -/* harmony export */ interpolate: () => (/* binding */ interpolate), -/* harmony export */ interpolate_4d: () => (/* binding */ interpolate_4d), -/* harmony export */ layer_norm: () => (/* binding */ layer_norm), -/* harmony export */ matmul: () => (/* binding */ matmul), -/* harmony export */ mean: () => (/* binding */ mean), -/* harmony export */ mean_pooling: () => (/* binding */ mean_pooling), -/* harmony export */ ones: () => (/* binding */ ones), -/* harmony export */ ones_like: () => (/* binding */ ones_like), -/* harmony export */ permute: () => (/* binding */ permute), -/* harmony export */ quantize_embeddings: () => (/* binding */ quantize_embeddings), -/* harmony export */ rand: () => (/* binding */ rand), -/* harmony export */ rfft: () => (/* binding */ rfft), -/* harmony export */ slice: () => (/* binding */ slice), -/* harmony export */ stack: () => (/* binding */ stack), -/* harmony export */ std_mean: () => (/* binding */ std_mean), -/* harmony export */ topk: () => (/* binding */ topk), -/* harmony export */ zeros: () => (/* binding */ zeros), -/* harmony export */ zeros_like: () => (/* binding */ zeros_like) -/* harmony export */ }); -/* harmony import */ var _maths_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../backends/onnx.js */ "./src/backends/onnx.js"); -/* harmony import */ var _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../ops/registry.js */ "./src/ops/registry.js"); -/** - * @file Helper module for `Tensor` processing. - * - * These functions and classes are only used internally, - * meaning an end-user shouldn't need to access anything here. - * - * @module utils/tensor - */ - - - - - - - -const DataTypeMap = Object.freeze({ - float32: Float32Array, - // @ts-ignore ts(2552) Limited availability of Float16Array across browsers: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float16Array - float16: typeof Float16Array !== "undefined" ? Float16Array: Uint16Array, - float64: Float64Array, - string: Array, // string[] - int8: Int8Array, - uint8: Uint8Array, - int16: Int16Array, - uint16: Uint16Array, - int32: Int32Array, - uint32: Uint32Array, - int64: BigInt64Array, - uint64: BigUint64Array, - bool: Uint8Array, - uint4: Uint8Array, - int4: Int8Array, -}); +// src/models/wav2vec2_bert/modeling_wav2vec2_bert.js +var Wav2Vec2BertPreTrainedModel = class extends PreTrainedModel { +}; +var Wav2Vec2BertModel = class extends Wav2Vec2BertPreTrainedModel { +}; +var Wav2Vec2BertForCTC = class extends Wav2Vec2BertPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; +var Wav2Vec2BertForSequenceClassification = class extends Wav2Vec2BertPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; + +// src/models/wavlm/modeling_wavlm.js +var XVectorOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`. + * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`. + */ + constructor({ logits, embeddings }) { + super(); + this.logits = logits; + this.embeddings = embeddings; + } +}; +var WavLMPreTrainedModel = class extends PreTrainedModel { +}; +var WavLMModel = class extends WavLMPreTrainedModel { +}; +var WavLMForCTC = class extends WavLMPreTrainedModel { + /** + * @param {Object} model_inputs + * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform. + * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1] + */ + async _call(model_inputs) { + return new CausalLMOutput(await super._call(model_inputs)); + } +}; +var WavLMForSequenceClassification = class extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var WavLMForXVector = class extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits and speaker embeddings. + */ + async _call(model_inputs) { + return new XVectorOutput(await super._call(model_inputs)); + } +}; +var WavLMForAudioFrameClassification = class extends WavLMPreTrainedModel { + /** + * Calls the model on new inputs. + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for sequence classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; -/** - * @typedef {keyof typeof DataTypeMap} DataType - * @typedef {import('./maths.js').AnyTypedArray | any[]} DataArray - */ +// src/models/wespeaker_resnet/modeling_wespeaker_resnet.js +var WeSpeakerResNetPreTrainedModel = class extends PreTrainedModel { +}; +var WeSpeakerResNetModel = class extends WeSpeakerResNetPreTrainedModel { +}; +// src/models/whisper/generation_whisper.js +var WhisperGenerationConfig = class extends GenerationConfig { + /** + * Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`. + * @type {boolean} + */ + return_timestamps = null; + /** + * Whether to return token-level timestamps + * with the text. This can be used with or without the `return_timestamps` option. To get word-level + * timestamps, use the tokenizer to group the tokens into words. + * @type {boolean} + */ + return_token_timestamps = null; + /** + * The number of audio frames available in this chunk. This is only used generating word-level timestamps. + * @type {number} + */ + num_frames = null; + /** + * Alignment heads to predict word-level timestamps. This is a list of [layer, head] pairs that + * select the cross-attention heads that are highly correlated to word-level timing. + * @type {[number, number][]} + */ + alignment_heads = null; + /** + * Task to use for generation, either "translate" or "transcribe". + * @type {string} + */ + task = null; + /** + * Language token to use for generation, can be either in the form of `<|en|>`, `en` or `english`. + * You can find all the possible language tokens in the `model.generation_config.lang_to_id` dictionary. + * @type {string} + */ + language = null; + /** + * The id of the `"<|notimestamps|>"` token. + * @type {number} + */ + no_timestamps_token_id = null; + /** + * Rank-1 list of token IDs created by passing text to [`~WhisperProcessor.get_prompt_ids`] that is + * provided as a prompt to each chunk. This can be used to provide or "prompt-engineer" a context for + * transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those words + * correctly. It cannot be used in conjunction with `decoder_start_token_id` as it overwrites this value. + * @type {number[]} + */ + prompt_ids = null; + /** + * Whether the model is multilingual or not. + * @type {boolean} + */ + is_multilingual = null; + /** + * (Optional) A mapping from language tokens to their corresponding IDs. + * Only required if the model is multilingual. + * @type {Record|null} + */ + lang_to_id = null; + /** + * (Optional) A mapping from task tokens to their corresponding IDs. + * @type {Record|null} + */ + task_to_id = null; + /** + * Used to set the maximum value of the initial timestamp. This is used to prevent the model from + * predicting timestamps that are too far in the future. + * @type {number} + */ + max_initial_timestamp_index = 1; +}; -class Tensor { - /** @type {number[]} Dimensions of the tensor. */ - get dims() { - // @ts-ignore - return this.ort_tensor.dims; +// src/models/whisper/modeling_whisper.js +var WhisperPreTrainedModel = class extends PreTrainedModel { + requires_attention_mask = false; + main_input_name = "input_features"; + forward_params = [ + "input_features", + "attention_mask", + "decoder_input_ids", + "decoder_attention_mask", + "past_key_values" + ]; +}; +var WhisperModel = class extends WhisperPreTrainedModel { +}; +var WhisperForConditionalGeneration = class extends WhisperPreTrainedModel { + _prepare_generation_config(generation_config, kwargs) { + return ( + /** @type {WhisperGenerationConfig} */ + super._prepare_generation_config(generation_config, kwargs, WhisperGenerationConfig) + ); + } + /** + * + * @param {WhisperGenerationConfig} generation_config + */ + _retrieve_init_tokens(generation_config) { + const init_tokens = [generation_config.decoder_start_token_id]; + let language = generation_config.language; + const task = generation_config.task; + if (generation_config.is_multilingual) { + if (!language) { + logger.warn("No language specified - defaulting to English (en)."); + language = "en"; + } + const language_code = whisper_language_to_code(language); + const language_token = `<|${language_code}|>`; + init_tokens.push(generation_config.lang_to_id[language_token]); + init_tokens.push(generation_config.task_to_id[task ?? "transcribe"]); + } else if (language || task) { + 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." + ); } - set dims(value) { - // FIXME: ONNXTensor declares dims as readonly so one needs to use the constructor() if dims change. - // @ts-ignore - this.ort_tensor.dims = value; + if (!generation_config.return_timestamps && generation_config.no_timestamps_token_id && init_tokens.at(-1) !== generation_config.no_timestamps_token_id) { + init_tokens.push(generation_config.no_timestamps_token_id); + } else if (generation_config.return_timestamps && init_tokens.at(-1) === generation_config.no_timestamps_token_id) { + logger.warn( + "<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`." + ); + init_tokens.pop(); } - - /** @type {DataType} Type of the tensor. */ - get type() { - return this.ort_tensor.type; - }; - - /** @type {DataArray} The data stored in the tensor. */ - get data() { - return this.ort_tensor.data; + return init_tokens.filter((token) => token != null); + } + /** + * Transcribes or translates log-mel input features to a sequence of auto-regressively generated token ids. + * @param {import('./generation_whisper.js').WhisperGenerationFunctionParameters} options + * @returns {Promise} The output of the model, which can contain the generated token ids, attentions, and scores. + */ + async generate({ + inputs = null, + generation_config = null, + logits_processor = null, + stopping_criteria = null, + // Whisper-specific options (passed to kwargs) + // prompt_ids = null, + // language = null, + // task = null, + ...kwargs + }) { + generation_config = this._prepare_generation_config(generation_config, kwargs); + const init_tokens = kwargs.decoder_input_ids instanceof Tensor3 ? prepareTensorForDecode(kwargs.decoder_input_ids) : kwargs.decoder_input_ids ?? this._retrieve_init_tokens(generation_config); + if (generation_config.return_timestamps) { + logits_processor ??= new LogitsProcessorList(); + logits_processor.push(new WhisperTimeStampLogitsProcessor(generation_config, init_tokens)); + } + if (generation_config.begin_suppress_tokens) { + logits_processor ??= new LogitsProcessorList(); + logits_processor.push( + new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, init_tokens.length) + ); } - - /** @type {number} The number of elements in the tensor. */ - get size() { - return this.ort_tensor.size; - }; - - /** @type {string} The location of the tensor data. */ - get location() { - return this.ort_tensor.location; - }; - - ort_tensor; - - /** - * Create a new Tensor or copy an existing Tensor. - * @param {[DataType, DataArray, number[]]|[ONNXTensor]} args - */ - constructor(...args) { - if ((0,_backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.isONNXTensor)(args[0])) { - this.ort_tensor = /** @type {ONNXTensor} */ (args[0]); - } else { - // Create new tensor - this.ort_tensor = new _backends_onnx_js__WEBPACK_IMPORTED_MODULE_1__.Tensor( - /** @type {DataType} */(args[0]), - // @ts-expect-error ts(2769) Type 'number' is not assignable to type 'bigint'. - /** @type {Exclude} */(args[1]), - args[2], - ); - } - - return new Proxy(this, { - get: (obj, key) => { - if (typeof key === 'string') { - let index = Number(key); - if (Number.isInteger(index)) { - // key is an integer (i.e., index) - return obj._getitem(index); - } - } - // @ts-ignore - return obj[key]; - }, - set: (obj, key, value) => { - // TODO allow setting of data - - // @ts-ignore - return obj[key] = value; - } - }); + if (generation_config.return_token_timestamps) { + if (!generation_config.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." + ); + } + if (generation_config.task === "translate") { + logger.warn("Token-level timestamps may not be reliable for task 'translate'."); + } + generation_config.output_attentions = true; + generation_config.return_dict_in_generate = true; } - - dispose() { - this.ort_tensor.dispose(); - // this.ort_tensor = undefined; + if (generation_config.return_timestamps && !kwargs.max_new_tokens) { + return this._generate_with_seek({ + inputs, + generation_config, + logits_processor, + init_tokens, + kwargs + }); } - - /** - * Returns an iterator object for iterating over the tensor data in row-major order. - * If the tensor has more than one dimension, the iterator will yield subarrays. - * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order. - */ - *[Symbol.iterator]() { - const [iterLength, ...iterDims] = this.dims; - - if (iterDims.length > 0) { - const iterSize = iterDims.reduce((a, b) => a * b); - for (let i = 0; i < iterLength; ++i) { - yield this._subarray(i, iterSize, iterDims); - } - } else { - yield* this.data - } - + const outputs = await super.generate({ + inputs, + generation_config, + logits_processor, + decoder_input_ids: init_tokens, + ...kwargs + }); + if (generation_config.return_token_timestamps) { + outputs["token_timestamps"] = this._extract_token_timestamps( + // @ts-expect-error TS2345 + outputs, + generation_config.alignment_heads, + generation_config.num_frames, + 0.02, + init_tokens.length + ); } - - /** - * Index into a Tensor object. - * @param {number} index The index to access. - * @returns {Tensor} The data at the specified index. - */ - _getitem(index) { - const [iterLength, ...iterDims] = this.dims; - - index = safeIndex(index, iterLength); - - if (iterDims.length > 0) { - const iterSize = iterDims.reduce((a, b) => a * b); - return this._subarray(index, iterSize, iterDims); - } else { - return new Tensor(this.type, [this.data[index]], iterDims); + return outputs; + } + /** + * Generates with a seek loop for timestamp mode, re-encoding and generating + * for each segment until all audio frames are consumed. + * This matches Python's WhisperForConditionalGeneration.generate() behavior. + * @private + */ + async _generate_with_seek({ inputs, generation_config, logits_processor, init_tokens, kwargs }) { + const timestamp_begin = generation_config.no_timestamps_token_id + 1; + const eos_token_id = Array.isArray(generation_config.eos_token_id) ? generation_config.eos_token_id[0] : generation_config.eos_token_id; + const return_token_timestamps = generation_config.return_token_timestamps; + const input_features = inputs; + const total_frames = input_features.dims[2]; + const input_stride = 2; + const max_source_positions = ( + /** @type {number} */ + this.config.max_source_positions + ); + const num_segment_frames = input_stride * max_source_positions; + let seek = 0; + const allTokens = []; + const allTokenTimestamps = []; + while (seek < total_frames) { + const seek_end = Math.min(seek + num_segment_frames, total_frames); + const segment_input = input_features.slice(null, null, [seek, seek_end]); + let segment_features; + const segment_frames = segment_input.dims[2]; + if (segment_frames < num_segment_frames) { + const n_mels = input_features.dims[1]; + const padded_data = new Float32Array(n_mels * num_segment_frames); + const src = ( + /** @type {Float32Array} */ + segment_input.data + ); + for (let m = 0; m < n_mels; ++m) { + padded_data.set(src.subarray(m * segment_frames, (m + 1) * segment_frames), m * num_segment_frames); } - } - - /** - * @param {number|bigint} item The item to search for in the tensor - * @returns {number} The index of the first occurrence of item in the tensor data. - */ - indexOf(item) { - const this_data = this.data; - for (let index = 0; index < this_data.length; ++index) { - // Note: == instead of === so we can match Ints with BigInts - if (this_data[index] == item) { - return index; - } + segment_features = new Tensor3("float32", padded_data, [1, n_mels, num_segment_frames]); + } else { + segment_features = segment_input; + } + if (logits_processor) { + for (const proc of logits_processor) { + if ("begin_index" in proc) { + proc.begin_index = init_tokens.length; + } } - return -1; - } - - /** - * @param {number} index - * @param {number} iterSize - * @param {any} iterDims - * @returns {Tensor} - */ - _subarray(index, iterSize, iterDims) { - const o1 = index * iterSize; - const o2 = (index + 1) * iterSize; - - // We use subarray if available (typed array), otherwise we use slice (normal array) - const data = - ('subarray' in this.data) - ? this.data.subarray(o1, o2) - : this.data.slice(o1, o2); - return new Tensor(this.type, data, iterDims); - } - - /** - * Returns the value of this tensor as a standard JavaScript Number. This only works - * for tensors with one element. For other cases, see `Tensor.tolist()`. - * @returns {number|bigint} The value of this tensor as a standard JavaScript Number. - * @throws {Error} If the tensor has more than one element. - */ - item() { - const this_data = this.data; - if (this_data.length !== 1) { - throw new Error(`a Tensor with ${this_data.length} elements cannot be converted to Scalar`); + } + const outputs = ( + /** @type {any} */ + await super.generate({ + inputs: segment_features, + generation_config, + logits_processor, + decoder_input_ids: init_tokens, + ...kwargs + }) + ); + const raw_sequence = return_token_timestamps ? outputs.sequences : ( + /** @type {Tensor} */ + outputs + ); + const generated_tokens = raw_sequence[0].tolist().map(Number).slice(init_tokens.length); + let seek_token_timestamps; + if (return_token_timestamps) { + outputs["token_timestamps"] = this._extract_token_timestamps( + outputs, + generation_config.alignment_heads, + Math.floor((seek_end - seek) / input_stride), + 0.02, + init_tokens.length + ); + const time_offset = seek / input_stride * 0.02; + seek_token_timestamps = outputs.token_timestamps[0].tolist().slice(init_tokens.length).map((t) => t + time_offset); + } + if (generated_tokens.length > 0 && generated_tokens.at(-1) === eos_token_id) { + generated_tokens.pop(); + } + if (generated_tokens.length === 0) { + break; + } + const is_timestamp = generated_tokens.map((t) => t >= timestamp_begin); + const single_timestamp_ending = generated_tokens.length >= 2 && is_timestamp[generated_tokens.length - 1] && !is_timestamp[generated_tokens.length - 2]; + const segment_boundary_indices = []; + for (let i = 0; i < generated_tokens.length - 1; ++i) { + if (is_timestamp[i] && is_timestamp[i + 1]) { + segment_boundary_indices.push(i + 1); + } + } + let segment_offset; + let tokens_to_keep = generated_tokens.length; + if (segment_boundary_indices.length > 0) { + if (single_timestamp_ending) { + segment_offset = seek_end - seek; + } else { + const last_boundary = segment_boundary_indices.at(-1); + const last_ts_pos = generated_tokens[last_boundary - 1] - timestamp_begin; + segment_offset = last_ts_pos * input_stride; + tokens_to_keep = last_boundary; + } + } else { + segment_offset = seek_end - seek; + } + const timestamp_offset = Math.floor(seek / input_stride); + const max_timestamp_token = timestamp_begin + 1500; + for (let i = 0; i < tokens_to_keep; ++i) { + if (generated_tokens[i] >= timestamp_begin) { + generated_tokens[i] = Math.min(generated_tokens[i] + timestamp_offset, max_timestamp_token); } - return this_data[0]; + } + allTokens.push(...generated_tokens.slice(0, tokens_to_keep)); + if (seek_token_timestamps) { + allTokenTimestamps.push(...seek_token_timestamps.slice(0, tokens_to_keep)); + } + seek += segment_offset; + } + allTokens.push(eos_token_id); + const full_sequence = [...init_tokens, ...allTokens]; + if (return_token_timestamps) { + const sequences = new Tensor3("int64", full_sequence.map(BigInt), [1, full_sequence.length]); + const full_timestamps = [...new Array(init_tokens.length).fill(0), ...allTokenTimestamps, 0]; + const token_timestamps = new Tensor3("float32", new Float32Array(full_timestamps), [ + 1, + full_timestamps.length + ]); + return { sequences, token_timestamps }; } - - /** - * Convert tensor data to a n-dimensional JS list - * @returns {Array} - */ - tolist() { - return reshape(this.data, this.dims) + return new Tensor3("int64", full_sequence.map(BigInt), [1, full_sequence.length]); + } + /** + * Calculates token-level timestamps using the encoder-decoder cross-attentions and + * dynamic time-warping (DTW) to map each output token to a position in the input audio. + * If `num_frames` is specified, the encoder-decoder cross-attentions will be cropped before applying DTW. + * @param {Object} generate_outputs Outputs generated by the model + * @param {Tensor[][]} generate_outputs.cross_attentions The cross attentions output by the model + * @param {Tensor} generate_outputs.sequences The sequences output by the model + * @param {number[][]} alignment_heads Alignment heads of the model + * @param {number} [num_frames=null] Number of frames in the input audio. + * @param {number} [time_precision=0.02] Precision of the timestamps in seconds + * @param {number} [num_input_ids=0] Number of decoder input ids (prefix tokens) to skip in DTW + * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token + */ + _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02, num_input_ids = 0) { + if (!generate_outputs.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`." + ); } - - /** - * Return a new Tensor with the sigmoid function applied to each element. - * @returns {Tensor} The tensor with the sigmoid function applied. - */ - sigmoid() { - return this.clone().sigmoid_(); + if (num_frames == null) { + logger.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)." + ); } - - /** - * Applies the sigmoid function to the tensor in place. - * @returns {Tensor} Returns `this`. - */ - sigmoid_() { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] = 1 / (1 + Math.exp(-this_data[i])); + let median_filter_width = this.config.median_filter_width; + if (median_filter_width === void 0) { + logger.warn("Model config has no `median_filter_width`, using default value of 7."); + median_filter_width = 7; + } + const batch = generate_outputs.cross_attentions; + const cross_attentions = Array.from( + // @ts-expect-error TS2339 + { length: this.config.decoder_layers }, + // Concatenate the cross attentions for each layer across sequence length dimension. + (_, i) => cat( + batch.map((x) => x[i]), + 2 + ) + ); + const weights = stack( + alignment_heads.map(([l, h]) => { + if (l >= cross_attentions.length) { + throw new Error( + `Layer index ${l} is out of bounds for cross attentions (length ${cross_attentions.length}).` + ); + } + return num_frames ? cross_attentions[l].slice(null, h, null, [0, num_frames]) : cross_attentions[l].slice(null, h); + }) + ).permute(1, 0, 2, 3); + const [std, calculatedMean] = std_mean(weights, -2, 0, true); + const smoothedWeights = weights.clone(); + for (let a = 0; a < smoothedWeights.dims[0]; ++a) { + const aTensor = smoothedWeights[a]; + for (let b = 0; b < aTensor.dims[0]; ++b) { + const bTensor = aTensor[b]; + const stdTensorData = std[a][b][0].data; + const meanTensorData = calculatedMean[a][b][0].data; + for (let c = 0; c < bTensor.dims[0]; ++c) { + let cTensorData = bTensor[c].data; + for (let d = 0; d < cTensorData.length; ++d) { + cTensorData[d] = (cTensorData[d] - meanTensorData[d]) / stdTensorData[d]; + } + cTensorData.set(medianFilter(cTensorData, median_filter_width)); } - return this; - } - - /** - * Return a new Tensor with a callback function applied to each element. - * @param {Function} callback - The function to apply to each element. It should take three arguments: - * the current element, its index, and the tensor's data array. - * @returns {Tensor} A new Tensor with the callback function applied to each element. - */ - map(callback) { - return this.clone().map_(callback); + } } - - /** - * Apply a callback function to each element of the tensor in place. - * @param {Function} callback - The function to apply to each element. It should take three arguments: - * the current element, its index, and the tensor's data array. - * @returns {Tensor} Returns `this`. - */ - map_(callback) { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] = callback(this_data[i], i, this_data); + const croppedWeights = num_input_ids > 0 ? smoothedWeights.slice(null, null, [num_input_ids, smoothedWeights.dims[2]], null) : smoothedWeights; + const batchedMatrices = [mean(croppedWeights, 1)]; + const timestampsShape = generate_outputs.sequences.dims; + const timestamps = new Tensor3( + "float32", + new Float32Array(timestampsShape[0] * timestampsShape[1]), + timestampsShape + ); + for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) { + const matrix = batchedMatrices[batch_idx].neg().squeeze_(0); + const [text_indices, time_indices] = dynamic_time_warping(matrix.tolist()); + const diffs = Array.from( + { length: text_indices.length - 1 }, + (v, i) => text_indices[i + 1] - text_indices[i] + ); + const jumps = mergeArrays([1], diffs).map((x) => !!x); + const jump_times = []; + for (let i = 0; i < jumps.length; ++i) { + if (jumps[i]) { + jump_times.push(time_indices[i] * time_precision); } - return this; + } + const padded = new Array(num_input_ids).fill(0); + padded.push(...jump_times); + if (jump_times.length > 0) { + padded.push(jump_times.at(-1)); + } + timestamps[batch_idx].data.set(padded); } + return timestamps; + } +}; +var LiteWhisperForConditionalGeneration = class extends WhisperForConditionalGeneration { +}; - /** - * Return a new Tensor with every element multiplied by a constant. - * @param {number} val The value to multiply by. - * @returns {Tensor} The new tensor. - */ - mul(val) { - return this.clone().mul_(val); - } +// src/models/xlm/modeling_xlm.js +var XLMPreTrainedModel = class extends PreTrainedModel { +}; +var XLMModel = class extends XLMPreTrainedModel { +}; +var XLMWithLMHeadModel = class extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var XLMForSequenceClassification = class extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var XLMForTokenClassification = class extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var XLMForQuestionAnswering = class extends XLMPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - /** - * Multiply the tensor by a constant in place. - * @param {number} val The value to multiply by. - * @returns {Tensor} Returns `this`. - */ - mul_(val) { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] *= val; - } - return this; - } +// src/models/xlm_roberta/modeling_xlm_roberta.js +var XLMRobertaPreTrainedModel = class extends PreTrainedModel { +}; +var XLMRobertaModel = class extends XLMRobertaPreTrainedModel { +}; +var XLMRobertaForMaskedLM = class extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new MaskedLMOutput(await super._call(model_inputs)); + } +}; +var XLMRobertaForSequenceClassification = class extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new SequenceClassifierOutput(await super._call(model_inputs)); + } +}; +var XLMRobertaForTokenClassification = class extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} An object containing the model's output logits for token classification. + */ + async _call(model_inputs) { + return new TokenClassifierOutput(await super._call(model_inputs)); + } +}; +var XLMRobertaForQuestionAnswering = class extends XLMRobertaPreTrainedModel { + /** + * Calls the model on new inputs. + * + * @param {Object} model_inputs The inputs to the model. + * @returns {Promise} returned object + */ + async _call(model_inputs) { + return new QuestionAnsweringModelOutput(await super._call(model_inputs)); + } +}; - /** - * Return a new Tensor with every element divided by a constant. - * @param {number} val The value to divide by. - * @returns {Tensor} The new tensor. - */ - div(val) { - return this.clone().div_(val); - } +// src/models/yolos/modeling_yolos.js +var YolosPreTrainedModel = class extends PreTrainedModel { +}; +var YolosModel = class extends YolosPreTrainedModel { +}; +var YolosForObjectDetection = class extends YolosPreTrainedModel { + /** + * @param {any} model_inputs + */ + async _call(model_inputs) { + return new YolosObjectDetectionOutput(await super._call(model_inputs)); + } +}; +var YolosObjectDetectionOutput = class extends ModelOutput { + /** + * @param {Object} output The output of the model. + * @param {Tensor} output.logits Classification logits (including no-object) for all queries. + * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). + * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). + */ + constructor({ logits, pred_boxes }) { + super(); + this.logits = logits; + this.pred_boxes = pred_boxes; + } +}; - /** - * Divide the tensor by a constant in place. - * @param {number} val The value to divide by. - * @returns {Tensor} Returns `this`. - */ - div_(val) { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] /= val; - } - return this; - } +// src/models/youtu/modeling_youtu.js +var YoutuPreTrainedModel = class extends PreTrainedModel { +}; +var YoutuModel = class extends YoutuPreTrainedModel { +}; +var YoutuForCausalLM = class extends YoutuPreTrainedModel { +}; - /** - * Return a new Tensor with every element added by a constant. - * @param {number} val The value to add by. - * @returns {Tensor} The new tensor. - */ - add(val) { - return this.clone().add_(val); - } +// src/models/zaya/modeling_zaya.js +var ZayaPreTrainedModel = class extends PreTrainedModel { +}; +var ZayaModel = class extends ZayaPreTrainedModel { +}; +var ZayaForCausalLM = class extends ZayaPreTrainedModel { +}; - /** - * Add the tensor by a constant in place. - * @param {number} val The value to add by. - * @returns {Tensor} Returns `this`. - */ - add_(val) { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] += val; - } - return this; - } +// src/models/registry.js +var MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ new Map([ + ["bert", "BertModel"], + ["eurobert", "EuroBertModel"], + ["neobert", "NeoBertModel"], + ["modernbert", "ModernBertModel"], + ["nomic_bert", "NomicBertModel"], + ["roformer", "RoFormerModel"], + ["electra", "ElectraModel"], + ["esm", "EsmModel"], + ["convbert", "ConvBertModel"], + ["camembert", "CamembertModel"], + ["deberta", "DebertaModel"], + ["deberta-v2", "DebertaV2Model"], + ["mpnet", "MPNetModel"], + ["albert", "AlbertModel"], + ["distilbert", "DistilBertModel"], + ["roberta", "RobertaModel"], + ["xlm", "XLMModel"], + ["xlm-roberta", "XLMRobertaModel"], + ["clap", "ClapModel"], + ["clip", "CLIPModel"], + ["clipseg", "CLIPSegModel"], + ["chinese_clip", "ChineseCLIPModel"], + ["siglip", "SiglipModel"], + ["jina_clip", "JinaCLIPModel"], + ["mobilebert", "MobileBertModel"], + ["squeezebert", "SqueezeBertModel"], + ["wav2vec2", "Wav2Vec2Model"], + ["wav2vec2-bert", "Wav2Vec2BertModel"], + ["unispeech", "UniSpeechModel"], + ["unispeech-sat", "UniSpeechSatModel"], + ["hubert", "HubertModel"], + ["wavlm", "WavLMModel"], + ["audio-spectrogram-transformer", "ASTModel"], + ["vits", "VitsModel"], + ["pyannote", "PyAnnoteModel"], + ["wespeaker-resnet", "WeSpeakerResNetModel"], + ["detr", "DetrModel"], + ["rt_detr", "RTDetrModel"], + ["rt_detr_v2", "RTDetrV2Model"], + ["rf_detr", "RFDetrModel"], + ["d_fine", "DFineModel"], + ["table-transformer", "TableTransformerModel"], + ["vit", "ViTModel"], + ["ijepa", "IJepaModel"], + ["pvt", "PvtModel"], + ["vit_msn", "ViTMSNModel"], + ["vit_mae", "ViTMAEModel"], + ["groupvit", "GroupViTModel"], + ["fastvit", "FastViTModel"], + ["mobilevit", "MobileViTModel"], + ["mobilevitv2", "MobileViTV2Model"], + ["owlvit", "OwlViTModel"], + ["owlv2", "Owlv2Model"], + ["beit", "BeitModel"], + ["deit", "DeiTModel"], + ["hiera", "HieraModel"], + ["convnext", "ConvNextModel"], + ["convnextv2", "ConvNextV2Model"], + ["dinov2", "Dinov2Model"], + ["dinov2_with_registers", "Dinov2WithRegistersModel"], + ["dinov3_vit", "DINOv3ViTModel"], + ["dinov3_convnext", "DINOv3ConvNextModel"], + ["resnet", "ResNetModel"], + ["swin", "SwinModel"], + ["swin2sr", "Swin2SRModel"], + ["donut-swin", "DonutSwinModel"], + ["yolos", "YolosModel"], + ["dpt", "DPTModel"], + ["glpn", "GLPNModel"], + ["hifigan", "SpeechT5HifiGan"], + ["efficientnet", "EfficientNetModel"], + ["decision_transformer", "DecisionTransformerModel"], + ["patchtst", "PatchTSTModel"], + ["patchtsmixer", "PatchTSMixerModel"], + ["mobilenet_v1", "MobileNetV1Model"], + ["mobilenet_v2", "MobileNetV2Model"], + ["mobilenet_v3", "MobileNetV3Model"], + ["mobilenet_v4", "MobileNetV4Model"], + ["maskformer", "MaskFormerModel"], + ["mgp-str", "MgpstrForSceneTextRecognition"], + ["style_text_to_speech_2", "StyleTextToSpeech2Model"], + ["openai_privacy_filter", "OpenAIPrivacyFilterModel"], + ["embedding_gemma2", "EmbeddingGemma2Model"] +]); +var MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ new Map([ + ["t5", "T5Model"], + ["longt5", "LongT5Model"], + ["mt5", "MT5Model"], + ["bart", "BartModel"], + ["mbart", "MBartModel"], + ["marian", "MarianModel"], + ["whisper", "WhisperModel"], + ["cohere_asr", "CohereAsrModel"], + ["m2m_100", "M2M100Model"], + ["blenderbot", "BlenderbotModel"], + ["blenderbot-small", "BlenderbotSmallModel"] +]); +var MODEL_MAPPING_NAMES_AUTO_ENCODER = /* @__PURE__ */ new Map([ + ["mimi", "MimiModel"], + ["dac", "DacModel"], + ["snac", "SnacModel"] +]); +var MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ new Map([ + ["bloom", "BloomModel"], + ["jais", "JAISModel"], + ["gpt2", "GPT2Model"], + ["gpt_oss", "GptOssModel"], + ["gptj", "GPTJModel"], + ["gpt_bigcode", "GPTBigCodeModel"], + ["gpt_neo", "GPTNeoModel"], + ["gpt_neox", "GPTNeoXModel"], + ["codegen", "CodeGenModel"], + ["llama", "LlamaModel"], + ["apertus", "ApertusModel"], + ["nanochat", "NanoChatModel"], + ["arcee", "ArceeModel"], + ["afmoe", "AfmoeModel"], + ["lfm2", "Lfm2Model"], + ["lfm2_moe", "Lfm2MoeModel"], + ["lfm3", "Lfm3Model"], + ["smollm3", "SmolLM3Model"], + ["exaone", "ExaoneModel"], + ["olmo", "OlmoModel"], + ["olmo2", "Olmo2Model"], + ["olmo3", "Olmo3Model"], + ["olmo_hybrid", "OlmoHybridModel"], + ["mobilellm", "MobileLLMModel"], + ["granite", "GraniteModel"], + ["granitemoehybrid", "GraniteMoeHybridModel"], + ["cohere", "CohereModel"], + ["cohere2", "Cohere2Model"], + ["gemma", "GemmaModel"], + ["gemma2", "Gemma2Model"], + ["vaultgemma", "VaultGemmaModel"], + ["gemma3_text", "Gemma3Model"], + ["helium", "HeliumModel"], + ["glm", "GlmModel"], + ["glm_moe_dsa", "GlmMoeDsaModel"], + ["openelm", "OpenELMModel"], + ["qwen2", "Qwen2Model"], + ["qwen2_moe", "Qwen2MoeModel"], + ["qwen3", "Qwen3Model"], + ["qwen3_moe", "Qwen3MoeModel"], + ["qwen3_next", "Qwen3NextModel"], + ["phi", "PhiModel"], + ["phi3", "Phi3Model"], + ["mpt", "MptModel"], + ["opt", "OPTModel"], + ["mistral", "MistralModel"], + ["mistral4", "Mistral4Model"], + ["ministral", "MinistralModel"], + ["ministral3", "Ministral3Model"], + ["ernie4_5", "Ernie4_5ForCausalLM"], + ["starcoder2", "Starcoder2Model"], + ["deepseek_v3", "DeepseekV3Model"], + ["deepseek_v4", "DeepseekV4Model"], + ["falcon", "FalconModel"], + ["falcon_h1", "FalconH1Model"], + ["nemotron_h", "NemotronHModel"], + ["solar_open", "SolarOpenModel"], + ["stablelm", "StableLmModel"], + ["modernbert-decoder", "ModernBertDecoderModel"], + ["hunyuan_v1_dense", "HunYuanDenseV1Model"], + ["youtu", "YoutuModel"], + ["zaya", "ZayaModel"], + ["hrm_text", "HrmTextModel"] +]); +var MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["speecht5", "SpeechT5ForSpeechToText"], + ["whisper", "WhisperForConditionalGeneration"], + ["lite-whisper", "LiteWhisperForConditionalGeneration"], + ["moonshine", "MoonshineForConditionalGeneration"], + ["cohere_asr", "CohereAsrForConditionalGeneration"] +]); +var MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([["speecht5", "SpeechT5ForTextToSpeech"]]); +var MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vits", "VitsModel"], + ["musicgen", "MusicgenForConditionalGeneration"], + ["supertonic", "SupertonicForConditionalGeneration"] +]); +var MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", "BertForSequenceClassification"], + ["eurobert", "EuroBertForSequenceClassification"], + ["neobert", "NeoBertForSequenceClassification"], + ["modernbert", "ModernBertForSequenceClassification"], + ["roformer", "RoFormerForSequenceClassification"], + ["electra", "ElectraForSequenceClassification"], + ["esm", "EsmForSequenceClassification"], + ["convbert", "ConvBertForSequenceClassification"], + ["camembert", "CamembertForSequenceClassification"], + ["deberta", "DebertaForSequenceClassification"], + ["deberta-v2", "DebertaV2ForSequenceClassification"], + ["mpnet", "MPNetForSequenceClassification"], + ["albert", "AlbertForSequenceClassification"], + ["distilbert", "DistilBertForSequenceClassification"], + ["roberta", "RobertaForSequenceClassification"], + ["xlm", "XLMForSequenceClassification"], + ["xlm-roberta", "XLMRobertaForSequenceClassification"], + ["bart", "BartForSequenceClassification"], + ["mbart", "MBartForSequenceClassification"], + ["mobilebert", "MobileBertForSequenceClassification"], + ["squeezebert", "SqueezeBertForSequenceClassification"] +]); +var MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", "BertForTokenClassification"], + ["eurobert", "EuroBertForTokenClassification"], + ["neobert", "NeoBertForTokenClassification"], + ["modernbert", "ModernBertForTokenClassification"], + ["roformer", "RoFormerForTokenClassification"], + ["electra", "ElectraForTokenClassification"], + ["esm", "EsmForTokenClassification"], + ["convbert", "ConvBertForTokenClassification"], + ["camembert", "CamembertForTokenClassification"], + ["deberta", "DebertaForTokenClassification"], + ["deberta-v2", "DebertaV2ForTokenClassification"], + ["mpnet", "MPNetForTokenClassification"], + ["distilbert", "DistilBertForTokenClassification"], + ["roberta", "RobertaForTokenClassification"], + ["xlm", "XLMForTokenClassification"], + ["xlm-roberta", "XLMRobertaForTokenClassification"], + ["openai_privacy_filter", "OpenAIPrivacyFilterForTokenClassification"] +]); +var MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["t5", "T5ForConditionalGeneration"], + ["longt5", "LongT5ForConditionalGeneration"], + ["mt5", "MT5ForConditionalGeneration"], + ["bart", "BartForConditionalGeneration"], + ["mbart", "MBartForConditionalGeneration"], + ["marian", "MarianMTModel"], + ["m2m_100", "M2M100ForConditionalGeneration"], + ["blenderbot", "BlenderbotForConditionalGeneration"], + ["blenderbot-small", "BlenderbotSmallForConditionalGeneration"] +]); +var MODEL_FOR_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bloom", "BloomForCausalLM"], + ["gpt2", "GPT2LMHeadModel"], + ["gpt_oss", "GptOssForCausalLM"], + ["jais", "JAISLMHeadModel"], + ["gptj", "GPTJForCausalLM"], + ["gpt_bigcode", "GPTBigCodeForCausalLM"], + ["gpt_neo", "GPTNeoForCausalLM"], + ["gpt_neox", "GPTNeoXForCausalLM"], + ["codegen", "CodeGenForCausalLM"], + ["llama", "LlamaForCausalLM"], + ["nanochat", "NanoChatForCausalLM"], + ["apertus", "ApertusForCausalLM"], + ["llama4_text", "Llama4ForCausalLM"], + ["arcee", "ArceeForCausalLM"], + ["afmoe", "AfmoeForCausalLM"], + ["lfm2", "Lfm2ForCausalLM"], + ["lfm2_moe", "Lfm2MoeForCausalLM"], + ["lfm3", "Lfm3ForCausalLM"], + ["smollm3", "SmolLM3ForCausalLM"], + ["exaone", "ExaoneForCausalLM"], + ["olmo", "OlmoForCausalLM"], + ["olmo2", "Olmo2ForCausalLM"], + ["olmo3", "Olmo3ForCausalLM"], + ["olmo_hybrid", "OlmoHybridForCausalLM"], + ["mobilellm", "MobileLLMForCausalLM"], + ["granite", "GraniteForCausalLM"], + ["granitemoehybrid", "GraniteMoeHybridForCausalLM"], + ["cohere", "CohereForCausalLM"], + ["cohere2", "Cohere2ForCausalLM"], + ["gemma", "GemmaForCausalLM"], + ["gemma2", "Gemma2ForCausalLM"], + ["vaultgemma", "VaultGemmaForCausalLM"], + ["gemma3_text", "Gemma3ForCausalLM"], + ["gemma3", "Gemma3ForCausalLM"], + ["helium", "HeliumForCausalLM"], + ["glm", "GlmForCausalLM"], + ["glm_moe_dsa", "GlmMoeDsaForCausalLM"], + ["openelm", "OpenELMForCausalLM"], + ["qwen2", "Qwen2ForCausalLM"], + ["qwen2_moe", "Qwen2MoeForCausalLM"], + ["qwen3", "Qwen3ForCausalLM"], + ["qwen3_moe", "Qwen3MoeForCausalLM"], + ["qwen3_next", "Qwen3NextForCausalLM"], + ["qwen2_vl", "Qwen2VLForCausalLM"], + ["qwen2_5_vl", "Qwen2_5_VLForCausalLM"], + ["qwen3_vl", "Qwen3VLForCausalLM"], + ["qwen3_vl_moe", "Qwen3VLMoeForCausalLM"], + ["qwen3_5", "Qwen3_5ForCausalLM"], + ["qwen3_5_text", "Qwen3_5ForCausalLM"], + ["qwen3_5_moe", "Qwen3_5MoeForCausalLM"], + ["gemma3n", "Gemma3nForCausalLM"], + ["gemma4", "Gemma4ForCausalLM"], + ["phi", "PhiForCausalLM"], + ["phi3", "Phi3ForCausalLM"], + ["mpt", "MptForCausalLM"], + ["opt", "OPTForCausalLM"], + ["mbart", "MBartForCausalLM"], + ["mistral", "MistralForCausalLM"], + ["mistral4", "Mistral4ForCausalLM"], + ["ministral", "MinistralForCausalLM"], + ["ministral3", "Ministral3ForCausalLM"], + ["ernie4_5", "Ernie4_5ForCausalLM"], + ["starcoder2", "Starcoder2ForCausalLM"], + ["deepseek_v3", "DeepseekV3ForCausalLM"], + ["deepseek_v4", "DeepseekV4ForCausalLM"], + ["falcon", "FalconForCausalLM"], + ["falcon_h1", "FalconH1ForCausalLM"], + ["nemotron_h", "NemotronHForCausalLM"], + ["trocr", "TrOCRForCausalLM"], + ["solar_open", "SolarOpenForCausalLM"], + ["stablelm", "StableLmForCausalLM"], + ["modernbert-decoder", "ModernBertDecoderForCausalLM"], + ["hunyuan_v1_dense", "HunYuanDenseV1ForCausalLM"], + ["youtu", "YoutuForCausalLM"], + ["zaya", "ZayaForCausalLM"], + ["hrm_text", "HrmTextForCausalLM"], + // Also image-text-to-text + ["phi3_v", "Phi3VForCausalLM"] +]); +var MODEL_FOR_MULTIMODALITY_MAPPING_NAMES = /* @__PURE__ */ new Map([["multi_modality", "MultiModalityCausalLM"]]); +var MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", "BertForMaskedLM"], + ["eurobert", "EuroBertForMaskedLM"], + ["neobert", "NeoBertForMaskedLM"], + ["modernbert", "ModernBertForMaskedLM"], + ["roformer", "RoFormerForMaskedLM"], + ["electra", "ElectraForMaskedLM"], + ["esm", "EsmForMaskedLM"], + ["convbert", "ConvBertForMaskedLM"], + ["camembert", "CamembertForMaskedLM"], + ["deberta", "DebertaForMaskedLM"], + ["deberta-v2", "DebertaV2ForMaskedLM"], + ["mpnet", "MPNetForMaskedLM"], + ["albert", "AlbertForMaskedLM"], + ["distilbert", "DistilBertForMaskedLM"], + ["roberta", "RobertaForMaskedLM"], + ["xlm", "XLMWithLMHeadModel"], + ["xlm-roberta", "XLMRobertaForMaskedLM"], + ["mobilebert", "MobileBertForMaskedLM"], + ["squeezebert", "SqueezeBertForMaskedLM"] +]); +var MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["bert", "BertForQuestionAnswering"], + ["neobert", "NeoBertForQuestionAnswering"], + ["roformer", "RoFormerForQuestionAnswering"], + ["electra", "ElectraForQuestionAnswering"], + ["convbert", "ConvBertForQuestionAnswering"], + ["camembert", "CamembertForQuestionAnswering"], + ["deberta", "DebertaForQuestionAnswering"], + ["deberta-v2", "DebertaV2ForQuestionAnswering"], + ["mpnet", "MPNetForQuestionAnswering"], + ["albert", "AlbertForQuestionAnswering"], + ["distilbert", "DistilBertForQuestionAnswering"], + ["roberta", "RobertaForQuestionAnswering"], + ["xlm", "XLMForQuestionAnswering"], + ["xlm-roberta", "XLMRobertaForQuestionAnswering"], + ["mobilebert", "MobileBertForQuestionAnswering"], + ["squeezebert", "SqueezeBertForQuestionAnswering"] +]); +var MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vision-encoder-decoder", "VisionEncoderDecoderModel"], + ["idefics3", "Idefics3ForConditionalGeneration"], + ["smolvlm", "SmolVLMForConditionalGeneration"] +]); +var MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["llava", "LlavaForConditionalGeneration"], + ["llava_onevision", "LlavaOnevisionForConditionalGeneration"], + ["moondream1", "Moondream1ForConditionalGeneration"], + ["florence2", "Florence2ForConditionalGeneration"], + ["qwen2_vl", "Qwen2VLForConditionalGeneration"], + ["qwen2_5_vl", "Qwen2_5_VLForConditionalGeneration"], + ["qwen3_vl", "Qwen3VLForConditionalGeneration"], + ["qwen3_vl_moe", "Qwen3VLMoeForConditionalGeneration"], + ["qwen3_5", "Qwen3_5ForConditionalGeneration"], + ["qwen3_5_moe", "Qwen3_5MoeForConditionalGeneration"], + ["lfm2_vl", "Lfm2VlForConditionalGeneration"], + ["lfm3_vl", "Lfm3VlForConditionalGeneration"], + ["idefics3", "Idefics3ForConditionalGeneration"], + ["smolvlm", "SmolVLMForConditionalGeneration"], + ["paligemma", "PaliGemmaForConditionalGeneration"], + ["llava_qwen2", "LlavaQwen2ForCausalLM"], + ["gemma3", "Gemma3ForConditionalGeneration"], + ["gemma3n", "Gemma3nForConditionalGeneration"], + ["gemma4", "Gemma4ForConditionalGeneration"], + ["mistral3", "Mistral3ForConditionalGeneration"], + ["lighton_ocr", "LightOnOcrForConditionalGeneration"], + ["glm_ocr", "GlmOcrForConditionalGeneration"] +]); +var MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["granite_speech", "GraniteSpeechForConditionalGeneration"], + ["ultravox", "UltravoxModel"], + ["voxtral", "VoxtralForConditionalGeneration"], + ["voxtral_realtime", "VoxtralRealtimeForConditionalGeneration"] +]); +var MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vision-encoder-decoder", "VisionEncoderDecoderModel"] +]); +var MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["vit", "ViTForImageClassification"], + ["ijepa", "IJepaForImageClassification"], + ["pvt", "PvtForImageClassification"], + ["vit_msn", "ViTMSNForImageClassification"], + ["fastvit", "FastViTForImageClassification"], + ["mobilevit", "MobileViTForImageClassification"], + ["mobilevitv2", "MobileViTV2ForImageClassification"], + ["beit", "BeitForImageClassification"], + ["deit", "DeiTForImageClassification"], + ["hiera", "HieraForImageClassification"], + ["convnext", "ConvNextForImageClassification"], + ["convnextv2", "ConvNextV2ForImageClassification"], + ["dinov2", "Dinov2ForImageClassification"], + ["dinov2_with_registers", "Dinov2WithRegistersForImageClassification"], + ["resnet", "ResNetForImageClassification"], + ["swin", "SwinForImageClassification"], + ["segformer", "SegformerForImageClassification"], + ["efficientnet", "EfficientNetForImageClassification"], + ["mobilenet_v1", "MobileNetV1ForImageClassification"], + ["mobilenet_v2", "MobileNetV2ForImageClassification"], + ["mobilenet_v3", "MobileNetV3ForImageClassification"], + ["mobilenet_v4", "MobileNetV4ForImageClassification"] +]); +var MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["detr", "DetrForObjectDetection"], + ["rt_detr", "RTDetrForObjectDetection"], + ["rt_detr_v2", "RTDetrV2ForObjectDetection"], + ["rf_detr", "RFDetrForObjectDetection"], + ["d_fine", "DFineForObjectDetection"], + ["table-transformer", "TableTransformerForObjectDetection"], + ["yolos", "YolosForObjectDetection"] +]); +var MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["owlvit", "OwlViTForObjectDetection"], + ["owlv2", "Owlv2ForObjectDetection"], + ["grounding-dino", "GroundingDinoForObjectDetection"] +]); +var MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + // TODO: Do not add new models here + ["detr", "DetrForSegmentation"], + ["clipseg", "CLIPSegForImageSegmentation"] +]); +var MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["segformer", "SegformerForSemanticSegmentation"], + ["sapiens", "SapiensForSemanticSegmentation"], + ["swin", "SwinForSemanticSegmentation"], + ["mobilenet_v1", "MobileNetV1ForSemanticSegmentation"], + ["mobilenet_v2", "MobileNetV2ForSemanticSegmentation"], + ["mobilenet_v3", "MobileNetV3ForSemanticSegmentation"], + ["mobilenet_v4", "MobileNetV4ForSemanticSegmentation"] +]); +var MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["detr", "DetrForSegmentation"], + ["maskformer", "MaskFormerForInstanceSegmentation"] +]); +var MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["sam", "SamModel"], + ["sam2", "Sam2Model"], + ["edgetam", "EdgeTamModel"], + ["sam3_tracker", "Sam3TrackerModel"] +]); +var MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["wav2vec2", "Wav2Vec2ForCTC"], + ["wav2vec2-bert", "Wav2Vec2BertForCTC"], + ["unispeech", "UniSpeechForCTC"], + ["unispeech-sat", "UniSpeechSatForCTC"], + ["wavlm", "WavLMForCTC"], + ["hubert", "HubertForCTC"], + ["parakeet_ctc", "ParakeetForCTC"] +]); +var MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["wav2vec2", "Wav2Vec2ForSequenceClassification"], + ["wav2vec2-bert", "Wav2Vec2BertForSequenceClassification"], + ["unispeech", "UniSpeechForSequenceClassification"], + ["unispeech-sat", "UniSpeechSatForSequenceClassification"], + ["wavlm", "WavLMForSequenceClassification"], + ["hubert", "HubertForSequenceClassification"], + ["audio-spectrogram-transformer", "ASTForAudioClassification"] +]); +var MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = /* @__PURE__ */ new Map([["wavlm", "WavLMForXVector"]]); +var MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["unispeech-sat", "UniSpeechSatForAudioFrameClassification"], + ["wavlm", "WavLMForAudioFrameClassification"], + ["wav2vec2", "Wav2Vec2ForAudioFrameClassification"], + ["pyannote", "PyAnnoteForAudioFrameClassification"] +]); +var MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([["vitmatte", "VitMatteForImageMatting"]]); +var MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["patchtst", "PatchTSTForPrediction"], + ["patchtsmixer", "PatchTSMixerForPrediction"] +]); +var MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([["swin2sr", "Swin2SRForImageSuperResolution"]]); +var MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["chmv2", "CHMv2ForDepthEstimation"], + ["dpt", "DPTForDepthEstimation"], + ["depth_anything", "DepthAnythingForDepthEstimation"], + ["glpn", "GLPNForDepthEstimation"], + ["sapiens", "SapiensForDepthEstimation"], + ["depth_pro", "DepthProForDepthEstimation"], + ["metric3d", "Metric3DForDepthEstimation"], + ["metric3dv2", "Metric3Dv2ForDepthEstimation"] +]); +var MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([["sapiens", "SapiensForNormalEstimation"]]); +var MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([["vitpose", "VitPoseForPoseEstimation"]]); +var MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = /* @__PURE__ */ new Map([ + ["clip", "CLIPVisionModelWithProjection"], + ["siglip", "SiglipVisionModel"], + ["jina_clip", "JinaCLIPVisionModel"] +]); +var MODEL_CLASS_TYPE_MAPPING = [ + // MODEL_MAPPING_NAMES: + [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly], + [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder], + [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnlyWithoutHead], + [MODEL_MAPPING_NAMES_AUTO_ENCODER, MODEL_TYPES.AutoEncoder], + [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.DecoderOnly], + [MODEL_FOR_MULTIMODALITY_MAPPING_NAMES, MODEL_TYPES.MultiModality], + [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq], + [MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.ImageTextToText], + [MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES, MODEL_TYPES.AudioTextToText], + [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TIME_SERIES_PREDICTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration], + [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq], + [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly], + // Custom: + [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly] +]; +for (const [mappings, type] of MODEL_CLASS_TYPE_MAPPING) { + for (const name of mappings.values()) { + MODEL_TYPE_MAPPING.set(name, type); + const model = models_exports[name]; + MODEL_CLASS_TO_NAME_MAPPING.set(model, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, model); + } +} +var CUSTOM_MAPPING = [ + // OVERRIDE: + // TODO: Refactor to allow class to specify model + ["MusicgenForConditionalGeneration", MusicgenForConditionalGeneration, MODEL_TYPES.Musicgen], + ["Phi3VForCausalLM", Phi3VForCausalLM, MODEL_TYPES.Phi3V], + ["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly], + ["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly], + ["JinaCLIPTextModel", JinaCLIPTextModel, MODEL_TYPES.EncoderOnly], + ["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly], + ["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly], + ["DacEncoderModel", DacEncoderModel, MODEL_TYPES.EncoderOnly], + ["DacDecoderModel", DacDecoderModel, MODEL_TYPES.EncoderOnly], + ["MimiEncoderModel", MimiEncoderModel, MODEL_TYPES.EncoderOnly], + ["MimiDecoderModel", MimiDecoderModel, MODEL_TYPES.EncoderOnly], + ["SnacEncoderModel", SnacEncoderModel, MODEL_TYPES.EncoderOnly], + ["SnacDecoderModel", SnacDecoderModel, MODEL_TYPES.EncoderOnly], + [ + "Gemma3nForConditionalGeneration", + Gemma3nForConditionalGeneration, + MODEL_TYPES.ImageAudioTextToText + ], + [ + "Gemma4ForConditionalGeneration", + Gemma4ForConditionalGeneration, + MODEL_TYPES.ImageAudioTextToText + ], + ["SupertonicForConditionalGeneration", SupertonicForConditionalGeneration, MODEL_TYPES.Supertonic], + ["ChatterboxModel", ChatterboxModel, MODEL_TYPES.Chatterbox], + ["EmbeddingGemma2Model", EmbeddingGemma2Model, MODEL_TYPES.MultimodalEncoder], + [ + "VoxtralRealtimeForConditionalGeneration", + VoxtralRealtimeForConditionalGeneration, + MODEL_TYPES.VoxtralRealtime + ] +]; +for (const [name, model, type] of CUSTOM_MAPPING) { + MODEL_TYPE_MAPPING.set(name, type); + MODEL_CLASS_TO_NAME_MAPPING.set(model, name); + MODEL_NAME_TO_CLASS_MAPPING.set(name, model); +} +var CUSTOM_ARCHITECTURES_MAPPING = /* @__PURE__ */ new Map([ + ["modnet", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], + ["birefnet", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], + ["isnet", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES], + ["ben", MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES] +]); +for (const [name, mapping] of CUSTOM_ARCHITECTURES_MAPPING.entries()) { + mapping.set(name, "PreTrainedModel"); + MODEL_TYPE_MAPPING.set(name, MODEL_TYPES.EncoderOnly); + MODEL_NAME_TO_CLASS_MAPPING.set(name, PreTrainedModel); +} +var CUSTOM_ARCHITECTURES = new Set(CUSTOM_ARCHITECTURES_MAPPING.keys()); +MODEL_TYPE_MAPPING.set("PreTrainedModel", MODEL_TYPES.EncoderOnly); +MODEL_CLASS_TO_NAME_MAPPING.set(PreTrainedModel, "PreTrainedModel"); +var MODEL_MAPPINGS = { + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, + MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, + MODEL_FOR_MASKED_LM_MAPPING_NAMES, + MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, + MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, + MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, + MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, + MODEL_FOR_CTC_MAPPING_NAMES, + MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, + MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, + MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, + MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, + MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, + MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES, + MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES, + MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, + MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, + MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, + MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES +}; +registerTaskMappings(MODEL_MAPPINGS); - /** - * Return a new Tensor with every element subtracted by a constant. - * @param {number} val The value to subtract by. - * @returns {Tensor} The new tensor. - */ - sub(val) { - return this.clone().sub_(val); +// src/models/auto/modeling_auto.js +var PretrainedMixin = class { + /** + * Mapping from model type to model class. + * @type {Map[]} + */ + static MODEL_CLASS_MAPPINGS = null; + /** + * Whether to attempt to instantiate the base class (`PretrainedModel`) if + * the model type is not found in the mapping. + */ + static BASE_IF_FAIL = false; + /** + * Check whether this AutoModel class supports a given model type. + * @param {string} model_type The model type from config (e.g., 'bert', 'whisper'). + * @returns {boolean} Whether this class can handle the given model type. + */ + static supports(model_type) { + if (!this.MODEL_CLASS_MAPPINGS) return false; + for (const mapping of this.MODEL_CLASS_MAPPINGS) { + if (mapping.has(model_type)) return true; } - - /** - * Subtract the tensor by a constant in place. - * @param {number} val The value to subtract by. - * @returns {Tensor} Returns `this`. - */ - sub_(val) { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] -= val; + return this.BASE_IF_FAIL; + } + /** @type {typeof PreTrainedModel.from_pretrained} */ + static async from_pretrained(pretrained_model_name_or_path, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + model_file_name = null, + subfolder = "onnx", + device = null, + dtype = null, + use_external_data_format = null, + session_options = {} + } = {}) { + const options = { + progress_callback, + config, + cache_dir, + local_files_only, + revision, + model_file_name, + subfolder, + device, + dtype, + use_external_data_format, + session_options + }; + options.config = await AutoConfig.from_pretrained(pretrained_model_name_or_path, options); + if (!this.MODEL_CLASS_MAPPINGS) { + throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name); + } + const { model_type } = options.config; + for (const MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) { + let modelInfo = MODEL_CLASS_MAPPING.get(model_type); + if (!modelInfo) { + for (const cls of MODEL_CLASS_MAPPING.values()) { + if (cls[0] === model_type) { + modelInfo = cls; + break; + } } - return this; + if (!modelInfo) continue; + } + return await models_exports[modelInfo].from_pretrained(pretrained_model_name_or_path, options); } - - /** - * Creates a deep copy of the current Tensor. - * @returns {Tensor} A new Tensor with the same type, data, and dimensions as the original. - */ - clone() { - return new Tensor(this.type, this.data.slice(), this.dims.slice()); + if (this.BASE_IF_FAIL) { + if (!CUSTOM_ARCHITECTURES.has(model_type)) { + logger.warn(`Unknown model class "${model_type}", attempting to construct from base class.`); + } + return await PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options); + } else { + throw Error(`Unsupported model type: ${model_type}`); } + } +}; +var AutoModel = class extends PretrainedMixin { + /** + * @internal + * @type {Map[]} + */ + // @ts-ignore + static MODEL_CLASS_MAPPINGS = MODEL_CLASS_TYPE_MAPPING.map((x) => x[0]); + static BASE_IF_FAIL = true; +}; +var AutoModelForSequenceClassification = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]; +}; +var AutoModelForTokenClassification = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]; +}; +var AutoModelForSeq2SeqLM = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]; +}; +var AutoModelForSpeechSeq2Seq = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]; +}; +var AutoModelForTextToSpectrogram = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]; +}; +var AutoModelForTextToWaveform = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]; +}; +var AutoModelForCausalLM = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]; +}; +var AutoModelForMaskedLM = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_MASKED_LM_MAPPING_NAMES]; +}; +var AutoModelForQuestionAnswering = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]; +}; +var AutoModelForVision2Seq = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]; +}; +var AutoModelForImageClassification = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]; +}; +var AutoModelForImageSegmentation = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]; +}; +var AutoModelForSemanticSegmentation = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]; +}; +var AutoModelForUniversalSegmentation = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]; +}; +var AutoModelForObjectDetection = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]; +}; +var AutoModelForZeroShotObjectDetection = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]; +}; +var AutoModelForMaskGeneration = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]; +}; +var AutoModelForCTC = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_CTC_MAPPING_NAMES]; +}; +var AutoModelForAudioClassification = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]; +}; +var AutoModelForXVector = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]; +}; +var AutoModelForAudioFrameClassification = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]; +}; +var AutoModelForDocumentQuestionAnswering = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]; +}; +var AutoModelForImageMatting = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]; +}; +var AutoModelForImageToImage = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]; +}; +var AutoModelForDepthEstimation = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]; +}; +var AutoModelForNormalEstimation = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]; +}; +var AutoModelForPoseEstimation = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]; +}; +var AutoModelForImageFeatureExtraction = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]; +}; +var AutoModelForImageTextToText = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]; +}; +var AutoModelForAudioTextToText = class extends PretrainedMixin { + static MODEL_CLASS_MAPPINGS = [MODEL_MAPPINGS.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]; +}; - /** - * Performs a slice operation on the Tensor along specified dimensions. - * - * Consider a Tensor that has a dimension of [4, 7]: - * ``` - * [ 1, 2, 3, 4, 5, 6, 7] - * [ 8, 9, 10, 11, 12, 13, 14] - * [15, 16, 17, 18, 19, 20, 21] - * [22, 23, 24, 25, 26, 27, 28] - * ``` - * We can slice against the two dims of row and column, for instance in this - * case we can start at the second element, and return to the second last, - * like this: - * ``` - * tensor.slice([1, -1], [1, -1]); - * ``` - * which would return: - * ``` - * [ 9, 10, 11, 12, 13 ] - * [ 16, 17, 18, 19, 20 ] - * ``` - * - * @param {...(number|number[]|null)} slices The slice specifications for each dimension. - * - If a number is given, then a single element is selected. - * - If an array of two numbers is given, then a range of elements [start, end (exclusive)] is selected. - * - If null is given, then the entire dimension is selected. - * @returns {Tensor} A new Tensor containing the selected elements. - * @throws {Error} If the slice input is invalid. - */ - slice(...slices) { - // This allows for slicing with ranges and numbers - const newTensorDims = []; - const newOffsets = []; - - // slices is an array of numbers or arrays of numbers - // e.g., slices = [0, [1, 3], null, [0, 3]] - for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) { - let slice = slices[sliceIndex]; - - if (slice === null || slice === undefined) { - // null or undefined means take the whole dimension - newOffsets.push([0, this.dims[sliceIndex]]); - newTensorDims.push(this.dims[sliceIndex]); - - } else if (typeof slice === 'number') { - slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex); - - // A number means take a single element - newOffsets.push([slice, slice + 1]); - - } else if (Array.isArray(slice) && slice.length === 2) { - // An array of length 2 means take a range of elements - let [start, end] = slice; - start = start === null - ? 0 - : safeIndex(start, this.dims[sliceIndex], sliceIndex, false); - end = end === null - ? this.dims[sliceIndex] - : safeIndex(end, this.dims[sliceIndex], sliceIndex, false); - - if (start > end) { - throw new Error(`Invalid slice: ${slice}`); - } - - const offsets = [ - Math.max(start, 0), - Math.min(end, this.dims[sliceIndex]) - ]; - - newOffsets.push(offsets); - newTensorDims.push(offsets[1] - offsets[0]); - - } else { - throw new Error(`Invalid slice: ${slice}`); - } - } - - const newDims = newOffsets.map(([start, end]) => end - start); - const newBufferSize = newDims.reduce((a, b) => a * b); - - const this_data = this.data; - // Allocate memory - // @ts-ignore - const data = new this_data.constructor(newBufferSize); - - // Precompute strides - const stride = this.stride(); - - // Detect if the slice is contiguous - let isContiguous = true; - for (let i = 1; i < newDims.length; ++i) { - if (newOffsets[i][0] !== 0 || newOffsets[i][1] !== this.dims[i]) { - isContiguous = false; - break; - } - } - - if (isContiguous) { - // Perform bulk copy for contiguous slices to improve performance - const start = newOffsets[0][0] * stride[0]; - const end = newOffsets[0][1] * stride[0]; - - if (ArrayBuffer.isView(this_data)) { - // If this.data is a TypedArray, use subarray - // @ts-ignore - data.set(this_data.subarray(start, end)); - } else if (Array.isArray(this_data)) { - // If this.data is a plain array, use slice - const slicedData = this_data.slice(start, end); - for (let i = 0; i < slicedData.length; ++i) { - data[i] = slicedData[i]; - } - } else { - throw new Error("Unsupported data type for slicing"); - } - } else { - // Fallback to manual copying for non-contiguous slices - for (let i = 0; i < newBufferSize; ++i) { - let originalIndex = 0; - for (let j = newDims.length - 1, num = i; j >= 0; --j) { - const size = newDims[j]; - originalIndex += ((num % size) + newOffsets[j][0]) * stride[j]; - num = Math.floor(num / size); - } - data[i] = this_data[originalIndex]; - } - } +// src/pipelines/_base.js +async function prepareImages(images) { + if (!Array.isArray(images)) { + images = [images]; + } + return await Promise.all(images.map((x) => RawImage.read(x))); +} +async function prepareAudios(audios, sampling_rate) { + if (!Array.isArray(audios)) { + audios = [audios]; + } + return await Promise.all( + audios.map((x) => { + if (typeof x === "string" || x instanceof URL) { + return read_audio(x, sampling_rate); + } else if (x instanceof Float64Array) { + return new Float32Array(x); + } + return x; + }) + ); +} +function get_bounding_box(box, asInteger) { + if (asInteger) { + box = box.map((x) => x | 0); + } + const [xmin, ymin, xmax, ymax] = box; + return { xmin, ymin, xmax, ymax }; +} +var Pipeline = class extends Callable { + /** + * Create a new Pipeline. + * @param {Object} options An object containing the following properties: + * @param {string} [options.task] The task of the pipeline. Useful for specifying subtasks. + * @param {PreTrainedModel} [options.model] The model used by the pipeline. + * @param {PreTrainedTokenizer} [options.tokenizer=null] The tokenizer used by the pipeline (if any). + * @param {Processor} [options.processor=null] The processor used by the pipeline (if any). + */ + constructor({ task, model, tokenizer = null, processor = null }) { + super(); + this.task = task; + this.model = model; + this.tokenizer = tokenizer; + this.processor = processor; + } + /** @type {DisposeType} */ + async dispose() { + await this.model.dispose(); + } +}; - return new Tensor(this.type, data, newTensorDims); +// src/pipelines/text-classification.js +var TextClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TextClassificationPipelineType} */ +Pipeline { + async _call(texts, { top_k = 1 } = {}) { + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const outputs = await this.model(model_inputs); + const { problem_type, id2label } = this.model.config; + const function_to_apply = problem_type === "multi_label_classification" ? (batch) => batch.sigmoid() : (batch) => new Tensor3("float32", softmax(batch.data), batch.dims); + const toReturn = []; + for (const batch of outputs.logits) { + const output = function_to_apply(batch); + const scores = await topk(output, top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + const vals = indices.map((x, i) => ({ + label: id2label ? id2label[x] : `LABEL_${x}`, + score: values[i] + })); + if (top_k === 1) { + toReturn.push(...vals); + } else { + toReturn.push(vals); + } } + return Array.isArray(texts) || top_k === 1 ? toReturn : toReturn[0]; + } +}; - /** - * Return a permuted version of this Tensor, according to the provided dimensions. - * @param {...number} dims Dimensions to permute. - * @returns {Tensor} The permuted tensor. - */ - permute(...dims) { - return permute(this, dims); +// src/pipelines/token-classification.js +var TokenClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TokenClassificationPipelineType} */ +Pipeline { + async _call(texts, { ignore_labels = ["O"], aggregation_strategy = "none" } = {}) { + if (aggregation_strategy !== "none" && aggregation_strategy !== "simple") { + throw new Error( + `Invalid aggregation_strategy: "${aggregation_strategy}". Must be one of "none" or "simple".` + ); } - - // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute() - transpose(...dims) { - return this.permute(...dims); + const isBatched = Array.isArray(texts); + const model_inputs = this.tokenizer(isBatched ? texts : [texts], { + padding: true, + truncation: true + }); + const outputs = await this.model(model_inputs); + const logits = outputs.logits; + const id2label = this.model.config.id2label; + const toReturn = []; + for (let i = 0; i < logits.dims[0]; ++i) { + const ids = model_inputs.input_ids[i].tolist(); + const batch = logits[i]; + const tokens = []; + for (let j2 = 0; j2 < batch.dims[0]; ++j2) { + const tokenData = batch[j2]; + const topScoreIndex = max(tokenData.data)[1]; + const entity = id2label ? id2label[topScoreIndex] : `LABEL_${topScoreIndex}`; + if (ignore_labels.includes(entity)) continue; + const word = this.tokenizer.decode([ids[j2]], { skip_special_tokens: true }); + if (word === "") continue; + const scores = softmax(tokenData.data); + tokens.push({ + entity, + score: scores[topScoreIndex], + index: j2, + word + // TODO: Add support for start and end + }); + } + toReturn.push(aggregation_strategy === "simple" ? groupEntities(tokens, ids, this.tokenizer) : tokens); } - - /** - * Returns the sum of each row of the input tensor in the given dimension dim. - * - * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced. - * @param {boolean} keepdim Whether the output tensor has `dim` retained or not. - * @returns The summed tensor - */ - sum(dim = null, keepdim = false) { - return this.norm(1, dim, keepdim); + return isBatched ? toReturn : toReturn[0]; + } +}; +function getTag(entity) { + const p = entity[0]; + return entity[1] === "-" && (p === "B" || p === "I" || p === "E" || p === "S") ? [p, entity.slice(2)] : ["I", entity]; +} +function groupEntities(tokens, ids, tokenizer) { + const groups = []; + let openTag = null; + for (let i = 0; i < tokens.length; ++i) { + const [prefix, tag] = getTag(tokens[i].entity); + const extend = openTag === tag && prefix !== "B" && prefix !== "S"; + if (extend) { + groups[groups.length - 1].end = i + 1; + if (prefix === "E") openTag = null; + } else { + groups.push({ tag, start: i, end: i + 1 }); + openTag = prefix === "S" ? null : tag; } - - /** - * Returns the matrix norm or vector norm of a given tensor. - * @param {number|string} [p='fro'] The order of norm - * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across. - * If dim is None, the norm will be calculated across all dimensions of input. - * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not. - * @returns {Tensor} The norm of the tensor. - */ - norm(p = 'fro', dim = null, keepdim = false) { - if (p === 'fro') { - // NOTE: Since we only support integer dims, Frobenius norm produces the same result as p=2. - p = 2; - } else if (typeof p === 'string') { - throw Error(`Unsupported norm: ${p}`); - } - - const this_data = this.data; - const fn = (a, b) => a + (b ** p); - - if (dim === null) { - // @ts-ignore - const val = this_data.reduce(fn, 0) ** (1 / p); - return new Tensor(this.type, [val], []); - } - - const [type, result, resultDims] = reduce_helper(fn, this, dim, keepdim); - - if (p !== 1) { - for (let i = 0; i < result.length; ++i) { - result[i] = result[i] ** (1 / p); - } - } - return new Tensor(type, result, resultDims); + } + return groups.map(({ tag, start, end }) => { + let scoreSum = 0; + const groupIds = []; + for (let i = start; i < end; ++i) { + scoreSum += tokens[i].score; + groupIds.push(ids[tokens[i].index]); } + return { + entity_group: tag, + score: scoreSum / (end - start), + word: tokenizer.decode(groupIds, { skip_special_tokens: true }) + }; + }); +} - /** - * Performs `L_p` normalization of inputs over specified dimension. Operates in place. - * @param {number} [p=2] The exponent value in the norm formulation - * @param {number} [dim=1] The dimension to reduce - * @returns {Tensor} `this` for operation chaining. - */ - normalize_(p = 2.0, dim = 1) { - dim = safeIndex(dim, this.dims.length); - - const norm = this.norm(p, dim, true); - - const this_data = this.data; - const norm_data = norm.data; - for (let i = 0; i < this_data.length; ++i) { - - // Calculate the index in the resulting array - let resultIndex = 0; - - for (let j = this.dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = this.dims[j]; - if (j !== dim) { - const index = num % size; - resultIndex += index * resultMultiplier; - resultMultiplier *= this.dims[j]; - } - num = Math.floor(num / size); - } - - // Divide by normalized value - this_data[i] /= norm_data[resultIndex]; +// src/pipelines/question-answering.js +var QuestionAnsweringPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => QuestionAnsweringPipelineType} */ +Pipeline { + async _call(question, context, { top_k = 1 } = {}) { + const inputs = this.tokenizer(question, { + text_pair: context, + padding: true, + truncation: true + }); + const isBatched = Array.isArray(question); + const { start_logits, end_logits } = await this.model(inputs); + const input_ids = inputs.input_ids.tolist(); + const attention_mask = inputs.attention_mask.tolist(); + const { all_special_ids, sep_token_id } = this.tokenizer; + const batchedResults = []; + for (let j2 = 0; j2 < start_logits.dims[0]; ++j2) { + const ids = input_ids[j2]; + const sepIndex = ids.findIndex( + (x) => ( + // We use == to match bigint with number + // @ts-ignore + x == sep_token_id + ) + ); + const start = start_logits[j2].tolist(); + const end = end_logits[j2].tolist(); + for (let i = 1; i < start.length; ++i) { + if (attention_mask[j2] == 0 || // is part of padding + i <= sepIndex || // is before the sep_token + all_special_ids.findIndex((x) => x == ids[i]) !== -1) { + start[i] = -Infinity; + end[i] = -Infinity; } - - return this; - } - - /** - * Performs `L_p` normalization of inputs over specified dimension. - * @param {number} [p=2] The exponent value in the norm formulation - * @param {number} [dim=1] The dimension to reduce - * @returns {Tensor} The normalized tensor. - */ - normalize(p = 2.0, dim = 1) { - return this.clone().normalize_(p, dim); - } - - /** - * Compute and return the stride of this tensor. - * Stride is the jump necessary to go from one element to the next one in the specified dimension dim. - * @returns {number[]} The stride of this tensor. - */ - stride() { - return dimsToStride(this.dims); + } + const start_scores = softmax(start).map((x, i) => [x, i]); + const end_scores = softmax(end).map((x, i) => [x, i]); + start_scores[0][0] = 0; + end_scores[0][0] = 0; + const options = product(start_scores, end_scores).filter((x) => x[0][1] <= x[1][1]).map((x) => [x[0][1], x[1][1], x[0][0] * x[1][0]]).sort((a, b) => b[2] - a[2]); + const sampleResults = []; + for (let k = 0; k < Math.min(options.length, top_k); ++k) { + const [start2, end2, score] = options[k]; + const answer_tokens = ids.slice(start2, end2 + 1); + const answer = this.tokenizer.decode(answer_tokens, { + skip_special_tokens: true + }); + sampleResults.push({ + answer, + score + }); + } + if (top_k === 1) { + batchedResults.push(...sampleResults); + } else { + batchedResults.push(sampleResults); + } } + return isBatched ? batchedResults : batchedResults[0]; + } +}; - /** - * Returns a tensor with all specified dimensions of input of size 1 removed. - * - * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. - * If you would like a copy, use `tensor.clone()` before squeezing. - * - * @param {number|number[]} [dim=null] If given, the input will be squeezed only in the specified dimensions. - * @returns {Tensor} The squeezed tensor - */ - squeeze(dim = null) { - return new Tensor( - this.type, - this.data, - calc_squeeze_dims(this.dims, dim) +// src/pipelines/fill-mask.js +var FillMaskPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => FillMaskPipelineType} */ +Pipeline { + async _call(texts, { top_k = 5 } = {}) { + const { mask_token_id, mask_token } = this.tokenizer; + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const { logits } = await this.model(model_inputs); + const toReturn = []; + const input_ids = model_inputs.input_ids.tolist(); + for (let i = 0; i < input_ids.length; ++i) { + const ids = input_ids[i]; + const mask_token_index = ids.findIndex( + (x) => ( + // We use == to match bigint with number + // @ts-ignore - TS2367: Intentional loose equality for bigint/number comparison + x == mask_token_id ) + ); + if (mask_token_index === -1) { + throw Error(`Mask token (${mask_token}) not found in text.`); + } + const itemLogits = logits[i][mask_token_index]; + const scores = await topk(new Tensor3("float32", softmax(itemLogits.data), itemLogits.dims), top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + toReturn.push( + indices.map((x, i2) => { + const sequence = ids.slice(); + sequence[mask_token_index] = x; + return { + score: values[i2], + token: Number(x), + token_str: this.tokenizer.decode([x]), + sequence: this.tokenizer.decode(sequence, { + skip_special_tokens: true + }) + }; + }) + ); } + return Array.isArray(texts) ? toReturn : toReturn[0]; + } +}; - /** - * In-place version of @see {@link Tensor.squeeze} - */ - squeeze_(dim = null) { - this.dims = calc_squeeze_dims(this.dims, dim); - return this; - } - - /** - * Returns a new tensor with a dimension of size one inserted at the specified position. - * - * NOTE: The returned tensor shares the same underlying data with this tensor. - * - * @param {number} dim The index at which to insert the singleton dimension - * @returns {Tensor} The unsqueezed tensor - */ - unsqueeze(dim = null) { - return new Tensor( - this.type, - this.data, - calc_unsqueeze_dims(this.dims, dim) - ); - } - - /** - * In-place version of @see {@link Tensor.unsqueeze} - */ - unsqueeze_(dim = null) { - this.dims = calc_unsqueeze_dims(this.dims, dim); - return this; - } - - /** - * In-place version of @see {@link Tensor.flatten} - */ - flatten_(start_dim = 0, end_dim = -1) { - // TODO validate inputs - end_dim = (end_dim + this.dims.length) % this.dims.length; - - let dimsToKeepBefore = this.dims.slice(0, start_dim); - let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1); - let dimsToKeepAfter = this.dims.slice(end_dim + 1); - - this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter] - return this; +// src/pipelines/text2text-generation.js +var Text2TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => Text2TextGenerationPipelineType} */ +Pipeline { + _default_generation_config = { + max_new_tokens: 256 + // do_sample: true, + // temperature: 0.7, + }; + /** @type {'generated_text'} */ + _key = "generated_text"; + /** @type {Text2TextGenerationPipelineCallback} */ + async _call(texts, generate_kwargs = {}) { + if (!Array.isArray(texts)) { + texts = [texts]; + } + if (this.model.config.prefix) { + texts = texts.map((x) => this.model.config.prefix + x); + } + const task_specific_params = this.model.config.task_specific_params; + if (task_specific_params && task_specific_params[this.task]) { + if (task_specific_params[this.task].prefix) { + texts = texts.map((x) => task_specific_params[this.task].prefix + x); + } } - - /** - * Flattens input by reshaping it into a one-dimensional tensor. - * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim` - * and ending with `end_dim` are flattened. The order of elements in input is unchanged. - * @param {number} start_dim the first dim to flatten - * @param {number} end_dim the last dim to flatten - * @returns {Tensor} The flattened tensor. - */ - flatten(start_dim = 0, end_dim = -1) { - return this.clone().flatten_(start_dim, end_dim); + const tokenizer = this.tokenizer; + const tokenizer_options = { + padding: true, + truncation: true + }; + let inputs; + if (this.task === "translation" && "_build_translation_inputs" in tokenizer) { + inputs = tokenizer._build_translation_inputs(texts, tokenizer_options, generate_kwargs); + } else { + inputs = tokenizer(texts, tokenizer_options); } + const outputTokenIds = await this.model.generate({ + ...inputs, + ...this._default_generation_config, + ...generate_kwargs + }); + return tokenizer.batch_decode( + /** @type {Tensor} */ + outputTokenIds, + { + skip_special_tokens: true + } + ).map((text) => ({ [this._key]: text })); + } +}; - /** - * Returns a new tensor with the same data as the `self` tensor but of a different `shape`. - * @param {...number} dims the desired size - * @returns {Tensor} The tensor with the same data but different shape - */ - view(...dims) { - // TODO: validate dims - let inferredIndex = -1; - for (let i = 0; i < dims.length; ++i) { - if (dims[i] === -1) { - if (inferredIndex !== -1) { - throw new Error("Only one dimension can be inferred"); - } - inferredIndex = i; - } - } +// src/pipelines/summarization.js +var SummarizationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => SummarizationPipelineType} */ +/** @type {any} */ +Text2TextGenerationPipeline { + /** @type {'summary_text'} */ + _key = "summary_text"; +}; - const this_data = this.data; - if (inferredIndex !== -1) { - // Some dimension must be inferred - const productOther = dims.reduce((product, curr, index) => { - return index !== inferredIndex ? product * curr : product - }, 1); +// src/pipelines/translation.js +var TranslationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TranslationPipelineType} */ +/** @type {any} */ +Text2TextGenerationPipeline { + /** @type {'translation_text'} */ + _key = "translation_text"; +}; - dims[inferredIndex] = this_data.length / productOther; +// src/pipelines/text-generation.js +function isChat(x) { + return Array.isArray(x) && x.every((x2) => "role" in x2 && "content" in x2); +} +var TextGenerationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => TextGenerationPipelineType} */ +Pipeline { + _default_generation_config = { + max_new_tokens: 256 + // do_sample: true, + // temperature: 0.7, + }; + /** + * @param {string | string[] | import('../tokenization_utils.js').Message[] | import('../tokenization_utils.js').Message[][]} texts + * @param {Partial} generate_kwargs + */ + async _call(texts, generate_kwargs = {}) { + const { + add_special_tokens: add_special_tokens_arg, + return_full_text: return_full_text_arg, + tools, + documents, + chat_template, + tokenizer_encode_kwargs, + ...generation_kwargs + } = generate_kwargs; + let isBatched = false; + let isChatInput = false; + let add_special_tokens = add_special_tokens_arg ?? (this.tokenizer.add_bos_token || this.tokenizer.add_eos_token) ?? false; + let tokenizer_kwargs = tokenizer_encode_kwargs; + let inputs; + if (typeof texts === "string") { + inputs = texts = [texts]; + } else if (Array.isArray(texts) && texts.every((x) => typeof x === "string")) { + isBatched = true; + inputs = /** @type {string[]} */ + texts; + } else { + if (isChat(texts)) { + texts = [ + /** @type {Chat} */ + texts + ]; + } else if (Array.isArray(texts) && texts.every(isChat)) { + isBatched = true; + } else { + throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats"); + } + isChatInput = true; + const chat_template_kwargs = { + tokenize: false, + add_generation_prompt: true, + ...pick({ tools, documents, chat_template }, ["tools", "documents", "chat_template"]), + ...tokenizer_kwargs + }; + inputs = /** @type {string[]} */ + /** @type {Chat[]} */ + texts.map( + (x) => ( + /** @type {string} */ + /** @type {unknown} */ + this.tokenizer.apply_chat_template(x, chat_template_kwargs) + ) + ); + add_special_tokens = false; + tokenizer_kwargs = void 0; + } + const return_full_text = isChatInput ? false : return_full_text_arg ?? true; + this.tokenizer.padding_side = "left"; + const text_inputs = this.tokenizer(inputs, { + add_special_tokens, + padding: true, + truncation: true, + ...tokenizer_kwargs + }); + const outputTokenIds = ( + /** @type {Tensor} */ + await this.model.generate({ + ...text_inputs, + ...this._default_generation_config, + ...generation_kwargs + }) + ); + const decoded = this.tokenizer.batch_decode(outputTokenIds, { + skip_special_tokens: true + }); + let promptLengths; + if (!return_full_text && text_inputs.input_ids.dims.at(-1) > 0) { + promptLengths = this.tokenizer.batch_decode(text_inputs.input_ids, { + skip_special_tokens: true + }).map((x) => x.length); + } + const toReturn = Array.from({ length: texts.length }, (_) => []); + for (let i = 0; i < decoded.length; ++i) { + const textIndex = Math.floor(i / outputTokenIds.dims[0] * texts.length); + if (promptLengths) { + decoded[i] = decoded[i].slice(promptLengths[textIndex]); + } + toReturn[textIndex].push( + /** @type {TextGenerationSingle} */ + { + generated_text: isChatInput ? [.../** @type {Chat[]} */ + texts[textIndex], { role: "assistant", content: decoded[i] }] : decoded[i] } - return new Tensor(this.type, this_data, dims); // NOTE: uses same underlying storage + ); } + return !isBatched && toReturn.length === 1 ? toReturn[0] : toReturn; + } +}; - neg_() { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] = -this_data[i]; - } - return this; +// src/pipelines/zero-shot-classification.js +var ZeroShotClassificationPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => ZeroShotClassificationPipelineType} */ +Pipeline { + /** + * Create a new ZeroShotClassificationPipeline. + * @param {TextPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + this.label2id = Object.fromEntries( + Object.entries( + /** @type {any} */ + this.model.config.label2id + ).map(([k, v]) => [k.toLowerCase(), v]) + ); + this.entailment_id = this.label2id["entailment"]; + if (this.entailment_id === void 0) { + logger.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."); + this.entailment_id = 2; } - neg() { - return this.clone().neg_(); + this.contradiction_id = this.label2id["contradiction"] ?? this.label2id["not_entailment"]; + if (this.contradiction_id === void 0) { + logger.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."); + this.contradiction_id = 0; } - - /** - * Computes input > val element-wise. - * @param {number} val The value to compare with. - * @returns {Tensor} A boolean tensor that is `true` where input is greater than other and `false` elsewhere. - */ - gt(val) { - const mask = new Uint8Array(this.data.length); - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - mask[i] = this_data[i] > val ? 1 : 0; - } - return new Tensor('bool', mask, this.dims); + } + async _call(texts, candidate_labels, { hypothesis_template = "This example is {}.", multi_label = false } = {}) { + const isBatched = Array.isArray(texts); + if (!isBatched) { + texts = [ + /** @type {string} */ + texts + ]; } - - /** - * Computes input < val element-wise. - * @param {number} val The value to compare with. - * @returns {Tensor} A boolean tensor that is `true` where input is less than other and `false` elsewhere. - */ - lt(val) { - const mask = new Uint8Array(this.data.length); - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - mask[i] = this_data[i] < val ? 1 : 0; - } - return new Tensor('bool', mask, this.dims); + if (!Array.isArray(candidate_labels)) { + candidate_labels = [candidate_labels]; } - - /** - * In-place version of @see {@link Tensor.clamp} - */ - clamp_(min, max) { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] = Math.min(Math.max(this_data[i], min), max); + const hypotheses = candidate_labels.map((x) => hypothesis_template.replace("{}", x)); + const softmaxEach = multi_label || candidate_labels.length === 1; + const toReturn = []; + for (const premise of texts) { + const entails_logits = []; + for (const hypothesis of hypotheses) { + const inputs = this.tokenizer(premise, { + text_pair: hypothesis, + padding: true, + truncation: true + }); + const outputs = await this.model(inputs); + if (softmaxEach) { + entails_logits.push([ + outputs.logits.data[this.contradiction_id], + outputs.logits.data[this.entailment_id] + ]); + } else { + entails_logits.push(outputs.logits.data[this.entailment_id]); } - return this; + } + const scores = softmaxEach ? entails_logits.map((x) => softmax(x)[1]) : softmax(entails_logits); + const scores_sorted = scores.map((x, i) => [x, i]).sort((a, b) => b[0] - a[0]); + toReturn.push({ + sequence: premise, + labels: scores_sorted.map((x) => candidate_labels[x[1]]), + scores: scores_sorted.map((x) => x[0]) + }); } + return isBatched ? toReturn : toReturn[0]; + } +}; - /** - * Clamps all elements in input into the range [ min, max ] - * @param {number} min lower-bound of the range to be clamped to - * @param {number} max upper-bound of the range to be clamped to - * @returns {Tensor} the output tensor. - */ - clamp(min, max) { - return this.clone().clamp_(min, max); +// src/pipelines/audio-classification.js +var AudioClassificationPipeline = class extends /** @type {new (options: AudioPipelineConstructorArgs) => AudioClassificationPipelineType} */ +Pipeline { + async _call(audio, { top_k = 5 } = {}) { + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const id2label = this.model.config.id2label; + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const output = await this.model(inputs); + const logits = output.logits[0]; + const scores = await topk(new Tensor3("float32", softmax(logits.data), logits.dims), top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + const vals = indices.map((x, i) => ({ + label: ( + /** @type {string} */ + id2label ? id2label[x] : `LABEL_${x}` + ), + score: ( + /** @type {number} */ + values[i] + ) + })); + toReturn.push(vals); } + return Array.isArray(audio) ? toReturn : toReturn[0]; + } +}; - /** - * In-place version of @see {@link Tensor.round} - */ - round_() { - const this_data = this.data; - for (let i = 0; i < this_data.length; ++i) { - this_data[i] = Math.round(this_data[i]); - } - return this; +// src/pipelines/zero-shot-audio-classification.js +var ZeroShotAudioClassificationPipeline = class extends /** @type {new (options: TextAudioPipelineConstructorArgs) => ZeroShotAudioClassificationPipelineType} */ +Pipeline { + async _call(audio, candidate_labels, { hypothesis_template = "This is a sound of {}." } = {}) { + const single = !Array.isArray(audio); + if (single) { + audio = [ + /** @type {AudioInput} */ + audio + ]; + } + const texts = candidate_labels.map((x) => hypothesis_template.replace("{}", x)); + const text_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(audio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + const audio_inputs = await this.processor(aud); + const output = await this.model({ ...text_inputs, ...audio_inputs }); + const probs = softmax(output.logits_per_audio.data); + toReturn.push( + [...probs].map((x, i) => ({ + score: x, + label: candidate_labels[i] + })) + ); } + return single ? toReturn[0] : toReturn; + } +}; - /** - * Rounds elements of input to the nearest integer. - * @returns {Tensor} the output tensor. - */ - round() { - return this.clone().round_(); +// src/pipelines/automatic-speech-recognition.js +var AutomaticSpeechRecognitionPipeline = class extends /** @type {new (options: TextAudioPipelineConstructorArgs) => AutomaticSpeechRecognitionPipelineType} */ +Pipeline { + _default_generation_config = { + // TODO: figure out good defaults for ASR generation parameters + // max_new_tokens: 256, + // num_beams: 5, + }; + async _call(audio, kwargs = {}) { + kwargs = { + ...this._default_generation_config, + ...kwargs + }; + switch (this.model.config.model_type) { + case "whisper": + case "lite-whisper": + return this._call_whisper(audio, kwargs); + case "wav2vec2": + case "wav2vec2-bert": + case "unispeech": + case "unispeech-sat": + case "hubert": + case "parakeet_ctc": + return this._call_wav2vec2(audio, kwargs); + case "moonshine": + return this._call_moonshine(audio, kwargs); + case "cohere_asr": + return this._call_cohere_asr(audio, kwargs); + default: + throw new Error( + `AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.` + ); } - - mean(dim = null, keepdim = false) { - return mean(this, dim, keepdim); + } + async _call_wav2vec2(audio, kwargs) { + if (kwargs.language) { + logger.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'); } - - min(dim = null, keepdim = false) { - if (dim === null) { - // None to reduce over all dimensions. - const val = (0,_maths_js__WEBPACK_IMPORTED_MODULE_0__.min)(this.data)[0]; - return new Tensor(this.type, [val], [/* scalar */]); - } - const [type, result, resultDims] = reduce_helper((a, b) => Math.min(a, b), this, dim, keepdim, Infinity); - return new Tensor(type, result, resultDims); + if (kwargs.task) { + logger.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".'); } - - max(dim = null, keepdim = false) { - if (dim === null) { - // None to reduce over all dimensions. - const val = (0,_maths_js__WEBPACK_IMPORTED_MODULE_0__.max)(this.data)[0]; - return new Tensor(this.type, [val], [/* scalar */]); - } - const [type, result, resultDims] = reduce_helper((a, b) => Math.max(a, b), this, dim, keepdim, -Infinity); - return new Tensor(type, result, resultDims); + const single = !Array.isArray(audio); + const batchedAudio = single ? [audio] : audio; + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(batchedAudio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const output = await this.model(inputs); + const logits = output.logits[0]; + const predicted_ids = []; + for (const item of logits) { + predicted_ids.push(max(item.data)[1]); + } + const predicted_sentences = this.tokenizer.decode(predicted_ids, { skip_special_tokens: true }).trim(); + toReturn.push({ text: predicted_sentences }); } - - argmin(dim = null, keepdim = false) { - if (dim !== null) { - throw new Error("`dim !== null` not yet implemented."); + return single ? toReturn[0] : toReturn; + } + async _call_whisper(audio, kwargs) { + const return_timestamps = kwargs.return_timestamps ?? false; + const chunk_length_s = kwargs.chunk_length_s ?? 0; + const force_full_sequences = kwargs.force_full_sequences ?? false; + let stride_length_s = kwargs.stride_length_s ?? null; + const generation_config = { ...kwargs }; + if (return_timestamps === "word") { + generation_config["return_token_timestamps"] = true; + generation_config["return_timestamps"] = true; + } + const single = !Array.isArray(audio); + const batchedAudio = single ? [audio] : audio; + const feature_extractor_config = this.processor.feature_extractor.config; + const time_precision = feature_extractor_config.chunk_length / this.model.config.max_source_positions; + const hop_length = feature_extractor_config.hop_length; + const sampling_rate = feature_extractor_config.sampling_rate; + const preparedAudios = await prepareAudios(batchedAudio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + let chunks = []; + if (chunk_length_s > 0) { + if (stride_length_s === null) { + stride_length_s = chunk_length_s / 6; + } else if (chunk_length_s <= stride_length_s) { + throw Error("`chunk_length_s` must be larger than `stride_length_s`."); + } + const window2 = sampling_rate * chunk_length_s; + const stride = sampling_rate * stride_length_s; + const jump = window2 - 2 * stride; + let offset = 0; + while (true) { + const offset_end = offset + window2; + const subarr = aud.subarray(offset, offset_end); + const feature = await this.processor(subarr); + const is_first = offset === 0; + const is_last = offset_end >= aud.length; + chunks.push({ + stride: [subarr.length, is_first ? 0 : stride, is_last ? 0 : stride], + input_features: feature.input_features, + is_last + }); + if (is_last) break; + offset += jump; } - const index = (0,_maths_js__WEBPACK_IMPORTED_MODULE_0__.min)(this.data)[1]; - return new Tensor('int64', [BigInt(index)], []); - } - argmax(dim = null, keepdim = false) { - if (dim !== null) { - throw new Error("`dim !== null` not yet implemented."); + } else { + chunks = [ + { + stride: [aud.length, 0, 0], + input_features: (await this.processor(aud)).input_features, + is_last: true + } + ]; + } + for (const chunk2 of chunks) { + generation_config.num_frames = Math.floor(chunk2.stride[0] / hop_length); + const data = await this.model.generate({ + inputs: chunk2.input_features, + ...generation_config + }); + if (return_timestamps === "word") { + const sequences = data.sequences.tolist()[0]; + const token_ts = data.token_timestamps.tolist()[0]; + const timestamp_begin = this.tokenizer.timestamp_begin; + const prefixLength = Math.max( + sequences.findIndex((t) => Number(t) >= timestamp_begin), + 0 + ); + chunk2.tokens = sequences.slice(prefixLength); + chunk2.token_timestamps = token_ts.slice(prefixLength).map((x) => round(x, 2)); + } else { + chunk2.tokens = /** @type {Tensor} */ + data[0].tolist(); } - const index = (0,_maths_js__WEBPACK_IMPORTED_MODULE_0__.max)(this.data)[1]; - return new Tensor('int64', [BigInt(index)], []); + chunk2.stride = chunk2.stride.map((x) => x / sampling_rate); + } + const [full_text, optional] = this.tokenizer._decode_asr(chunks, { + time_precision, + return_timestamps, + force_full_sequences + }); + toReturn.push({ text: full_text, ...optional }); } - - /** - * Performs Tensor dtype conversion. - * @param {DataType} type The desired data type. - * @returns {Tensor} The converted tensor. - */ - to(type) { - // If the self Tensor already has the correct dtype, then self is returned. - if (this.type === type) return this; - - // Otherwise, the returned tensor is a copy of self with the desired dtype. - if (!DataTypeMap.hasOwnProperty(type)) { - throw new Error(`Unsupported type: ${type}`); - } - - // Handle special cases where a mapping function is needed (e.g., where one type is a bigint and the other is a number) - let map_fn; - const is_source_bigint = ['int64', 'uint64'].includes(this.type); - const is_dest_bigint = ['int64', 'uint64'].includes(type); - if (is_source_bigint && !is_dest_bigint) { - // TypeError: Cannot convert a BigInt value to a number - map_fn = Number; - } else if (!is_source_bigint && is_dest_bigint) { - // TypeError: Cannot convert [x] to a BigInt - map_fn = BigInt; - } - - // @ts-ignore - return new Tensor(type, DataTypeMap[type].from(this.data, map_fn), this.dims); - } -} - -/** - * This creates a nested array of a given type and depth (see examples). - * - * @example - * NestArray; // string[] - * @example - * NestArray; // number[][] - * @example - * NestArray; // string[][][] etc. - * @template T - * @template {number} Depth - * @template {never[]} [Acc=[]] - * @typedef {Acc['length'] extends Depth ? T : NestArray} NestArray - */ - -/** - * Reshapes a 1-dimensional array into an n-dimensional array, according to the provided dimensions. - * - * @example - * reshape([10 ], [1 ]); // Type: number[] Value: [10] - * reshape([1, 2, 3, 4 ], [2, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4]] - * reshape([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2]); // Type: number[][][] Value: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] - * reshape([1, 2, 3, 4, 5, 6, 7, 8], [4, 2 ]); // Type: number[][] Value: [[1, 2], [3, 4], [5, 6], [7, 8]] - * @param {T[]|DataArray} data The input array to reshape. - * @param {DIM} dimensions The target shape/dimensions. - * @template T - * @template {[number]|number[]} DIM - * @returns {NestArray} The reshaped array. - */ -function reshape(data, dimensions) { - - const totalElements = data.length; - const dimensionSize = dimensions.reduce((a, b) => a * b); - - if (totalElements !== dimensionSize) { - throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`); + return single ? toReturn[0] : toReturn; + } + async _call_moonshine(audio, kwargs) { + const single = !Array.isArray(audio); + const batchedAudio = single ? [audio] : audio; + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(batchedAudio, sampling_rate); + const toReturn = []; + for (const aud of preparedAudios) { + const inputs = await this.processor(aud); + const max_new_tokens = Math.floor(aud.length / sampling_rate) * 6; + const outputs = await this.model.generate({ max_new_tokens, ...kwargs, ...inputs }); + const text = this.tokenizer.batch_decode( + /** @type {Tensor} */ + outputs, + { skip_special_tokens: true } + )[0]; + toReturn.push({ text }); } - - /** @type {any} */ - let reshapedArray = data; - - for (let i = dimensions.length - 1; i >= 0; i--) { - reshapedArray = reshapedArray.reduce((acc, val) => { - let lastArray = acc[acc.length - 1]; - - if (lastArray.length < dimensions[i]) { - lastArray.push(val); - } else { - acc.push([val]); - } - - return acc; - }, [[]]); + return single ? toReturn[0] : toReturn; + } + async _call_cohere_asr(audio, kwargs) { + const single = !Array.isArray(audio); + const batchedAudio = single ? [audio] : audio; + const feature_extractor = this.processor.feature_extractor; + const sampling_rate = feature_extractor.config.sampling_rate; + const preparedAudios = await prepareAudios(batchedAudio, sampling_rate); + const language = kwargs.language ?? "en"; + const decoder_input_ids = this.processor.get_decoder_prompt_ids(language); + const toReturn = []; + for (const aud of preparedAudios) { + const audioChunks = feature_extractor.split_audio(aud); + const chunk_texts = []; + for (const chunk2 of audioChunks) { + const inputs = await this.processor(chunk2); + const outputs = await this.model.generate({ + ...inputs, + decoder_input_ids, + ...kwargs + }); + const text = this.tokenizer.decode( + /** @type {Tensor} */ + outputs[0].tolist(), + { skip_special_tokens: true } + ).trim(); + chunk_texts.push(text); + } + const full_text = this.processor.constructor.join_chunks(chunk_texts, language); + toReturn.push({ text: full_text }); } + return single ? toReturn[0] : toReturn; + } +}; - return reshapedArray[0]; -} - -/** - * Permutes a tensor according to the provided axes. - * @param {any} tensor The input tensor to permute. - * @param {Array} axes The axes to permute the tensor along. - * @returns {Tensor} The permuted tensor. - */ -function permute(tensor, axes) { - const [permutedData, shape] = (0,_maths_js__WEBPACK_IMPORTED_MODULE_0__.permute_data)(tensor.data, tensor.dims, axes); - return new Tensor(tensor.type, permutedData, shape); -} - - -/** - * Interpolates an Tensor to the given size. - * @param {Tensor} input The input tensor to interpolate. Data must be channel-first (i.e., [c, h, w]) - * @param {number[]} size The output size of the image - * @param {string} mode The interpolation mode - * @param {boolean} align_corners Whether to align corners. - * @returns {Tensor} The interpolated tensor. - */ -function interpolate(input, [out_height, out_width], mode = 'bilinear', align_corners = false) { - - // Input image dimensions - const in_channels = input.dims.at(-3) ?? 1; - const in_height = input.dims.at(-2); - const in_width = input.dims.at(-1); - - let output = (0,_maths_js__WEBPACK_IMPORTED_MODULE_0__.interpolate_data)( - /** @type {import('./maths.js').TypedArray}*/(input.data), - [in_channels, in_height, in_width], - [out_height, out_width], - mode, - align_corners - ); - return new Tensor(input.type, output, [in_channels, out_height, out_width]); -} - - -/** - * Down/up samples the input. - * Inspired by https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html. - * @param {Tensor} input the input tensor - * @param {Object} options the options for the interpolation - * @param {[number, number]|[number, number, number]|[number, number, number, number]} [options.size=null] output spatial size. - * @param {"nearest"|"bilinear"|"bicubic"} [options.mode='bilinear'] algorithm used for upsampling - * @returns {Promise} The interpolated tensor. - */ -async function interpolate_4d(input, { - size = null, - mode = 'bilinear', -} = {}) { - - // Error checking - if (input.dims.length !== 4) { - throw new Error('`interpolate_4d` currently only supports 4D input.'); - } - if (!size) { - // TODO: support scale_factor - throw new Error('`interpolate_4d` requires a `size` argument.'); +// src/pipelines/text-to-audio.js +var TextToAudioPipeline = class extends /** @type {new (options: TextToAudioPipelineConstructorArgs) => TextToAudioPipelineType} */ +Pipeline { + DEFAULT_VOCODER_ID = "Xenova/speecht5_hifigan"; + /** + * Create a new TextToAudioPipeline. + * @param {TextToAudioPipelineConstructorArgs} options An object used to instantiate the pipeline. + */ + constructor(options) { + super(options); + this.vocoder = options.vocoder ?? null; + } + async _prepare_speaker_embeddings(speaker_embeddings, batch_size) { + if (typeof speaker_embeddings === "string" || speaker_embeddings instanceof URL) { + speaker_embeddings = new Float32Array(await (await env.fetch(speaker_embeddings)).arrayBuffer()); + } + if (speaker_embeddings instanceof Float32Array) { + speaker_embeddings = new Tensor3("float32", speaker_embeddings, [speaker_embeddings.length]); + } else if (!(speaker_embeddings instanceof Tensor3)) { + throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`."); + } + if (batch_size > 1) { + if (speaker_embeddings.dims[0] === 1) { + speaker_embeddings = speaker_embeddings.repeat(batch_size, 1); + } else if (speaker_embeddings.dims[0] !== batch_size) { + throw new Error( + `Expected speaker embeddings batch size to be 1 or ${batch_size}, but got ${speaker_embeddings.dims[0]}.` + ); + } } - - // Fill in missing dimensions - let targetDims; - if (size.length === 2) { - targetDims = [...input.dims.slice(0, 2), ...size]; - } else if (size.length === 3) { - targetDims = [input.dims[0], ...size]; - } else if (size.length === 4) { - targetDims = size; - } else { - throw new Error('`size` must be of length 2, 3, or 4.'); + return speaker_embeddings; + } + /** + * Helper to convert batched waveform tensor to RawAudio output(s). + * @param {string|string[]} text_inputs Original text input(s) to determine return type. + * @param {Tensor} waveform The waveform tensor of shape [batch_size, waveform_length]. + * @param {number} sampling_rate The audio sampling rate. + * @param {Tensor} [durations] Optional durations tensor for trimming (used by Supertonic). + * @returns {RawAudio|RawAudio[]} Single RawAudio or array based on input type. + * @private + */ + _postprocess_waveform(text_inputs, waveform, sampling_rate, durations = null) { + const waveformData = ( + /** @type {Float32Array} */ + waveform.data + ); + const [batch_size, waveformLength] = waveform.dims; + const durationsData = durations ? ( + /** @type {Float32Array} */ + durations.data + ) : null; + const results = []; + for (let i = 0; i < batch_size; ++i) { + const length = durationsData ? Math.min(Math.ceil(durationsData[i]), waveformLength) : waveformLength; + const start = i * waveformLength; + results.push(new RawAudio(waveformData.slice(start, start + length), sampling_rate)); } - - let op; - if (mode === 'nearest') { - op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.nearest_interpolate_4d; - } else if (mode === 'bilinear') { - op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.bilinear_interpolate_4d; - } else if (mode === 'bicubic') { - op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.bicubic_interpolate_4d; + return Array.isArray(text_inputs) ? results : results[0]; + } + async _call(text_inputs, options) { + if (this.processor) { + return this._call_text_to_spectrogram(text_inputs, options); + } else if (this.model.config.model_type === "supertonic") { + return this._call_supertonic(text_inputs, options); } else { - throw new Error(`Unsupported mode: ${mode}`); + return this._call_text_to_waveform(text_inputs); } - - const sizeTensor = new Tensor('int64', new BigInt64Array(targetDims.map(BigInt)), [targetDims.length]); - return await op({ x: input, s: sizeTensor }); -} - -/** - * Matrix product of two tensors. - * Inspired by https://pytorch.org/docs/stable/generated/torch.matmul.html - * @param {Tensor} a the first tensor to be multiplied - * @param {Tensor} b the second tensor to be multiplied - * @returns {Promise} The matrix product of the two tensors. - */ -async function matmul(a, b) { - const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.matmul; - return await op({ a, b }); -} - -/** - * Computes the one dimensional Fourier transform of real-valued input. - * Inspired by https://pytorch.org/docs/stable/generated/torch.fft.rfft.html - * @param {Tensor} x the real input tensor - * @param {Tensor} a The dimension along which to take the one dimensional real FFT. - * @returns {Promise} the output tensor. - */ -async function rfft(x, a) { - const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.rfft; - return await op({ x, a }); -} - - -/** - * Returns the k largest elements of the given input tensor. - * Inspired by https://pytorch.org/docs/stable/generated/torch.topk.html - * @param {Tensor} x the input tensor - * @param {number} [k] the k in "top-k" - * @returns {Promise<[Tensor, Tensor]>} the output tuple of (Tensor, LongTensor) of top-k elements and their indices. - */ -async function topk(x, k) { - const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.top_k; - - if (k == null) { - k = x.dims.at(-1); - } else { - k = Math.min(k, x.dims.at(-1)); - } - return await op({ - x, - k: new Tensor( - 'int64', - [BigInt(k)], - [1] - ) + } + async _call_supertonic(text_inputs, { speaker_embeddings, num_inference_steps, speed }) { + if (!speaker_embeddings) { + throw new Error("Speaker embeddings must be provided for Supertonic models."); + } + const { sampling_rate, style_dim } = this.model.config; + const inputs = this.tokenizer(text_inputs, { + padding: true, + truncation: true }); -} - - -const arrayToIndexTensor = (array) => new Tensor('int64', array, [array.length]); -/** - * Slice a multidimensional float32 tensor. - * @param {Tensor} data: Tensor of data to extract slices from - * @param {number[]} starts: 1-D array of starting indices of corresponding axis in axes - * @param {number[]} ends: 1-D array of ending indices (exclusive) of corresponding axis in axes - * @param {number[]} axes: 1-D array of axes that starts and ends apply to - * @param {number[]} [steps]: 1-D array of slice step of corresponding axis in axes. - * @returns {Promise} Sliced data tensor. - */ -async function slice(data, starts, ends, axes, steps) { - const op = await _ops_registry_js__WEBPACK_IMPORTED_MODULE_2__.TensorOpRegistry.slice; - return await op({ - x: data, - s: arrayToIndexTensor(starts), - e: arrayToIndexTensor(ends), - a: arrayToIndexTensor(axes), - t: arrayToIndexTensor(steps ?? new Array(axes.length).fill(1)), + const batch_size = inputs.input_ids.dims[0]; + speaker_embeddings = await this._prepare_speaker_embeddings(speaker_embeddings, batch_size); + speaker_embeddings = /** @type {Tensor} */ + speaker_embeddings.view(batch_size, -1, style_dim); + const { waveform, durations } = await this.model.generate_speech({ + ...inputs, + style: speaker_embeddings, + num_inference_steps, + speed }); -} - - -/** - * Perform mean pooling of the last hidden state followed by a normalization step. - * @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim] - * @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength] - * @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim]. - */ -function mean_pooling(last_hidden_state, attention_mask) { - // last_hidden_state: [batchSize, seqLength, embedDim] - // attention_mask: [batchSize, seqLength] - const lastHiddenStateData = last_hidden_state.data; - const attentionMaskData = attention_mask.data; - - const shape = [last_hidden_state.dims[0], last_hidden_state.dims[2]]; - - // @ts-ignore - const returnedData = new lastHiddenStateData.constructor(shape[0] * shape[1]); - const [batchSize, seqLength, embedDim] = last_hidden_state.dims; - - let outIndex = 0; - for (let i = 0; i < batchSize; ++i) { - const offset = i * embedDim * seqLength; - - for (let k = 0; k < embedDim; ++k) { - let sum = 0; - let count = 0; - - const attnMaskOffset = i * seqLength; - const offset2 = offset + k; - // Pool over all words in sequence - for (let j = 0; j < seqLength; ++j) { - // index into attention mask - const attn = Number(attentionMaskData[attnMaskOffset + j]); - - count += attn; - sum += lastHiddenStateData[offset2 + j * embedDim] * attn; - } + return this._postprocess_waveform(text_inputs, waveform, sampling_rate, durations); + } + async _call_text_to_waveform(text_inputs) { + const inputs = this.tokenizer(text_inputs, { + padding: true, + truncation: true + }); + const { waveform } = await this.model(inputs); + const sampling_rate = this.model.config.sampling_rate; + return this._postprocess_waveform(text_inputs, waveform, sampling_rate); + } + async _call_text_to_spectrogram(text_inputs, { speaker_embeddings }) { + if (!this.vocoder) { + logger.info("No vocoder specified, using default HifiGan vocoder."); + this.vocoder = await AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID, { dtype: "fp32" }); + } + const { input_ids } = this.tokenizer(text_inputs, { + padding: true, + truncation: true + }); + const batch_size = input_ids.dims[0]; + speaker_embeddings = await this._prepare_speaker_embeddings(speaker_embeddings, batch_size); + speaker_embeddings = speaker_embeddings.view(batch_size, -1); + const { waveform } = await this.model.generate_speech(input_ids, speaker_embeddings, { vocoder: this.vocoder }); + const sampling_rate = this.processor.feature_extractor.config.sampling_rate; + return this._postprocess_waveform(text_inputs, waveform, sampling_rate); + } +}; - const avg = sum / count; - returnedData[outIndex++] = avg; +// src/pipelines/image-to-text.js +var ImageToTextPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ImageToTextPipelineType} */ +Pipeline { + async _call(images, generate_kwargs = {}) { + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + const { pixel_values } = await this.processor(preparedImages); + const toReturn = []; + for (const batch of pixel_values) { + batch.dims = [1, ...batch.dims]; + const output = await this.model.generate({ inputs: batch, ...generate_kwargs }); + const decoded = this.tokenizer.batch_decode( + /** @type {Tensor} */ + output, + { + skip_special_tokens: true } + ).map((x) => ({ generated_text: x.trim() })); + toReturn.push(decoded); } + return isBatched ? toReturn : toReturn[0]; + } +}; - return new Tensor( - last_hidden_state.type, - returnedData, - shape - ) -} - -/** - * Apply Layer Normalization for last certain number of dimensions. - * @param {Tensor} input The input tensor - * @param {number[]} normalized_shape input shape from an expected input of size - * @param {Object} options The options for the layer normalization - * @param {number} [options.eps=1e-5] A value added to the denominator for numerical stability. - * @returns {Tensor} The normalized tensor. - */ -function layer_norm(input, normalized_shape, { - eps = 1e-5, -} = {}) { - if (input.dims.length !== 2) { - throw new Error('`layer_norm` currently only supports 2D input.'); - } - - const [batchSize, featureDim] = input.dims; - - if (normalized_shape.length !== 1 && normalized_shape[0] !== featureDim) { - throw new Error('`normalized_shape` must be a 1D array with shape `[input.dims[1]]`.'); +// src/pipelines/image-classification.js +var ImageClassificationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageClassificationPipelineType} */ +Pipeline { + async _call(images, { top_k = 5 } = {}) { + const preparedImages = await prepareImages(images); + const { pixel_values } = await this.processor(preparedImages); + const output = await this.model({ pixel_values }); + const { id2label } = this.model.config; + const toReturn = []; + for (const batch of output.logits) { + const scores = await topk(new Tensor3("float32", softmax(batch.data), batch.dims), top_k); + const values = scores[0].tolist(); + const indices = scores[1].tolist(); + const vals = indices.map((x, i) => ({ + label: ( + /** @type {string} */ + id2label ? id2label[x] : `LABEL_${x}` + ), + score: ( + /** @type {number} */ + values[i] + ) + })); + toReturn.push(vals); } + return Array.isArray(images) ? toReturn : toReturn[0]; + } +}; - const [std, mean] = std_mean(input, 1, 0, true); - const stdData = /** @type {Float32Array} */(std.data); - const meanData = /** @type {Float32Array} */(mean.data); - - const inputData = /** @type {Float32Array} */(input.data); - - // @ts-ignore - const returnedData = new inputData.constructor(inputData.length); - - for (let i = 0; i < batchSize; ++i) { - const offset = i * featureDim; - for (let j = 0; j < featureDim; ++j) { - const offset2 = offset + j; - returnedData[offset2] = (inputData[offset2] - meanData[i]) / (stdData[i] + eps); +// src/pipelines/image-segmentation.js +var SUBTASKS_MAPPING = { + // Mapping of subtasks to their corresponding post-processing function names. + panoptic: "post_process_panoptic_segmentation", + instance: "post_process_instance_segmentation", + semantic: "post_process_semantic_segmentation" +}; +var ImageSegmentationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageSegmentationPipelineType} */ +Pipeline { + /** @type {ImageSegmentationPipelineCallback} */ + async _call(images, { + threshold = 0.5, + mask_threshold = 0.5, + overlap_mask_area_threshold = 0.8, + label_ids_to_fuse = null, + target_sizes = null, + subtask = null + } = {}) { + const isBatched = Array.isArray(images); + if (isBatched && images.length !== 1) { + throw Error("Image segmentation pipeline currently only supports a batch size of 1."); + } + const preparedImages = await prepareImages(images); + const imageSizes = preparedImages.map((x) => [x.height, x.width]); + const inputs = await this.processor(preparedImages); + const { inputNames, outputNames } = this.model.sessions["model"]; + if (!inputNames.includes("pixel_values")) { + if (inputNames.length !== 1) { + throw Error(`Expected a single input name, but got ${inputNames.length} inputs: ${inputNames}.`); + } + const newName = inputNames[0]; + if (newName in inputs) { + throw Error(`Input name ${newName} already exists in the inputs.`); + } + inputs[newName] = inputs.pixel_values; + } + const output = await this.model(inputs); + let fn2 = null; + if (subtask !== null) { + fn2 = SUBTASKS_MAPPING[subtask]; + } else if (this.processor.image_processor) { + for (const [task, func] of Object.entries(SUBTASKS_MAPPING)) { + if (func in this.processor.image_processor) { + fn2 = this.processor.image_processor[func].bind(this.processor.image_processor); + subtask = task; + break; } + } } - return new Tensor(input.type, returnedData, input.dims); -} - -/** - * Helper function to calculate new dimensions when performing a squeeze operation. - * @param {number[]} dims The dimensions of the tensor. - * @param {number|number[]|null} dim The dimension(s) to squeeze. - * @returns {number[]} The new dimensions. - * @private - */ -function calc_squeeze_dims(dims, dim) { - dims = dims.slice(); - if (dim === null) { - dims = dims.filter((d) => d !== 1); - } else if (typeof dim === 'number') { - if (dims[dim] === 1) { - dims.splice(dim, 1); - } - } else if (Array.isArray(dim)) { - dims = dims.filter((x, i) => { - return x !== 1 || !dim.includes(i); + const id2label = this.model.config.id2label; + const annotation = []; + if (!subtask) { + const epsilon = 1e-5; + const result = output[outputNames[0]]; + for (let i = 0; i < imageSizes.length; ++i) { + const size = imageSizes[i]; + const item = result[i]; + if (item.data.some((x) => x < -epsilon || x > 1 + epsilon)) { + item.sigmoid_(); + } + const mask = await RawImage.fromTensor(item.mul_(255).to("uint8")).resize(size[1], size[0]); + annotation.push({ + label: null, + score: null, + mask }); - } - return dims; -} - -/** - * Helper function to calculate new dimensions when performing an unsqueeze operation. - * @param {number[]} dims The dimensions of the tensor. - * @param {number} dim The dimension to unsqueeze. - * @returns {number[]} The new dimensions. - * @private - */ -function calc_unsqueeze_dims(dims, dim) { - // Dimension out of range (e.g., "expected to be in range of [-4, 3], but got 4") - // + 1 since we allow inserting at the end (i.e. dim = -1) - dim = safeIndex(dim, dims.length + 1); - dims = dims.slice(); - // Insert 1 into specified dimension - dims.splice(dim, 0, 1); - return dims; -} - -/** - * Safely calculate the index for an array of a given size, allowing negative indexing. - * @param {number} index The index that will be used. - * @param {number} size The size of the array. - * @param {number} [dimension=null] The dimension that the index is for (optional). - * @returns {number} The index, guaranteed to be non-negative and less than `arrayLength`. - * - * @throws {Error} If the index is out of range. - * @private - */ -function safeIndex(index, size, dimension = null, boundsCheck = true) { - if (index < -size || index >= size) { - if (boundsCheck) { - throw new Error(`IndexError: index ${index} is out of bounds for dimension${dimension === null ? '' : ' ' + dimension} with size ${size}`); - } else { - return index < -size ? 0 : size; + } + } else if (subtask === "panoptic" || subtask === "instance") { + const processed = fn2( + output, + threshold, + mask_threshold, + overlap_mask_area_threshold, + label_ids_to_fuse, + target_sizes ?? imageSizes + // TODO FIX? + )[0]; + const segmentation = processed.segmentation; + for (const segment of processed.segments_info) { + const maskData = new Uint8ClampedArray(segmentation.data.length); + for (let i = 0; i < segmentation.data.length; ++i) { + if (segmentation.data[i] === segment.id) { + maskData[i] = 255; + } } - } - - if (index < 0) { - // Negative indexing, ensuring positive index - index = ((index % size) + size) % size; - } - return index; -} - -/** - * Concatenates an array of tensors along a specified dimension. - * @param {Tensor[]} tensors The array of tensors to concatenate. - * @param {number} dim The dimension to concatenate along. - * @returns {Tensor} The concatenated tensor. - */ -function cat(tensors, dim = 0) { - dim = safeIndex(dim, tensors[0].dims.length); - - // TODO do validation of shapes - - const resultDims = tensors[0].dims.slice(); - resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0); - - // Create a new array to store the accumulated values - const resultSize = resultDims.reduce((a, b) => a * b, 1); - // @ts-ignore - const result = new tensors[0].data.constructor(resultSize); - - // Create output tensor of same type as first - const resultType = tensors[0].type; - - if (dim === 0) { - // Handle special case for performance reasons - - let offset = 0; - for (const tensor of tensors) { - const tensorData = tensor.data; - result.set(tensorData, offset); - offset += tensorData.length; + const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); + annotation.push({ + score: segment.score, + label: id2label[segment.label_id], + mask + }); + } + } else if (subtask === "semantic") { + const { segmentation, labels } = fn2(output, target_sizes ?? imageSizes)[0]; + for (const label of labels) { + const maskData = new Uint8ClampedArray(segmentation.data.length); + for (let i = 0; i < segmentation.data.length; ++i) { + if (segmentation.data[i] === label) { + maskData[i] = 255; + } } - + const mask = new RawImage(maskData, segmentation.dims[1], segmentation.dims[0], 1); + annotation.push({ + score: null, + label: id2label[label], + mask + }); + } } else { - - let currentDim = 0; - - for (let t = 0; t < tensors.length; ++t) { - const { data, dims } = tensors[t]; - - // Iterate over the data array - for (let i = 0; i < data.length; ++i) { - // Calculate the index in the resulting array - let resultIndex = 0; - - for (let j = dims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = dims[j]; - let index = num % size; - if (j === dim) { - index += currentDim; - } - resultIndex += index * resultMultiplier; - resultMultiplier *= resultDims[j]; - num = Math.floor(num / size); - } - // Accumulate the value at the current index - result[resultIndex] = data[i]; - } - - currentDim += dims[dim]; - } - } - return new Tensor(resultType, result, resultDims); -} - -/** - * Stack an array of tensors along a specified dimension. - * @param {Tensor[]} tensors The array of tensors to stack. - * @param {number} dim The dimension to stack along. - * @returns {Tensor} The stacked tensor. - */ -function stack(tensors, dim = 0) { - // TODO do validation of shapes - // NOTE: stack expects each tensor to be equal size - return cat(tensors.map(t => t.unsqueeze(dim)), dim); -} - - -/** - * @param {(previousValue: any, currentValue: any, currentIndex?: number, resultIndex?: number) => any} callbackfn - * @param {Tensor} input the input tensor. - * @param {number|null} dim the dimension to reduce. - * @param {boolean} keepdim whether the output tensor has dim retained or not. - * @returns {[DataType, any, number[]]} The reduced tensor data. - */ -function reduce_helper(callbackfn, input, dim = null, keepdim = false, initialValue = null) { - const inputData = input.data; - const inputDims = input.dims; - - // Negative indexing - dim = safeIndex(dim, inputDims.length); - - // Calculate the shape of the resulting array after summation - const resultDims = inputDims.slice(); // Copy the original dimensions - resultDims[dim] = 1; // Remove the specified axis - - // Create a new array to store the accumulated values - // @ts-ignore - const result = new inputData.constructor(inputData.length / inputDims[dim]); - if (initialValue !== null) { - result.fill(initialValue); + throw Error(`Subtask ${subtask} not supported.`); } + return annotation; + } +}; - // Iterate over the data array - for (let i = 0; i < inputData.length; ++i) { +// src/pipelines/background-removal.js +var BackgroundRemovalPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => BackgroundRemovalPipelineType} */ +/** @type {any} */ +ImageSegmentationPipeline { + async _call(images, options = {}) { + const preparedImages = await prepareImages(images); + const masks = await super._call(images, options); + const result = preparedImages.map((img, i) => { + const cloned = img.clone(); + cloned.putAlpha(masks[i].mask); + return cloned; + }); + return Array.isArray(images) ? result : result[0]; + } +}; - // Calculate the index in the resulting array - let resultIndex = 0; +// src/pipelines/zero-shot-image-classification.js +var ZeroShotImageClassificationPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotImageClassificationPipelineType} */ +Pipeline { + async _call(images, candidate_labels, { hypothesis_template = "This is a photo of {}" } = {}) { + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + const texts = candidate_labels.map((x) => hypothesis_template.replace("{}", x)); + const text_inputs = this.tokenizer(texts, { + padding: this.model.config.model_type === "siglip" ? "max_length" : true, + truncation: true + }); + const { pixel_values } = await this.processor(preparedImages); + const output = await this.model({ ...text_inputs, pixel_values }); + const function_to_apply = this.model.config.model_type === "siglip" ? (batch) => batch.sigmoid().data : (batch) => softmax(batch.data); + const toReturn = []; + for (const batch of output.logits_per_image) { + const probs = function_to_apply(batch); + const result = [...probs].map((x, i) => ({ + score: x, + label: candidate_labels[i] + })); + result.sort((a, b) => b.score - a.score); + toReturn.push(result); + } + return isBatched ? toReturn : toReturn[0]; + } +}; - for (let j = inputDims.length - 1, num = i, resultMultiplier = 1; j >= 0; --j) { - const size = inputDims[j]; - if (j !== dim) { - const index = num % size; - resultIndex += index * resultMultiplier; - resultMultiplier *= resultDims[j]; - } - num = Math.floor(num / size); - } +// src/pipelines/object-detection.js +var ObjectDetectionPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ObjectDetectionPipelineType} */ +Pipeline { + async _call(images, { threshold = 0.9, percentage = false } = {}) { + const isBatched = Array.isArray(images); + if (isBatched && images.length !== 1) { + throw Error("Object detection pipeline currently only supports a batch size of 1."); + } + const preparedImages = await prepareImages(images); + const imageSizes = percentage ? null : preparedImages.map((x) => [x.height, x.width]); + const { pixel_values, pixel_mask } = await this.processor(preparedImages); + const output = await this.model({ pixel_values, pixel_mask }); + const processed = this.processor.image_processor.post_process_object_detection(output, threshold, imageSizes); + const { id2label } = this.model.config; + const result = processed.map( + (batch) => batch.boxes.map((box, i) => ({ + score: batch.scores[i], + label: id2label[batch.classes[i]], + box: get_bounding_box(box, !percentage) + })) + ); + return isBatched ? result : result[0]; + } +}; - // Accumulate the value at the current index - result[resultIndex] = callbackfn(result[resultIndex], inputData[i], i, resultIndex); +// src/pipelines/zero-shot-object-detection.js +var ZeroShotObjectDetectionPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => ZeroShotObjectDetectionPipelineType} */ +Pipeline { + async _call(images, candidate_labels, { threshold = 0.1, top_k = null, percentage = false } = {}) { + const isBatched = Array.isArray(images); + const preparedImages = await prepareImages(images); + const text_inputs = this.tokenizer(candidate_labels, { + padding: true, + truncation: true + }); + const model_inputs = await this.processor(preparedImages); + const toReturn = []; + for (let i = 0; i < preparedImages.length; ++i) { + const image = preparedImages[i]; + const imageSize = percentage ? null : [[image.height, image.width]]; + const pixel_values = model_inputs.pixel_values[i].unsqueeze_(0); + const output = await this.model({ ...text_inputs, pixel_values }); + let result; + if ("post_process_grounded_object_detection" in this.processor) { + const processed = this.processor.post_process_grounded_object_detection(output, text_inputs.input_ids, { + // TODO: support separate threshold values + box_threshold: threshold, + text_threshold: threshold, + target_sizes: imageSize + })[0]; + result = processed.boxes.map((box, i2) => ({ + score: processed.scores[i2], + label: processed.labels[i2], + box: get_bounding_box(box, !percentage) + })); + } else { + const processed = this.processor.image_processor.post_process_object_detection( + output, + threshold, + imageSize, + true + )[0]; + result = processed.boxes.map((box, i2) => ({ + score: processed.scores[i2], + label: candidate_labels[processed.classes[i2]], + box: get_bounding_box(box, !percentage) + })); + } + result.sort((a, b) => b.score - a.score); + if (top_k !== null) { + result = result.slice(0, top_k); + } + toReturn.push(result); } + return isBatched ? toReturn : toReturn[0]; + } +}; - if (!keepdim) resultDims.splice(dim, 1); - - return [input.type, result, resultDims]; -} - - -/** - * Calculates the standard deviation and mean over the dimensions specified by dim. dim can be a single dimension or `null` to reduce over all dimensions. - * @param {Tensor} input the input tenso - * @param {number|null} dim the dimension to reduce. If None, all dimensions are reduced. - * @param {number} correction difference between the sample size and sample degrees of freedom. Defaults to Bessel's correction, correction=1. - * @param {boolean} keepdim whether the output tensor has dim retained or not. - * @returns {Tensor[]} A tuple of (std, mean) tensors. - */ -function std_mean(input, dim = null, correction = 1, keepdim = false) { - const inputData = /** @type {Float32Array} */(input.data); - const inputDims = input.dims; - - if (dim === null) { - // None to reduce over all dimensions. - const sum = inputData.reduce((a, b) => a + b, 0); - const mean = sum / inputData.length; - const std = Math.sqrt(inputData.reduce((a, b) => a + (b - mean) ** 2, 0) / (inputData.length - correction)); - - const meanTensor = new Tensor(input.type, [mean], [/* scalar */]); - const stdTensor = new Tensor(input.type, [std], [/* scalar */]); +// src/pipelines/document-question-answering.js +var DocumentQuestionAnsweringPipeline = class extends /** @type {new (options: TextImagePipelineConstructorArgs) => DocumentQuestionAnsweringPipelineType} */ +Pipeline { + _default_generation_config = { + max_new_tokens: 256 + }; + async _call(image, question, generate_kwargs = {}) { + if (Array.isArray(image)) { + if (image.length !== 1) { + throw Error("Document Question Answering pipeline currently only supports a batch size of 1."); + } + image = image[0]; + } + const preparedImage = (await prepareImages(image))[0]; + const { pixel_values } = await this.processor(preparedImage); + const task_prompt = `${question}`; + const decoder_input_ids = this.tokenizer(task_prompt, { + add_special_tokens: false, + padding: true, + truncation: true + }).input_ids; + const output = await this.model.generate({ + inputs: pixel_values, + // @ts-expect-error Ts2339 + max_length: this.model.config.decoder.max_position_embeddings, + decoder_input_ids, + ...this._default_generation_config, + ...generate_kwargs + }); + const decoded = this.tokenizer.batch_decode( + /** @type {Tensor} */ + output + )[0]; + const match = decoded.match(/(.*?)<\/s_answer>/); + let answer = null; + if (match && match.length >= 2) { + answer = match[1].trim(); + } + return [{ answer }]; + } +}; - return [stdTensor, meanTensor]; +// src/pipelines/image-to-image.js +var ImageToImagePipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageToImagePipelineType} */ +Pipeline { + async _call(images) { + const preparedImages = await prepareImages(images); + const inputs = await this.processor(preparedImages); + const outputs = await this.model(inputs); + const toReturn = []; + for (const batch of outputs.reconstruction) { + const output = batch.squeeze().clamp_(0, 1).mul_(255).round_().to("uint8"); + toReturn.push(RawImage.fromTensor(output)); } - dim = safeIndex(dim, inputDims.length); - const meanTensor = mean(input, dim, keepdim); - const meanTensorData = meanTensor.data; - - // Compute squared sum - const [type, result, resultDims] = reduce_helper((a, b, i, j) => a + (b - meanTensorData[j]) ** 2, input, dim, keepdim); + return Array.isArray(images) ? toReturn : toReturn[0]; + } +}; - // Square root of the squared sum - for (let i = 0; i < result.length; ++i) { - result[i] = Math.sqrt(result[i] / (inputDims[dim] - correction)); +// src/pipelines/depth-estimation.js +var DepthEstimationPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => DepthEstimationPipelineType} */ +Pipeline { + async _call(images) { + const preparedImages = await prepareImages(images); + const inputs = await this.processor(preparedImages); + const { predicted_depth } = await this.model(inputs); + const toReturn = []; + for (let i = 0; i < preparedImages.length; ++i) { + const batch = predicted_depth[i]; + const [height, width] = batch.dims.slice(-2); + const [new_width, new_height] = preparedImages[i].size; + const prediction = (await interpolate_4d(batch.view(1, 1, height, width), { + size: [new_height, new_width], + mode: "bilinear" + })).view(new_height, new_width); + const minval = ( + /** @type {number} */ + prediction.min().item() + ); + const maxval = ( + /** @type {number} */ + prediction.max().item() + ); + const formatted = prediction.sub(minval).div_(maxval - minval).mul_(255).to("uint8").unsqueeze(0); + const depth = RawImage.fromTensor(formatted); + toReturn.push({ + predicted_depth: prediction, + depth + }); } + return Array.isArray(images) ? toReturn : toReturn[0]; + } +}; - const stdTensor = new Tensor(type, result, resultDims); - - return [stdTensor, meanTensor]; -} - -/** - * Returns the mean value of each row of the input tensor in the given dimension dim. - * @param {Tensor} input the input tensor. - * @param {number|null} dim the dimension to reduce. - * @param {boolean} keepdim whether the output tensor has dim retained or not. - * @returns {Tensor} A new tensor with means taken along the specified dimension. - */ -function mean(input, dim = null, keepdim = false) { - const inputDims = input.dims; - const inputData = /** @type {Float32Array} */(input.data); - - if (dim === null) { - // None to reduce over all dimensions. - const val = inputData.reduce((a, b) => a + b, 0); - return new Tensor(input.type, [val / inputData.length], [/* scalar */]); +// src/pipelines/feature-extraction.js +var FeatureExtractionPipeline = class extends /** @type {new (options: TextPipelineConstructorArgs) => FeatureExtractionPipelineType} */ +Pipeline { + /** @type {FeatureExtractionPipelineCallback} */ + async _call(texts, { + pooling = ( + /** @type {'none'} */ + "none" + ), + normalize = false, + quantize = false, + precision = ( + /** @type {'binary'} */ + "binary" + ) + } = {}) { + const model_inputs = this.tokenizer(texts, { + padding: true, + truncation: true + }); + const outputs = await this.model(model_inputs); + let result = outputs.last_hidden_state ?? outputs.logits ?? outputs.token_embeddings; + switch (pooling) { + case "none": + break; + case "mean": + result = mean_pooling(result, model_inputs.attention_mask); + break; + case "first_token": + case "cls": + result = result.slice(null, 0); + break; + case "last_token": + case "eos": + result = result.slice(null, -1); + break; + default: + throw Error(`Pooling method '${pooling}' not supported.`); } - dim = safeIndex(dim, inputDims.length); - - // Compute sum - const [type, result, resultDims] = reduce_helper((a, b) => a + b, input, dim, keepdim); - - // Divide by number of elements in the dimension - if (inputDims[dim] !== 1) { - for (let i = 0; i < result.length; ++i) { - result[i] /= inputDims[dim]; - } + if (normalize) { + result = result.normalize(2, -1); } - - return new Tensor(type, result, resultDims); -} - - -function dimsToStride(dims) { - const stride = new Array(dims.length); - for (let i = dims.length - 1, s2 = 1; i >= 0; --i) { - stride[i] = s2; - s2 *= dims[i]; + if (quantize) { + result = quantize_embeddings(result, precision); } - return stride; -} - -function fullHelper(size, fill_value, dtype, cls) { - const numElements = size.reduce((a, b) => a * b, 1); - return new Tensor( - dtype, - new cls(numElements).fill(fill_value), - size - ) -} + return result; + } +}; -/** - * Creates a tensor of size size filled with fill_value. The tensor's dtype is inferred from fill_value. - * @param {number[]} size A sequence of integers defining the shape of the output tensor. - * @param {number|bigint|boolean} fill_value The value to fill the output tensor with. - * @returns {Tensor} The filled tensor. - */ -function full(size, fill_value) { - let dtype; - let typedArrayCls; - if (typeof fill_value === 'number') { - dtype = 'float32'; - typedArrayCls = Float32Array; - } else if (typeof fill_value === 'bigint') { - dtype = 'int64'; - typedArrayCls = BigInt64Array; - } else if (typeof fill_value === 'boolean') { - dtype = 'bool'; - typedArrayCls = Uint8Array; +// src/pipelines/image-feature-extraction.js +var ImageFeatureExtractionPipeline = class extends /** @type {new (options: ImagePipelineConstructorArgs) => ImageFeatureExtractionPipelineType} */ +Pipeline { + /** @type {ImageFeatureExtractionPipelineCallback} */ + async _call(images, { pool = null } = {}) { + const preparedImages = await prepareImages(images); + const { pixel_values } = await this.processor(preparedImages); + const outputs = await this.model({ pixel_values }); + let result; + if (pool) { + if (!("pooler_output" in outputs)) { + throw Error( + `No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.` + ); + } + result = outputs.pooler_output; } else { - // TODO: support other dtypes - throw new Error(`Unsupported data type: ${typeof fill_value}`); - } - return fullHelper(size, fill_value, dtype, typedArrayCls); -} - -function full_like(tensor, fill_value) { - return full(tensor.dims, fill_value); -} - -/** - * Returns a tensor filled with the scalar value 1, with the shape defined by the variable argument size. - * @param {number[]} size A sequence of integers defining the shape of the output tensor. - * @returns {Tensor} The ones tensor. - */ -function ones(size) { - return fullHelper(size, 1n, 'int64', BigInt64Array); -} - -/** - * Returns a tensor filled with the scalar value 1, with the same size as input. - * @param {Tensor} tensor The size of input will determine size of the output tensor. - * @returns {Tensor} The ones tensor. - */ -function ones_like(tensor) { - return ones(tensor.dims); -} - -/** - * Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. - * @param {number[]} size A sequence of integers defining the shape of the output tensor. - * @returns {Tensor} The zeros tensor. - */ -function zeros(size) { - return fullHelper(size, 0n, 'int64', BigInt64Array); -} - -/** - * Returns a tensor filled with the scalar value 0, with the same size as input. - * @param {Tensor} tensor The size of input will determine size of the output tensor. - * @returns {Tensor} The zeros tensor. - */ -function zeros_like(tensor) { - return zeros(tensor.dims); -} - -/** - * Returns a tensor filled with random numbers from a uniform distribution on the interval [0, 1) - * @param {number[]} size A sequence of integers defining the shape of the output tensor. - * @returns {Tensor} The random tensor. - */ -function rand(size) { - const length = size.reduce((a, b) => a * b, 1); - return new Tensor( - "float32", - Float32Array.from({ length }, () => Math.random()), - size, - ) -} - -/** - * Quantizes the embeddings tensor to binary or unsigned binary precision. - * @param {Tensor} tensor The tensor to quantize. - * @param {'binary'|'ubinary'} precision The precision to use for quantization. - * @returns {Tensor} The quantized tensor. - */ -function quantize_embeddings(tensor, precision) { - if (tensor.dims.length !== 2) { - throw new Error("The tensor must have 2 dimensions"); - } - if (tensor.dims.at(-1) % 8 !== 0) { - throw new Error("The last dimension of the tensor must be a multiple of 8"); + result = outputs.last_hidden_state ?? outputs.logits ?? outputs.image_embeds; } - if (!['binary', 'ubinary'].includes(precision)) { - throw new Error("The precision must be either 'binary' or 'ubinary'"); - } - - const signed = precision === 'binary'; - const dtype = signed ? 'int8' : 'uint8'; - - // Create a typed array to store the packed bits - const cls = signed ? Int8Array : Uint8Array; - const inputData = tensor.data; - const outputData = new cls(inputData.length / 8); - - // Iterate over each number in the array - for (let i = 0; i < inputData.length; ++i) { - // Determine if the number is greater than 0 - const bit = inputData[i] > 0 ? 1 : 0; - - // Calculate the index in the typed array and the position within the byte - const arrayIndex = Math.floor(i / 8); - const bitPosition = i % 8; - - // Pack the bit into the typed array - outputData[arrayIndex] |= bit << (7 - bitPosition); - if (signed && bitPosition === 0) { - outputData[arrayIndex] -= 128; - } - }; - - return new Tensor(dtype, outputData, [tensor.dims[0], tensor.dims[1] / 8]); -} - - -/***/ }), - -/***/ "./src/utils/video.js": -/*!****************************!*\ - !*** ./src/utils/video.js ***! - \****************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ RawVideo: () => (/* binding */ RawVideo), -/* harmony export */ RawVideoFrame: () => (/* binding */ RawVideoFrame), -/* harmony export */ load_video: () => (/* binding */ load_video) -/* harmony export */ }); -/* harmony import */ var _image_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./image.js */ "./src/utils/image.js"); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../env.js */ "./src/env.js"); - - + return result; + } +}; -class RawVideoFrame { +// src/pipelines/index.js +var SUPPORTED_TASKS = Object.freeze({ + "text-classification": { + pipeline: TextClassificationPipeline, + model: AutoModelForSequenceClassification, + default: { + model: "Xenova/distilbert-base-uncased-finetuned-sst-2-english" + }, + type: "text" + }, + "token-classification": { + pipeline: TokenClassificationPipeline, + model: AutoModelForTokenClassification, + default: { + model: "Xenova/bert-base-multilingual-cased-ner-hrl" + }, + type: "text" + }, + "question-answering": { + pipeline: QuestionAnsweringPipeline, + model: AutoModelForQuestionAnswering, + default: { + model: "Xenova/distilbert-base-cased-distilled-squad" + }, + type: "text" + }, + "fill-mask": { + pipeline: FillMaskPipeline, + model: AutoModelForMaskedLM, + default: { + model: "onnx-community/ettin-encoder-32m-ONNX", + dtype: "fp32" + }, + type: "text" + }, + summarization: { + pipeline: SummarizationPipeline, + model: AutoModelForSeq2SeqLM, + default: { + model: "Xenova/distilbart-cnn-6-6" + }, + type: "text" + }, + translation: { + pipeline: TranslationPipeline, + model: AutoModelForSeq2SeqLM, + default: { + model: "Xenova/t5-small" + }, + type: "text" + }, + "text2text-generation": { + pipeline: Text2TextGenerationPipeline, + model: AutoModelForSeq2SeqLM, + default: { + model: "Xenova/flan-t5-small" + }, + type: "text" + }, + "text-generation": { + pipeline: TextGenerationPipeline, + model: AutoModelForCausalLM, + default: { + model: "onnx-community/Qwen3-0.6B-ONNX", + dtype: "q4" + }, + type: "text" + }, + "zero-shot-classification": { + pipeline: ZeroShotClassificationPipeline, + model: AutoModelForSequenceClassification, + default: { + model: "Xenova/distilbert-base-uncased-mnli" + }, + type: "text" + }, + "audio-classification": { + pipeline: AudioClassificationPipeline, + model: AutoModelForAudioClassification, + default: { + model: "Xenova/wav2vec2-base-superb-ks" + }, + type: "audio" + }, + "zero-shot-audio-classification": { + pipeline: ZeroShotAudioClassificationPipeline, + model: AutoModel, + default: { + model: "Xenova/clap-htsat-unfused" + }, + type: "multimodal" + }, + "automatic-speech-recognition": { + pipeline: AutomaticSpeechRecognitionPipeline, + model: [AutoModelForSpeechSeq2Seq, AutoModelForCTC], + default: { + model: "Xenova/whisper-tiny.en" + }, + type: "multimodal" + }, + "text-to-audio": { + pipeline: TextToAudioPipeline, + model: [AutoModelForTextToWaveform, AutoModelForTextToSpectrogram], + default: { + model: "onnx-community/Supertonic-TTS-ONNX", + dtype: "fp32" + }, + type: "text" + }, + "image-to-text": { + pipeline: ImageToTextPipeline, + model: AutoModelForVision2Seq, + default: { + model: "Xenova/vit-gpt2-image-captioning" + }, + type: "multimodal" + }, + "image-classification": { + pipeline: ImageClassificationPipeline, + model: AutoModelForImageClassification, + default: { + model: "Xenova/vit-base-patch16-224" + }, + type: "multimodal" + }, + "image-segmentation": { + pipeline: ImageSegmentationPipeline, + model: [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForUniversalSegmentation], + default: { + model: "Xenova/detr-resnet-50-panoptic" + }, + type: "multimodal" + }, + "background-removal": { + pipeline: BackgroundRemovalPipeline, + model: [AutoModelForImageSegmentation, AutoModelForSemanticSegmentation, AutoModelForUniversalSegmentation], + default: { + model: "Xenova/modnet" + }, + type: "image" + }, + "zero-shot-image-classification": { + pipeline: ZeroShotImageClassificationPipeline, + model: AutoModel, + default: { + model: "Xenova/clip-vit-base-patch32" + }, + type: "multimodal" + }, + "object-detection": { + pipeline: ObjectDetectionPipeline, + model: AutoModelForObjectDetection, + default: { + model: "Xenova/detr-resnet-50" + }, + type: "multimodal" + }, + "zero-shot-object-detection": { + pipeline: ZeroShotObjectDetectionPipeline, + model: AutoModelForZeroShotObjectDetection, + default: { + model: "Xenova/owlvit-base-patch32" + }, + type: "multimodal" + }, + "document-question-answering": { + pipeline: DocumentQuestionAnsweringPipeline, + model: AutoModelForDocumentQuestionAnswering, + default: { + model: "Xenova/donut-base-finetuned-docvqa" + }, + type: "multimodal" + }, + "image-to-image": { + pipeline: ImageToImagePipeline, + model: AutoModelForImageToImage, + default: { + model: "Xenova/swin2SR-classical-sr-x2-64" + }, + type: "image" + }, + "depth-estimation": { + pipeline: DepthEstimationPipeline, + model: AutoModelForDepthEstimation, + default: { + model: "onnx-community/depth-anything-v2-small" + }, + type: "image" + }, + "feature-extraction": { + pipeline: FeatureExtractionPipeline, + model: AutoModel, + default: { + model: "onnx-community/all-MiniLM-L6-v2-ONNX", + dtype: "fp32" + }, + type: "text" + }, + "image-feature-extraction": { + pipeline: ImageFeatureExtractionPipeline, + model: [AutoModelForImageFeatureExtraction, AutoModel], + default: { + model: "onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX", + dtype: "fp32" + }, + type: "image" + } +}); +var TASK_ALIASES = Object.freeze({ + "sentiment-analysis": "text-classification", + ner: "token-classification", + // "vqa": "visual-question-answering", // TODO: Add + asr: "automatic-speech-recognition", + "text-to-speech": "text-to-audio", + // Add for backwards compatibility + embeddings: "feature-extraction" +}); - /** - * @param {RawImage} image - * @param {number} timestamp - */ - constructor(image, timestamp) { - this.image = image; - this.timestamp = timestamp; - } +// src/utils/model_registry/get_processor_files.js +async function get_processor_files(modelId) { + if (!modelId) { + throw new Error("modelId is required"); + } + const metadata = await get_file_metadata(modelId, IMAGE_PROCESSOR_NAME, {}); + return metadata.exists ? [IMAGE_PROCESSOR_NAME] : []; +} + +// src/utils/model_registry/get_files.js +async function get_files(modelId, { + config = null, + dtype = null, + device = null, + model_file_name = null, + include_tokenizer = true, + include_processor = true +} = {}) { + const files = await get_model_files(modelId, { config, dtype, device, model_file_name }); + if (include_tokenizer) { + const tokenizerFiles = await get_tokenizer_files(modelId); + files.push(...tokenizerFiles); + } + if (include_processor) { + const processorFiles = await get_processor_files(modelId); + files.push(...processorFiles); + } + return files; } -class RawVideo { - /** - * @param {RawVideoFrame[]|RawImage[]} frames - * @param {number} duration - */ - constructor(frames, duration) { - if (frames.length > 0 && frames[0] instanceof _image_js__WEBPACK_IMPORTED_MODULE_0__.RawImage) { - // Assume uniform timestamps - frames = frames.map((image, i) => new RawVideoFrame(image, (i + 1) / (frames.length + 1) * duration)); - } - this.frames = /** @type {RawVideoFrame[]} */ (frames); - this.duration = duration; +// src/utils/model_registry/get_pipeline_files.js +async function get_pipeline_files(task, modelId, options = {}) { + task = TASK_ALIASES[task] ?? task; + const taskConfig = SUPPORTED_TASKS[task]; + if (!taskConfig) { + throw new Error( + `Unsupported pipeline task: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS).join(", ")}]` + ); + } + const { type } = taskConfig; + const include_tokenizer = type !== "audio" && type !== "image"; + const include_processor = type !== "text"; + const files = await get_files(modelId, { + ...options, + include_tokenizer, + include_processor + }); + if (task === "text-generation") { + const config = await get_config(modelId, options); + const modelType = resolve_model_type(config); + const textOnlySessions = getTextOnlySessions(modelType); + if (textOnlySessions) { + const allowedPrefixes = Object.values(textOnlySessions).map((s) => `onnx/${s}`); + return files.filter((f) => !f.startsWith("onnx/") || allowedPrefixes.some((p) => f.startsWith(p))); } - - get width() { - return this.frames[0].image.width; + } + return files; +} + +// src/pipelines.js +async function pipeline2(task, model = null, { + progress_callback = null, + config = null, + cache_dir = null, + local_files_only = false, + revision = "main", + device = null, + dtype = null, + subfolder = "onnx", + use_external_data_format = null, + model_file_name = null, + session_options = {} +} = {}) { + task = TASK_ALIASES[task] ?? task; + const pipelineInfo = SUPPORTED_TASKS[task.split("_", 1)[0]]; + if (!pipelineInfo) { + throw Error(`Unsupported pipeline: ${task}. Must be one of [${Object.keys(SUPPORTED_TASKS)}]`); + } + if (!model) { + model = pipelineInfo.default.model; + logger.info(`No model specified. Using default model: "${model}".`); + if (!dtype && pipelineInfo.default.dtype) { + dtype = pipelineInfo.default.dtype; } - get height() { - return this.frames[0].image.height; + } + const expected_files = await get_pipeline_files(task, model, { + device, + dtype + }); + let files_loading = {}; + if (progress_callback) { + try { + const metadata = await Promise.all(expected_files.map(async (file) => get_file_metadata(model, file))); + metadata.forEach((m, i) => { + if (m.exists) { + files_loading[expected_files[i]] = { + loaded: 0, + total: m.size ?? 0 + }; + } + }); + } catch (e) { + logger.warn(`Unable to fetch model file metadata for total progress tracking: ${e}`); } - - get fps() { - return this.frames.length / this.duration; + } + const pretrainedOptions = { + progress_callback: progress_callback ? new DefaultProgressCallback(progress_callback, files_loading) : void 0, + config, + cache_dir, + local_files_only, + revision, + device, + dtype, + subfolder, + use_external_data_format, + model_file_name, + session_options + }; + const hasTokenizer = expected_files.includes("tokenizer.json"); + const hasProcessor = expected_files.includes("preprocessor_config.json"); + const modelClasses = pipelineInfo.model; + let modelPromise; + if (Array.isArray(modelClasses)) { + const resolvedConfig = config ?? await AutoConfig.from_pretrained(model, pretrainedOptions); + const { model_type } = resolvedConfig; + const matchedClass = modelClasses.find((cls) => cls.supports(model_type)); + if (!matchedClass) { + throw Error( + `Unsupported model type "${model_type}" for task "${task}". None of the candidate model classes support this type.` + ); } + modelPromise = matchedClass.from_pretrained(model, { ...pretrainedOptions, config: resolvedConfig }); + } else { + modelPromise = modelClasses.from_pretrained(model, pretrainedOptions); + } + const [tokenizer, processor, model_loaded] = await Promise.all([ + hasTokenizer ? AutoTokenizer.from_pretrained(model, pretrainedOptions) : null, + hasProcessor ? AutoProcessor.from_pretrained(model, pretrainedOptions) : null, + modelPromise + ]); + const results = { task, model: model_loaded }; + if (tokenizer) results.tokenizer = tokenizer; + if (processor) results.processor = processor; + dispatchCallback(progress_callback, { + status: "ready", + task, + model + }); + const pipelineClass = pipelineInfo.pipeline; + return new pipelineClass(results); } - -/** - * Loads a video. - * - * @param {string|Blob|HTMLVideoElement} src The video to process. - * @param {Object} [options] Optional parameters. - * @param {number} [options.num_frames=null] The number of frames to sample uniformly. - * @param {number} [options.fps=null] The number of frames to sample per second. - * - * @returns {Promise} The loaded video. - */ -async function load_video(src, { num_frames = null, fps = null } = {}) { - if (!_env_js__WEBPACK_IMPORTED_MODULE_1__.apis.IS_BROWSER_ENV) { - throw new Error("`load_video` is currently only supported in browser environments."); +// src/generation/streamers.js +var is_chinese_char2 = (cp) => cp >= 19968 && cp <= 40959 || cp >= 13312 && cp <= 19903 || cp >= 131072 && cp <= 173791 || cp >= 173824 && cp <= 177983 || cp >= 177984 && cp <= 178207 || cp >= 178208 && cp <= 183983 || cp >= 63744 && cp <= 64255 || cp >= 194560 && cp <= 195103; +var BaseStreamer = class { + /** + * Function that is called by `.generate()` to push new tokens + * @param {bigint[][]} value + */ + put(value) { + throw Error("Not implemented"); + } + /** + * Function that is called by `.generate()` to signal the end of generation + */ + end() { + throw Error("Not implemented"); + } +}; +var stdout_write = apis.IS_PROCESS_AVAILABLE ? (x) => process.stdout.write(x) : (x) => console.log(x); +var TextStreamer = class extends BaseStreamer { + /** + * + * @param {import('../tokenization_utils.js').PreTrainedTokenizer} tokenizer + * @param {Object} options + * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens + * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding + * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display + * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated + * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method + */ + constructor(tokenizer, { + skip_prompt = false, + callback_function = null, + token_callback_function = null, + skip_special_tokens = true, + decode_kwargs = {}, + ...kwargs + } = {}) { + super(); + this.tokenizer = tokenizer; + this.skip_prompt = skip_prompt; + this.callback_function = callback_function ?? stdout_write; + this.token_callback_function = token_callback_function; + this.decode_kwargs = { skip_special_tokens, ...decode_kwargs, ...kwargs }; + this.token_cache = []; + this.print_len = 0; + this.next_tokens_are_prompt = true; + this.special_ids = new Set(this.tokenizer.all_special_ids.map(BigInt)); + } + /** + * Receives tokens, decodes them, and prints them to stdout as soon as they form entire words. + * @param {bigint[][]} value + */ + put(value) { + if (value.length > 1) { + throw Error("TextStreamer only supports batch size of 1"); + } + const is_prompt = this.next_tokens_are_prompt; + if (is_prompt) { + this.next_tokens_are_prompt = false; + if (this.skip_prompt) return; + } + const tokens = value[0]; + this.token_callback_function?.(tokens); + if (tokens.length === 1 && this.special_ids.has(tokens[0])) { + if (this.decode_kwargs.skip_special_tokens) return; + if (this.token_cache.length > 0) { + const text2 = this.tokenizer.decode(this.token_cache, this.decode_kwargs); + const printable_text2 = text2.slice(this.print_len); + this.on_finalized_text(printable_text2, false); + this.token_cache = []; + this.print_len = 0; + } + const special_text = this.tokenizer.decode(tokens, this.decode_kwargs); + this.on_finalized_text(special_text, false); + return; } - - // TODO: Support efficiently loading all frames using the WebCodecs API. - // Specfically, https://developer.mozilla.org/en-US/docs/Web/API/VideoDecoder - if (num_frames == null && fps == null) { - throw new Error("Either num_frames or fps must be provided."); + this.token_cache = mergeArrays(this.token_cache, tokens); + const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs); + let printable_text; + if (is_prompt || text.endsWith("\n")) { + printable_text = text.slice(this.print_len); + this.token_cache = []; + this.print_len = 0; + } else if (text.length > 0 && is_chinese_char2(text.charCodeAt(text.length - 1))) { + printable_text = text.slice(this.print_len); + this.print_len += printable_text.length; + } else { + printable_text = text.slice(this.print_len, text.lastIndexOf(" ") + 1); + this.print_len += printable_text.length; } - - const frames = []; - - const video = document.createElement("video"); - video.crossOrigin = "anonymous"; - video.muted = true; // mute to allow autoplay and seeking - - if (typeof src === 'string') { - video.src = src; - } else if (src instanceof Blob) { - video.src = URL.createObjectURL(src); - } else if (src instanceof HTMLVideoElement) { - video.src = src.src; + this.on_finalized_text(printable_text, false); + } + /** + * Flushes any remaining cache and prints a newline to stdout. + */ + end() { + let printable_text; + if (this.token_cache.length > 0) { + const text = this.tokenizer.decode(this.token_cache, this.decode_kwargs); + printable_text = text.slice(this.print_len); + this.token_cache = []; + this.print_len = 0; } else { - throw new Error("Invalid URL or video element provided."); + printable_text = ""; } - // Wait for metadata to load to obtain duration - await new Promise((resolve) => video.onloadedmetadata = resolve); - - if (video.seekable.start(0) === video.seekable.end(0)) { - // Fallback: Download entire video if not seekable - const response = await fetch(video.src); - const blob = await response.blob(); - video.src = URL.createObjectURL(blob); - await new Promise((resolve) => video.onloadedmetadata = resolve); + this.next_tokens_are_prompt = true; + this.on_finalized_text(printable_text, true); + } + /** + * Prints the new text to stdout. If the stream is ending, also prints a newline. + * @param {string} text + * @param {boolean} stream_end + */ + on_finalized_text(text, stream_end) { + if (text.length > 0) { + this.callback_function?.(text); } - - const duration = video.duration; - - let count, step; - if (num_frames != null) { - count = num_frames; - step = num_frames === 1 ? 0 : duration / (num_frames - 1); - } else { - step = 1 / fps; - count = Math.floor(duration / step); + if (stream_end && this.callback_function === stdout_write && apis.IS_PROCESS_AVAILABLE) { + this.callback_function?.("\n"); } - - // Build an array of sample times based on num_frames or fps - let sampleTimes = []; - for (let i = 0; i < count; ++i) { - sampleTimes.push(num_frames === 1 ? duration / 2 : i * step); + } +}; +var WhisperTextStreamer = class extends TextStreamer { + /** + * @param {import('../models/whisper/tokenization_whisper.js').WhisperTokenizer} tokenizer + * @param {Object} options + * @param {boolean} [options.skip_prompt=false] Whether to skip the prompt tokens + * @param {function(string): void} [options.callback_function=null] Function to call when a piece of text is ready to display + * @param {function(bigint[]): void} [options.token_callback_function=null] Function to call when a new token is generated + * @param {function(number): void} [options.on_chunk_start=null] Function to call when a new chunk starts + * @param {function(number): void} [options.on_chunk_end=null] Function to call when a chunk ends + * @param {function(): void} [options.on_finalize=null] Function to call when the stream is finalized + * @param {number} [options.time_precision=0.02] Precision of the timestamps + * @param {boolean} [options.skip_special_tokens=true] Whether to skip special tokens when decoding + * @param {Object} [options.decode_kwargs={}] Additional keyword arguments to pass to the tokenizer's decode method + */ + constructor(tokenizer, { + skip_prompt = false, + callback_function = null, + token_callback_function = null, + on_chunk_start = null, + on_chunk_end = null, + on_finalize = null, + time_precision = 0.02, + skip_special_tokens = true, + decode_kwargs = {} + } = {}) { + super(tokenizer, { + skip_prompt, + skip_special_tokens, + callback_function, + token_callback_function, + decode_kwargs + }); + this.timestamp_begin = tokenizer.timestamp_begin; + this.on_chunk_start = on_chunk_start; + this.on_chunk_end = on_chunk_end; + this.on_finalize = on_finalize; + this.time_precision = time_precision; + this.waiting_for_timestamp = false; + } + /** + * @param {bigint[][]} value + */ + put(value) { + if (value.length > 1) { + throw Error("WhisperTextStreamer only supports batch size of 1"); + } + const tokens = value[0]; + if (tokens.length === 1) { + const offset = Number(tokens[0]) - this.timestamp_begin; + if (offset >= 0) { + const time = offset * this.time_precision; + if (this.waiting_for_timestamp) { + this.on_chunk_end?.(time); + } else { + this.on_chunk_start?.(time); + } + this.waiting_for_timestamp = !this.waiting_for_timestamp; + this.token_callback_function?.(tokens); + return; + } } + return super.put(value); + } + end() { + super.end(); + this.on_finalize?.(); + } +}; - const canvas = document.createElement("canvas"); - canvas.width = video.videoWidth; - canvas.height = video.videoHeight; - const ctx = canvas.getContext("2d", { willReadFrequently: true }); - for (const t of sampleTimes) { - video.currentTime = t; - await new Promise((resolve) => { - video.onseeked = resolve; - }); - ctx.drawImage(video, 0, 0, canvas.width, canvas.height); - const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - const frameData = new _image_js__WEBPACK_IMPORTED_MODULE_0__.RawImage(imageData.data, canvas.width, canvas.height, 4); - - const frame = new RawVideoFrame(frameData, t); - frames.push(frame); - } - - // Clean up video element. - video.remove(); - - return new RawVideo(frames, duration); -} - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/create fake namespace object */ -/******/ (() => { -/******/ var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__); -/******/ var leafPrototypes; -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 16: return value when it's Promise-like -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = this(value); -/******/ if(mode & 8) return value; -/******/ if(typeof value === 'object' && value) { -/******/ if((mode & 4) && value.__esModule) return value; -/******/ if((mode & 16) && typeof value.then === 'function') return value; -/******/ } -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ var def = {}; -/******/ leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)]; -/******/ for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) { -/******/ Object.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key]))); -/******/ } -/******/ def['default'] = () => (value); -/******/ __webpack_require__.d(ns, def); -/******/ return ns; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __webpack_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/publicPath */ -/******/ (() => { -/******/ var scriptUrl = ''; -/******/ if (typeof import.meta.url === "string") scriptUrl = import.meta.url -/******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration -/******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic. -/******/ scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/"); -/******/ __webpack_require__.p = scriptUrl; -/******/ })(); -/******/ -/******/ /* webpack/runtime/base uri */ -/******/ (() => { -/******/ __webpack_require__.b = undefined; -/******/ })(); -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; -// This entry needs to be wrapped in an IIFE because it needs to be isolated against other modules in the chunk. -(() => { -/*!*****************************!*\ - !*** ./src/transformers.js ***! - \*****************************/ -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ ASTFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ASTFeatureExtractor), -/* harmony export */ ASTForAudioClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTForAudioClassification), -/* harmony export */ ASTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTModel), -/* harmony export */ ASTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ASTPreTrainedModel), -/* harmony export */ AlbertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForMaskedLM), -/* harmony export */ AlbertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForQuestionAnswering), -/* harmony export */ AlbertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertForSequenceClassification), -/* harmony export */ AlbertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertModel), -/* harmony export */ AlbertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AlbertPreTrainedModel), -/* harmony export */ AlbertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AlbertTokenizer), -/* harmony export */ ArceeForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ArceeForCausalLM), -/* harmony export */ ArceeModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ArceeModel), -/* harmony export */ ArceePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ArceePreTrainedModel), -/* harmony export */ AudioClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.AudioClassificationPipeline), -/* harmony export */ AutoConfig: () => (/* reexport safe */ _configs_js__WEBPACK_IMPORTED_MODULE_4__.AutoConfig), -/* harmony export */ AutoFeatureExtractor: () => (/* reexport safe */ _models_auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_12__.AutoFeatureExtractor), -/* harmony export */ AutoImageProcessor: () => (/* reexport safe */ _models_auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_15__.AutoImageProcessor), -/* harmony export */ AutoModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModel), -/* harmony export */ AutoModelForAudioClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioClassification), -/* harmony export */ AutoModelForAudioFrameClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioFrameClassification), -/* harmony export */ AutoModelForAudioTextToText: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForAudioTextToText), -/* harmony export */ AutoModelForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForCTC), -/* harmony export */ AutoModelForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForCausalLM), -/* harmony export */ AutoModelForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForDepthEstimation), -/* harmony export */ AutoModelForDocumentQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForDocumentQuestionAnswering), -/* harmony export */ AutoModelForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageClassification), -/* harmony export */ AutoModelForImageFeatureExtraction: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageFeatureExtraction), -/* harmony export */ AutoModelForImageMatting: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageMatting), -/* harmony export */ AutoModelForImageSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageSegmentation), -/* harmony export */ AutoModelForImageTextToText: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageTextToText), -/* harmony export */ AutoModelForImageToImage: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForImageToImage), -/* harmony export */ AutoModelForMaskGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForMaskGeneration), -/* harmony export */ AutoModelForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForMaskedLM), -/* harmony export */ AutoModelForNormalEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForNormalEstimation), -/* harmony export */ AutoModelForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForObjectDetection), -/* harmony export */ AutoModelForPoseEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForPoseEstimation), -/* harmony export */ AutoModelForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForQuestionAnswering), -/* harmony export */ AutoModelForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSemanticSegmentation), -/* harmony export */ AutoModelForSeq2SeqLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSeq2SeqLM), -/* harmony export */ AutoModelForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSequenceClassification), -/* harmony export */ AutoModelForSpeechSeq2Seq: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForSpeechSeq2Seq), -/* harmony export */ AutoModelForTextToSpectrogram: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTextToSpectrogram), -/* harmony export */ AutoModelForTextToWaveform: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTextToWaveform), -/* harmony export */ AutoModelForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForTokenClassification), -/* harmony export */ AutoModelForUniversalSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForUniversalSegmentation), -/* harmony export */ AutoModelForVision2Seq: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForVision2Seq), -/* harmony export */ AutoModelForXVector: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForXVector), -/* harmony export */ AutoModelForZeroShotObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.AutoModelForZeroShotObjectDetection), -/* harmony export */ AutoProcessor: () => (/* reexport safe */ _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_18__.AutoProcessor), -/* harmony export */ AutoTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.AutoTokenizer), -/* harmony export */ AutomaticSpeechRecognitionPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.AutomaticSpeechRecognitionPipeline), -/* harmony export */ BackgroundRemovalPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.BackgroundRemovalPipeline), -/* harmony export */ BartForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartForConditionalGeneration), -/* harmony export */ BartForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartForSequenceClassification), -/* harmony export */ BartModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartModel), -/* harmony export */ BartPretrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BartPretrainedModel), -/* harmony export */ BartTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BartTokenizer), -/* harmony export */ BaseModelOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BaseModelOutput), -/* harmony export */ BaseStreamer: () => (/* reexport safe */ _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__.BaseStreamer), -/* harmony export */ BeitFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.BeitFeatureExtractor), -/* harmony export */ BeitForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitForImageClassification), -/* harmony export */ BeitModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitModel), -/* harmony export */ BeitPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BeitPreTrainedModel), -/* harmony export */ BertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForMaskedLM), -/* harmony export */ BertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForQuestionAnswering), -/* harmony export */ BertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForSequenceClassification), -/* harmony export */ BertForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertForTokenClassification), -/* harmony export */ BertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertModel), -/* harmony export */ BertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BertPreTrainedModel), -/* harmony export */ BertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BertTokenizer), -/* harmony export */ BitImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.BitImageProcessor), -/* harmony export */ BlenderbotForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotForConditionalGeneration), -/* harmony export */ BlenderbotModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotModel), -/* harmony export */ BlenderbotPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotPreTrainedModel), -/* harmony export */ BlenderbotSmallForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallForConditionalGeneration), -/* harmony export */ BlenderbotSmallModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallModel), -/* harmony export */ BlenderbotSmallPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BlenderbotSmallPreTrainedModel), -/* harmony export */ BlenderbotSmallTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BlenderbotSmallTokenizer), -/* harmony export */ BlenderbotTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BlenderbotTokenizer), -/* harmony export */ BloomForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomForCausalLM), -/* harmony export */ BloomModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomModel), -/* harmony export */ BloomPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.BloomPreTrainedModel), -/* harmony export */ BloomTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.BloomTokenizer), -/* harmony export */ CLIPFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.CLIPFeatureExtractor), -/* harmony export */ CLIPImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.CLIPImageProcessor), -/* harmony export */ CLIPModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPModel), -/* harmony export */ CLIPPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPPreTrainedModel), -/* harmony export */ CLIPSegForImageSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegForImageSegmentation), -/* harmony export */ CLIPSegModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegModel), -/* harmony export */ CLIPSegPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPSegPreTrainedModel), -/* harmony export */ CLIPTextModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPTextModel), -/* harmony export */ CLIPTextModelWithProjection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPTextModelWithProjection), -/* harmony export */ CLIPTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CLIPTokenizer), -/* harmony export */ CLIPVisionModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPVisionModel), -/* harmony export */ CLIPVisionModelWithProjection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CLIPVisionModelWithProjection), -/* harmony export */ CamembertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForMaskedLM), -/* harmony export */ CamembertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForQuestionAnswering), -/* harmony export */ CamembertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForSequenceClassification), -/* harmony export */ CamembertForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertForTokenClassification), -/* harmony export */ CamembertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertModel), -/* harmony export */ CamembertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CamembertPreTrainedModel), -/* harmony export */ CamembertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CamembertTokenizer), -/* harmony export */ CausalLMOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CausalLMOutput), -/* harmony export */ CausalLMOutputWithPast: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CausalLMOutputWithPast), -/* harmony export */ ChineseCLIPFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ChineseCLIPFeatureExtractor), -/* harmony export */ ChineseCLIPModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPModel), -/* harmony export */ ChineseCLIPPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ChineseCLIPPreTrainedModel), -/* harmony export */ ClapAudioModelWithProjection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapAudioModelWithProjection), -/* harmony export */ ClapFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ClapFeatureExtractor), -/* harmony export */ ClapModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapModel), -/* harmony export */ ClapPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapPreTrainedModel), -/* harmony export */ ClapTextModelWithProjection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ClapTextModelWithProjection), -/* harmony export */ ClassifierFreeGuidanceLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.ClassifierFreeGuidanceLogitsProcessor), -/* harmony export */ CodeGenForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenForCausalLM), -/* harmony export */ CodeGenModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenModel), -/* harmony export */ CodeGenPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CodeGenPreTrainedModel), -/* harmony export */ CodeGenTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CodeGenTokenizer), -/* harmony export */ CodeLlamaTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CodeLlamaTokenizer), -/* harmony export */ CohereForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CohereForCausalLM), -/* harmony export */ CohereModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CohereModel), -/* harmony export */ CoherePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.CoherePreTrainedModel), -/* harmony export */ CohereTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.CohereTokenizer), -/* harmony export */ ConvBertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForMaskedLM), -/* harmony export */ ConvBertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForQuestionAnswering), -/* harmony export */ ConvBertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForSequenceClassification), -/* harmony export */ ConvBertForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertForTokenClassification), -/* harmony export */ ConvBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertModel), -/* harmony export */ ConvBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvBertPreTrainedModel), -/* harmony export */ ConvBertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.ConvBertTokenizer), -/* harmony export */ ConvNextFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ConvNextFeatureExtractor), -/* harmony export */ ConvNextForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextForImageClassification), -/* harmony export */ ConvNextImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ConvNextImageProcessor), -/* harmony export */ ConvNextModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextModel), -/* harmony export */ ConvNextPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextPreTrainedModel), -/* harmony export */ ConvNextV2ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2ForImageClassification), -/* harmony export */ ConvNextV2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2Model), -/* harmony export */ ConvNextV2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ConvNextV2PreTrainedModel), -/* harmony export */ DFineForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DFineForObjectDetection), -/* harmony export */ DFineModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DFineModel), -/* harmony export */ DFinePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DFinePreTrainedModel), -/* harmony export */ DINOv3ConvNextModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ConvNextModel), -/* harmony export */ DINOv3ConvNextPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ConvNextPreTrainedModel), -/* harmony export */ DINOv3ViTImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DINOv3ViTImageProcessor), -/* harmony export */ DINOv3ViTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ViTModel), -/* harmony export */ DINOv3ViTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DINOv3ViTPreTrainedModel), -/* harmony export */ DPTFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DPTFeatureExtractor), -/* harmony export */ DPTForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTForDepthEstimation), -/* harmony export */ DPTImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DPTImageProcessor), -/* harmony export */ DPTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTModel), -/* harmony export */ DPTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DPTPreTrainedModel), -/* harmony export */ DacDecoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DacDecoderModel), -/* harmony export */ DacDecoderOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DacDecoderOutput), -/* harmony export */ DacEncoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DacEncoderModel), -/* harmony export */ DacEncoderOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DacEncoderOutput), -/* harmony export */ DacFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.DacFeatureExtractor), -/* harmony export */ DacModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DacModel), -/* harmony export */ DacPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DacPreTrainedModel), -/* harmony export */ DataTypeMap: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.DataTypeMap), -/* harmony export */ DebertaForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForMaskedLM), -/* harmony export */ DebertaForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForQuestionAnswering), -/* harmony export */ DebertaForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForSequenceClassification), -/* harmony export */ DebertaForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaForTokenClassification), -/* harmony export */ DebertaModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaModel), -/* harmony export */ DebertaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaPreTrainedModel), -/* harmony export */ DebertaTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DebertaTokenizer), -/* harmony export */ DebertaV2ForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForMaskedLM), -/* harmony export */ DebertaV2ForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForQuestionAnswering), -/* harmony export */ DebertaV2ForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForSequenceClassification), -/* harmony export */ DebertaV2ForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2ForTokenClassification), -/* harmony export */ DebertaV2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2Model), -/* harmony export */ DebertaV2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DebertaV2PreTrainedModel), -/* harmony export */ DebertaV2Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DebertaV2Tokenizer), -/* harmony export */ DecisionTransformerModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DecisionTransformerModel), -/* harmony export */ DecisionTransformerPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DecisionTransformerPreTrainedModel), -/* harmony export */ DeiTFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DeiTFeatureExtractor), -/* harmony export */ DeiTForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTForImageClassification), -/* harmony export */ DeiTImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DeiTImageProcessor), -/* harmony export */ DeiTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTModel), -/* harmony export */ DeiTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DeiTPreTrainedModel), -/* harmony export */ DepthAnythingForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthAnythingForDepthEstimation), -/* harmony export */ DepthAnythingPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthAnythingPreTrainedModel), -/* harmony export */ DepthEstimationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.DepthEstimationPipeline), -/* harmony export */ DepthProForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthProForDepthEstimation), -/* harmony export */ DepthProPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DepthProPreTrainedModel), -/* harmony export */ DetrFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DetrFeatureExtractor), -/* harmony export */ DetrForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrForObjectDetection), -/* harmony export */ DetrForSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrForSegmentation), -/* harmony export */ DetrImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DetrImageProcessor), -/* harmony export */ DetrModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrModel), -/* harmony export */ DetrObjectDetectionOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrObjectDetectionOutput), -/* harmony export */ DetrPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrPreTrainedModel), -/* harmony export */ DetrSegmentationOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DetrSegmentationOutput), -/* harmony export */ Dinov2ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2ForImageClassification), -/* harmony export */ Dinov2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2Model), -/* harmony export */ Dinov2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2PreTrainedModel), -/* harmony export */ Dinov2WithRegistersForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2WithRegistersForImageClassification), -/* harmony export */ Dinov2WithRegistersModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2WithRegistersModel), -/* harmony export */ Dinov2WithRegistersPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Dinov2WithRegistersPreTrainedModel), -/* harmony export */ DistilBertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForMaskedLM), -/* harmony export */ DistilBertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForQuestionAnswering), -/* harmony export */ DistilBertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForSequenceClassification), -/* harmony export */ DistilBertForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertForTokenClassification), -/* harmony export */ DistilBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertModel), -/* harmony export */ DistilBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DistilBertPreTrainedModel), -/* harmony export */ DistilBertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.DistilBertTokenizer), -/* harmony export */ DocumentQuestionAnsweringPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.DocumentQuestionAnsweringPipeline), -/* harmony export */ DonutFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DonutFeatureExtractor), -/* harmony export */ DonutImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.DonutImageProcessor), -/* harmony export */ DonutSwinModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DonutSwinModel), -/* harmony export */ DonutSwinPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.DonutSwinPreTrainedModel), -/* harmony export */ EfficientNetForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetForImageClassification), -/* harmony export */ EfficientNetImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.EfficientNetImageProcessor), -/* harmony export */ EfficientNetModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetModel), -/* harmony export */ EfficientNetPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EfficientNetPreTrainedModel), -/* harmony export */ ElectraForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForMaskedLM), -/* harmony export */ ElectraForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForQuestionAnswering), -/* harmony export */ ElectraForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForSequenceClassification), -/* harmony export */ ElectraForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraForTokenClassification), -/* harmony export */ ElectraModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraModel), -/* harmony export */ ElectraPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ElectraPreTrainedModel), -/* harmony export */ ElectraTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.ElectraTokenizer), -/* harmony export */ EncodecFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.EncodecFeatureExtractor), -/* harmony export */ EosTokenCriteria: () => (/* reexport safe */ _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.EosTokenCriteria), -/* harmony export */ Ernie4_5_ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Ernie4_5_ForCausalLM), -/* harmony export */ Ernie4_5_Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Ernie4_5_Model), -/* harmony export */ Ernie4_5_PretrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Ernie4_5_PretrainedModel), -/* harmony export */ Ernie4_5_Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Ernie4_5_Tokenizer), -/* harmony export */ EsmForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForMaskedLM), -/* harmony export */ EsmForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForSequenceClassification), -/* harmony export */ EsmForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmForTokenClassification), -/* harmony export */ EsmModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmModel), -/* harmony export */ EsmPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.EsmPreTrainedModel), -/* harmony export */ EsmTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.EsmTokenizer), -/* harmony export */ ExaoneForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ExaoneForCausalLM), -/* harmony export */ ExaoneModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ExaoneModel), -/* harmony export */ ExaonePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ExaonePreTrainedModel), -/* harmony export */ FFT: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.FFT), -/* harmony export */ FalconForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconForCausalLM), -/* harmony export */ FalconModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconModel), -/* harmony export */ FalconPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FalconPreTrainedModel), -/* harmony export */ FalconTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.FalconTokenizer), -/* harmony export */ FastViTForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTForImageClassification), -/* harmony export */ FastViTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTModel), -/* harmony export */ FastViTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.FastViTPreTrainedModel), -/* harmony export */ FeatureExtractionPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.FeatureExtractionPipeline), -/* harmony export */ FeatureExtractor: () => (/* reexport safe */ _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_10__.FeatureExtractor), -/* harmony export */ FillMaskPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.FillMaskPipeline), -/* harmony export */ Florence2ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Florence2ForConditionalGeneration), -/* harmony export */ Florence2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Florence2PreTrainedModel), -/* harmony export */ Florence2Processor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Florence2Processor), -/* harmony export */ ForcedBOSTokenLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.ForcedBOSTokenLogitsProcessor), -/* harmony export */ ForcedEOSTokenLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.ForcedEOSTokenLogitsProcessor), -/* harmony export */ GLPNFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.GLPNFeatureExtractor), -/* harmony export */ GLPNForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNForDepthEstimation), -/* harmony export */ GLPNModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNModel), -/* harmony export */ GLPNPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GLPNPreTrainedModel), -/* harmony export */ GPT2LMHeadModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2LMHeadModel), -/* harmony export */ GPT2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2Model), -/* harmony export */ GPT2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPT2PreTrainedModel), -/* harmony export */ GPT2Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GPT2Tokenizer), -/* harmony export */ GPTBigCodeForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodeForCausalLM), -/* harmony export */ GPTBigCodeModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodeModel), -/* harmony export */ GPTBigCodePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTBigCodePreTrainedModel), -/* harmony export */ GPTJForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJForCausalLM), -/* harmony export */ GPTJModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJModel), -/* harmony export */ GPTJPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTJPreTrainedModel), -/* harmony export */ GPTNeoForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoForCausalLM), -/* harmony export */ GPTNeoModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoModel), -/* harmony export */ GPTNeoPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoPreTrainedModel), -/* harmony export */ GPTNeoXForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXForCausalLM), -/* harmony export */ GPTNeoXModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXModel), -/* harmony export */ GPTNeoXPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GPTNeoXPreTrainedModel), -/* harmony export */ GPTNeoXTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GPTNeoXTokenizer), -/* harmony export */ Gemma2ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma2ForCausalLM), -/* harmony export */ Gemma2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma2Model), -/* harmony export */ Gemma2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma2PreTrainedModel), -/* harmony export */ Gemma3ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3ForCausalLM), -/* harmony export */ Gemma3Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3Model), -/* harmony export */ Gemma3PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3PreTrainedModel), -/* harmony export */ Gemma3nAudioFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.Gemma3nAudioFeatureExtractor), -/* harmony export */ Gemma3nForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3nForConditionalGeneration), -/* harmony export */ Gemma3nPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Gemma3nPreTrainedModel), -/* harmony export */ Gemma3nProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Gemma3nProcessor), -/* harmony export */ GemmaForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GemmaForCausalLM), -/* harmony export */ GemmaModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GemmaModel), -/* harmony export */ GemmaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GemmaPreTrainedModel), -/* harmony export */ GemmaTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.GemmaTokenizer), -/* harmony export */ GlmForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GlmForCausalLM), -/* harmony export */ GlmModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GlmModel), -/* harmony export */ GlmPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GlmPreTrainedModel), -/* harmony export */ GraniteForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteForCausalLM), -/* harmony export */ GraniteModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GraniteModel), -/* harmony export */ GranitePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GranitePreTrainedModel), -/* harmony export */ Grok1Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Grok1Tokenizer), -/* harmony export */ GroundingDinoForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GroundingDinoForObjectDetection), -/* harmony export */ GroundingDinoImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.GroundingDinoImageProcessor), -/* harmony export */ GroundingDinoPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GroundingDinoPreTrainedModel), -/* harmony export */ GroundingDinoProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.GroundingDinoProcessor), -/* harmony export */ GroupViTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GroupViTModel), -/* harmony export */ GroupViTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.GroupViTPreTrainedModel), -/* harmony export */ HeliumForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HeliumForCausalLM), -/* harmony export */ HeliumModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HeliumModel), -/* harmony export */ HeliumPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HeliumPreTrainedModel), -/* harmony export */ HerbertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.HerbertTokenizer), -/* harmony export */ HieraForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HieraForImageClassification), -/* harmony export */ HieraModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HieraModel), -/* harmony export */ HieraPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HieraPreTrainedModel), -/* harmony export */ HubertForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertForCTC), -/* harmony export */ HubertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertForSequenceClassification), -/* harmony export */ HubertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertModel), -/* harmony export */ HubertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.HubertPreTrainedModel), -/* harmony export */ IJepaForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.IJepaForImageClassification), -/* harmony export */ IJepaModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.IJepaModel), -/* harmony export */ IJepaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.IJepaPreTrainedModel), -/* harmony export */ Idefics3ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Idefics3ForConditionalGeneration), -/* harmony export */ Idefics3ImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Idefics3ImageProcessor), -/* harmony export */ Idefics3PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Idefics3PreTrainedModel), -/* harmony export */ Idefics3Processor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Idefics3Processor), -/* harmony export */ ImageClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageClassificationPipeline), -/* harmony export */ ImageFeatureExtractionPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageFeatureExtractionPipeline), -/* harmony export */ ImageFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.ImageFeatureExtractor), -/* harmony export */ ImageMattingOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ImageMattingOutput), -/* harmony export */ ImageProcessor: () => (/* reexport safe */ _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_13__.ImageProcessor), -/* harmony export */ ImageSegmentationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageSegmentationPipeline), -/* harmony export */ ImageToImagePipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageToImagePipeline), -/* harmony export */ ImageToTextPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ImageToTextPipeline), -/* harmony export */ InterruptableStoppingCriteria: () => (/* reexport safe */ _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.InterruptableStoppingCriteria), -/* harmony export */ JAISLMHeadModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JAISLMHeadModel), -/* harmony export */ JAISModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JAISModel), -/* harmony export */ JAISPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JAISPreTrainedModel), -/* harmony export */ JinaCLIPImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.JinaCLIPImageProcessor), -/* harmony export */ JinaCLIPModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPModel), -/* harmony export */ JinaCLIPPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPPreTrainedModel), -/* harmony export */ JinaCLIPProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.JinaCLIPProcessor), -/* harmony export */ JinaCLIPTextModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPTextModel), -/* harmony export */ JinaCLIPVisionModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.JinaCLIPVisionModel), -/* harmony export */ Lfm2ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Lfm2ForCausalLM), -/* harmony export */ Lfm2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Lfm2Model), -/* harmony export */ Lfm2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Lfm2PreTrainedModel), -/* harmony export */ LiteWhisperForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LiteWhisperForConditionalGeneration), -/* harmony export */ LlamaForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaForCausalLM), -/* harmony export */ LlamaModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaModel), -/* harmony export */ LlamaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlamaPreTrainedModel), -/* harmony export */ LlamaTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.LlamaTokenizer), -/* harmony export */ LlavaForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaForConditionalGeneration), -/* harmony export */ LlavaOnevisionForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaOnevisionForConditionalGeneration), -/* harmony export */ LlavaOnevisionImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.LlavaOnevisionImageProcessor), -/* harmony export */ LlavaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaPreTrainedModel), -/* harmony export */ LlavaProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.LlavaProcessor), -/* harmony export */ LlavaQwen2ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LlavaQwen2ForCausalLM), -/* harmony export */ LogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.LogitsProcessor), -/* harmony export */ LogitsProcessorList: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.LogitsProcessorList), -/* harmony export */ LogitsWarper: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.LogitsWarper), -/* harmony export */ LongT5ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5ForConditionalGeneration), -/* harmony export */ LongT5Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5Model), -/* harmony export */ LongT5PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.LongT5PreTrainedModel), -/* harmony export */ M2M100ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100ForConditionalGeneration), -/* harmony export */ M2M100Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100Model), -/* harmony export */ M2M100PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.M2M100PreTrainedModel), -/* harmony export */ M2M100Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.M2M100Tokenizer), -/* harmony export */ MBart50Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MBart50Tokenizer), -/* harmony export */ MBartForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForCausalLM), -/* harmony export */ MBartForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForConditionalGeneration), -/* harmony export */ MBartForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartForSequenceClassification), -/* harmony export */ MBartModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartModel), -/* harmony export */ MBartPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MBartPreTrainedModel), -/* harmony export */ MBartTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MBartTokenizer), -/* harmony export */ MPNetForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForMaskedLM), -/* harmony export */ MPNetForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForQuestionAnswering), -/* harmony export */ MPNetForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForSequenceClassification), -/* harmony export */ MPNetForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetForTokenClassification), -/* harmony export */ MPNetModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetModel), -/* harmony export */ MPNetPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MPNetPreTrainedModel), -/* harmony export */ MPNetTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MPNetTokenizer), -/* harmony export */ MT5ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5ForConditionalGeneration), -/* harmony export */ MT5Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5Model), -/* harmony export */ MT5PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MT5PreTrainedModel), -/* harmony export */ MarianMTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianMTModel), -/* harmony export */ MarianModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianModel), -/* harmony export */ MarianPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MarianPreTrainedModel), -/* harmony export */ MarianTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MarianTokenizer), -/* harmony export */ Mask2FormerImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Mask2FormerImageProcessor), -/* harmony export */ MaskFormerFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MaskFormerFeatureExtractor), -/* harmony export */ MaskFormerForInstanceSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskFormerForInstanceSegmentation), -/* harmony export */ MaskFormerImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MaskFormerImageProcessor), -/* harmony export */ MaskFormerModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskFormerModel), -/* harmony export */ MaskFormerPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskFormerPreTrainedModel), -/* harmony export */ MaskedLMOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MaskedLMOutput), -/* harmony export */ MaxLengthCriteria: () => (/* reexport safe */ _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.MaxLengthCriteria), -/* harmony export */ Metric3DForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3DForDepthEstimation), -/* harmony export */ Metric3DPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3DPreTrainedModel), -/* harmony export */ Metric3Dv2ForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3Dv2ForDepthEstimation), -/* harmony export */ Metric3Dv2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Metric3Dv2PreTrainedModel), -/* harmony export */ MgpstrForSceneTextRecognition: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MgpstrForSceneTextRecognition), -/* harmony export */ MgpstrModelOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MgpstrModelOutput), -/* harmony export */ MgpstrPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MgpstrPreTrainedModel), -/* harmony export */ MgpstrProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.MgpstrProcessor), -/* harmony export */ MgpstrTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MgpstrTokenizer), -/* harmony export */ MimiDecoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiDecoderModel), -/* harmony export */ MimiDecoderOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiDecoderOutput), -/* harmony export */ MimiEncoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiEncoderModel), -/* harmony export */ MimiEncoderOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiEncoderOutput), -/* harmony export */ MimiModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiModel), -/* harmony export */ MimiPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MimiPreTrainedModel), -/* harmony export */ MinLengthLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.MinLengthLogitsProcessor), -/* harmony export */ MinNewTokensLengthLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.MinNewTokensLengthLogitsProcessor), -/* harmony export */ MistralForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralForCausalLM), -/* harmony export */ MistralModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralModel), -/* harmony export */ MistralPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MistralPreTrainedModel), -/* harmony export */ MobileBertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForMaskedLM), -/* harmony export */ MobileBertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForQuestionAnswering), -/* harmony export */ MobileBertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertForSequenceClassification), -/* harmony export */ MobileBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertModel), -/* harmony export */ MobileBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileBertPreTrainedModel), -/* harmony export */ MobileBertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.MobileBertTokenizer), -/* harmony export */ MobileLLMForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileLLMForCausalLM), -/* harmony export */ MobileLLMModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileLLMModel), -/* harmony export */ MobileLLMPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileLLMPreTrainedModel), -/* harmony export */ MobileNetV1FeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV1FeatureExtractor), -/* harmony export */ MobileNetV1ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1ForImageClassification), -/* harmony export */ MobileNetV1ForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1ForSemanticSegmentation), -/* harmony export */ MobileNetV1ImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV1ImageProcessor), -/* harmony export */ MobileNetV1Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1Model), -/* harmony export */ MobileNetV1PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV1PreTrainedModel), -/* harmony export */ MobileNetV2FeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV2FeatureExtractor), -/* harmony export */ MobileNetV2ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2ForImageClassification), -/* harmony export */ MobileNetV2ForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2ForSemanticSegmentation), -/* harmony export */ MobileNetV2ImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV2ImageProcessor), -/* harmony export */ MobileNetV2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2Model), -/* harmony export */ MobileNetV2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV2PreTrainedModel), -/* harmony export */ MobileNetV3FeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV3FeatureExtractor), -/* harmony export */ MobileNetV3ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3ForImageClassification), -/* harmony export */ MobileNetV3ForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3ForSemanticSegmentation), -/* harmony export */ MobileNetV3ImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV3ImageProcessor), -/* harmony export */ MobileNetV3Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3Model), -/* harmony export */ MobileNetV3PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV3PreTrainedModel), -/* harmony export */ MobileNetV4FeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV4FeatureExtractor), -/* harmony export */ MobileNetV4ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4ForImageClassification), -/* harmony export */ MobileNetV4ForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4ForSemanticSegmentation), -/* harmony export */ MobileNetV4ImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileNetV4ImageProcessor), -/* harmony export */ MobileNetV4Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4Model), -/* harmony export */ MobileNetV4PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileNetV4PreTrainedModel), -/* harmony export */ MobileViTFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileViTFeatureExtractor), -/* harmony export */ MobileViTForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTForImageClassification), -/* harmony export */ MobileViTImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.MobileViTImageProcessor), -/* harmony export */ MobileViTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTModel), -/* harmony export */ MobileViTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTPreTrainedModel), -/* harmony export */ MobileViTV2ForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2ForImageClassification), -/* harmony export */ MobileViTV2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2Model), -/* harmony export */ MobileViTV2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MobileViTV2PreTrainedModel), -/* harmony export */ ModelOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModelOutput), -/* harmony export */ ModernBertDecoderForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertDecoderForCausalLM), -/* harmony export */ ModernBertDecoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertDecoderModel), -/* harmony export */ ModernBertDecoderPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertDecoderPreTrainedModel), -/* harmony export */ ModernBertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertForMaskedLM), -/* harmony export */ ModernBertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertForSequenceClassification), -/* harmony export */ ModernBertForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertForTokenClassification), -/* harmony export */ ModernBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertModel), -/* harmony export */ ModernBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ModernBertPreTrainedModel), -/* harmony export */ Moondream1ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Moondream1ForConditionalGeneration), -/* harmony export */ MoonshineFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.MoonshineFeatureExtractor), -/* harmony export */ MoonshineForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MoonshineForConditionalGeneration), -/* harmony export */ MoonshineModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MoonshineModel), -/* harmony export */ MoonshinePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MoonshinePreTrainedModel), -/* harmony export */ MoonshineProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.MoonshineProcessor), -/* harmony export */ MptForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MptForCausalLM), -/* harmony export */ MptModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MptModel), -/* harmony export */ MptPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MptPreTrainedModel), -/* harmony export */ MultiModalityCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MultiModalityCausalLM), -/* harmony export */ MultiModalityPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MultiModalityPreTrainedModel), -/* harmony export */ MusicgenForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenForCausalLM), -/* harmony export */ MusicgenForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenForConditionalGeneration), -/* harmony export */ MusicgenModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenModel), -/* harmony export */ MusicgenPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.MusicgenPreTrainedModel), -/* harmony export */ NeoBertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForMaskedLM), -/* harmony export */ NeoBertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForQuestionAnswering), -/* harmony export */ NeoBertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForSequenceClassification), -/* harmony export */ NeoBertForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertForTokenClassification), -/* harmony export */ NeoBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertModel), -/* harmony export */ NeoBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NeoBertPreTrainedModel), -/* harmony export */ NllbTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.NllbTokenizer), -/* harmony export */ NoBadWordsLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.NoBadWordsLogitsProcessor), -/* harmony export */ NoRepeatNGramLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.NoRepeatNGramLogitsProcessor), -/* harmony export */ NomicBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NomicBertModel), -/* harmony export */ NomicBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.NomicBertPreTrainedModel), -/* harmony export */ NougatImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.NougatImageProcessor), -/* harmony export */ NougatTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.NougatTokenizer), -/* harmony export */ OPTForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTForCausalLM), -/* harmony export */ OPTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTModel), -/* harmony export */ OPTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OPTPreTrainedModel), -/* harmony export */ ObjectDetectionPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ObjectDetectionPipeline), -/* harmony export */ Olmo2ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Olmo2ForCausalLM), -/* harmony export */ Olmo2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Olmo2Model), -/* harmony export */ Olmo2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Olmo2PreTrainedModel), -/* harmony export */ OlmoForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OlmoForCausalLM), -/* harmony export */ OlmoModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OlmoModel), -/* harmony export */ OlmoPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OlmoPreTrainedModel), -/* harmony export */ OpenELMForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OpenELMForCausalLM), -/* harmony export */ OpenELMModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OpenELMModel), -/* harmony export */ OpenELMPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OpenELMPreTrainedModel), -/* harmony export */ OwlViTFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.OwlViTFeatureExtractor), -/* harmony export */ OwlViTForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTForObjectDetection), -/* harmony export */ OwlViTImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.OwlViTImageProcessor), -/* harmony export */ OwlViTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTModel), -/* harmony export */ OwlViTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.OwlViTPreTrainedModel), -/* harmony export */ OwlViTProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.OwlViTProcessor), -/* harmony export */ Owlv2ForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2ForObjectDetection), -/* harmony export */ Owlv2ImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Owlv2ImageProcessor), -/* harmony export */ Owlv2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2Model), -/* harmony export */ Owlv2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Owlv2PreTrainedModel), -/* harmony export */ PaliGemmaForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PaliGemmaForConditionalGeneration), -/* harmony export */ PaliGemmaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PaliGemmaPreTrainedModel), -/* harmony export */ PaliGemmaProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.PaliGemmaProcessor), -/* harmony export */ PatchTSMixerForPrediction: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSMixerForPrediction), -/* harmony export */ PatchTSMixerModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSMixerModel), -/* harmony export */ PatchTSMixerPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSMixerPreTrainedModel), -/* harmony export */ PatchTSTForPrediction: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSTForPrediction), -/* harmony export */ PatchTSTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSTModel), -/* harmony export */ PatchTSTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PatchTSTPreTrainedModel), -/* harmony export */ Phi3ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3ForCausalLM), -/* harmony export */ Phi3Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3Model), -/* harmony export */ Phi3PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3PreTrainedModel), -/* harmony export */ Phi3VForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3VForCausalLM), -/* harmony export */ Phi3VImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Phi3VImageProcessor), -/* harmony export */ Phi3VPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Phi3VPreTrainedModel), -/* harmony export */ Phi3VProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Phi3VProcessor), -/* harmony export */ PhiForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiForCausalLM), -/* harmony export */ PhiModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiModel), -/* harmony export */ PhiPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PhiPreTrainedModel), -/* harmony export */ Pipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.Pipeline), -/* harmony export */ PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PreTrainedModel), -/* harmony export */ PreTrainedTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.PreTrainedTokenizer), -/* harmony export */ PretrainedConfig: () => (/* reexport safe */ _configs_js__WEBPACK_IMPORTED_MODULE_4__.PretrainedConfig), -/* harmony export */ PretrainedMixin: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PretrainedMixin), -/* harmony export */ Processor: () => (/* reexport safe */ _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_16__.Processor), -/* harmony export */ PvtForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PvtForImageClassification), -/* harmony export */ PvtImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.PvtImageProcessor), -/* harmony export */ PvtModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PvtModel), -/* harmony export */ PvtPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PvtPreTrainedModel), -/* harmony export */ PyAnnoteFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.PyAnnoteFeatureExtractor), -/* harmony export */ PyAnnoteForAudioFrameClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PyAnnoteForAudioFrameClassification), -/* harmony export */ PyAnnoteModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PyAnnoteModel), -/* harmony export */ PyAnnotePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.PyAnnotePreTrainedModel), -/* harmony export */ PyAnnoteProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.PyAnnoteProcessor), -/* harmony export */ QuestionAnsweringModelOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.QuestionAnsweringModelOutput), -/* harmony export */ QuestionAnsweringPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.QuestionAnsweringPipeline), -/* harmony export */ Qwen2ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2ForCausalLM), -/* harmony export */ Qwen2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2Model), -/* harmony export */ Qwen2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2PreTrainedModel), -/* harmony export */ Qwen2Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Qwen2Tokenizer), -/* harmony export */ Qwen2VLForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2VLForConditionalGeneration), -/* harmony export */ Qwen2VLImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Qwen2VLImageProcessor), -/* harmony export */ Qwen2VLPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen2VLPreTrainedModel), -/* harmony export */ Qwen2VLProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Qwen2VLProcessor), -/* harmony export */ Qwen3ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen3ForCausalLM), -/* harmony export */ Qwen3Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen3Model), -/* harmony export */ Qwen3PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Qwen3PreTrainedModel), -/* harmony export */ RFDetrForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrForObjectDetection), -/* harmony export */ RFDetrModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrModel), -/* harmony export */ RFDetrObjectDetectionOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrObjectDetectionOutput), -/* harmony export */ RFDetrPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RFDetrPreTrainedModel), -/* harmony export */ RTDetrForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrForObjectDetection), -/* harmony export */ RTDetrImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.RTDetrImageProcessor), -/* harmony export */ RTDetrModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrModel), -/* harmony export */ RTDetrObjectDetectionOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrObjectDetectionOutput), -/* harmony export */ RTDetrPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrPreTrainedModel), -/* harmony export */ RTDetrV2ForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2ForObjectDetection), -/* harmony export */ RTDetrV2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2Model), -/* harmony export */ RTDetrV2ObjectDetectionOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2ObjectDetectionOutput), -/* harmony export */ RTDetrV2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RTDetrV2PreTrainedModel), -/* harmony export */ RawAudio: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.RawAudio), -/* harmony export */ RawImage: () => (/* reexport safe */ _utils_image_js__WEBPACK_IMPORTED_MODULE_6__.RawImage), -/* harmony export */ RawVideo: () => (/* reexport safe */ _utils_video_js__WEBPACK_IMPORTED_MODULE_7__.RawVideo), -/* harmony export */ RawVideoFrame: () => (/* reexport safe */ _utils_video_js__WEBPACK_IMPORTED_MODULE_7__.RawVideoFrame), -/* harmony export */ RepetitionPenaltyLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.RepetitionPenaltyLogitsProcessor), -/* harmony export */ ResNetForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetForImageClassification), -/* harmony export */ ResNetModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetModel), -/* harmony export */ ResNetPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ResNetPreTrainedModel), -/* harmony export */ RoFormerForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForMaskedLM), -/* harmony export */ RoFormerForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForQuestionAnswering), -/* harmony export */ RoFormerForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForSequenceClassification), -/* harmony export */ RoFormerForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerForTokenClassification), -/* harmony export */ RoFormerModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerModel), -/* harmony export */ RoFormerPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RoFormerPreTrainedModel), -/* harmony export */ RoFormerTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.RoFormerTokenizer), -/* harmony export */ RobertaForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForMaskedLM), -/* harmony export */ RobertaForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForQuestionAnswering), -/* harmony export */ RobertaForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForSequenceClassification), -/* harmony export */ RobertaForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaForTokenClassification), -/* harmony export */ RobertaModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaModel), -/* harmony export */ RobertaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.RobertaPreTrainedModel), -/* harmony export */ RobertaTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.RobertaTokenizer), -/* harmony export */ SamImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SamImageProcessor), -/* harmony export */ SamImageSegmentationOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SamImageSegmentationOutput), -/* harmony export */ SamModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SamModel), -/* harmony export */ SamPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SamPreTrainedModel), -/* harmony export */ SamProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.SamProcessor), -/* harmony export */ SapiensForDepthEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensForDepthEstimation), -/* harmony export */ SapiensForNormalEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensForNormalEstimation), -/* harmony export */ SapiensForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensForSemanticSegmentation), -/* harmony export */ SapiensPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SapiensPreTrainedModel), -/* harmony export */ SeamlessM4TFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.SeamlessM4TFeatureExtractor), -/* harmony export */ SegformerFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SegformerFeatureExtractor), -/* harmony export */ SegformerForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerForImageClassification), -/* harmony export */ SegformerForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerForSemanticSegmentation), -/* harmony export */ SegformerImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SegformerImageProcessor), -/* harmony export */ SegformerModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerModel), -/* harmony export */ SegformerPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SegformerPreTrainedModel), -/* harmony export */ Seq2SeqLMOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Seq2SeqLMOutput), -/* harmony export */ SequenceClassifierOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SequenceClassifierOutput), -/* harmony export */ SiglipImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SiglipImageProcessor), -/* harmony export */ SiglipModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipModel), -/* harmony export */ SiglipPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipPreTrainedModel), -/* harmony export */ SiglipTextModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipTextModel), -/* harmony export */ SiglipTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SiglipTokenizer), -/* harmony export */ SiglipVisionModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SiglipVisionModel), -/* harmony export */ SmolLM3ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolLM3ForCausalLM), -/* harmony export */ SmolLM3Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolLM3Model), -/* harmony export */ SmolLM3PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolLM3PreTrainedModel), -/* harmony export */ SmolVLMForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SmolVLMForConditionalGeneration), -/* harmony export */ SmolVLMImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.SmolVLMImageProcessor), -/* harmony export */ SmolVLMProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.SmolVLMProcessor), -/* harmony export */ SnacDecoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacDecoderModel), -/* harmony export */ SnacEncoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacEncoderModel), -/* harmony export */ SnacFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.SnacFeatureExtractor), -/* harmony export */ SnacModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacModel), -/* harmony export */ SnacPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SnacPreTrainedModel), -/* harmony export */ SpeechT5FeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.SpeechT5FeatureExtractor), -/* harmony export */ SpeechT5ForSpeechToText: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5ForSpeechToText), -/* harmony export */ SpeechT5ForTextToSpeech: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5ForTextToSpeech), -/* harmony export */ SpeechT5HifiGan: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5HifiGan), -/* harmony export */ SpeechT5Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5Model), -/* harmony export */ SpeechT5PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SpeechT5PreTrainedModel), -/* harmony export */ SpeechT5Processor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.SpeechT5Processor), -/* harmony export */ SpeechT5Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SpeechT5Tokenizer), -/* harmony export */ SqueezeBertForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForMaskedLM), -/* harmony export */ SqueezeBertForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForQuestionAnswering), -/* harmony export */ SqueezeBertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertForSequenceClassification), -/* harmony export */ SqueezeBertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertModel), -/* harmony export */ SqueezeBertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SqueezeBertPreTrainedModel), -/* harmony export */ SqueezeBertTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.SqueezeBertTokenizer), -/* harmony export */ StableLmForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmForCausalLM), -/* harmony export */ StableLmModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmModel), -/* harmony export */ StableLmPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StableLmPreTrainedModel), -/* harmony export */ Starcoder2ForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2ForCausalLM), -/* harmony export */ Starcoder2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2Model), -/* harmony export */ Starcoder2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Starcoder2PreTrainedModel), -/* harmony export */ StoppingCriteria: () => (/* reexport safe */ _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.StoppingCriteria), -/* harmony export */ StoppingCriteriaList: () => (/* reexport safe */ _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__.StoppingCriteriaList), -/* harmony export */ StyleTextToSpeech2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StyleTextToSpeech2Model), -/* harmony export */ StyleTextToSpeech2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.StyleTextToSpeech2PreTrainedModel), -/* harmony export */ SummarizationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.SummarizationPipeline), -/* harmony export */ SuppressTokensAtBeginLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.SuppressTokensAtBeginLogitsProcessor), -/* harmony export */ Swin2SRForImageSuperResolution: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRForImageSuperResolution), -/* harmony export */ Swin2SRImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.Swin2SRImageProcessor), -/* harmony export */ Swin2SRModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRModel), -/* harmony export */ Swin2SRPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Swin2SRPreTrainedModel), -/* harmony export */ SwinForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinForImageClassification), -/* harmony export */ SwinForSemanticSegmentation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinForSemanticSegmentation), -/* harmony export */ SwinModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinModel), -/* harmony export */ SwinPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.SwinPreTrainedModel), -/* harmony export */ T5ForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.T5ForConditionalGeneration), -/* harmony export */ T5Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.T5Model), -/* harmony export */ T5PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.T5PreTrainedModel), -/* harmony export */ T5Tokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.T5Tokenizer), -/* harmony export */ TableTransformerForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerForObjectDetection), -/* harmony export */ TableTransformerModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerModel), -/* harmony export */ TableTransformerObjectDetectionOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerObjectDetectionOutput), -/* harmony export */ TableTransformerPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TableTransformerPreTrainedModel), -/* harmony export */ TemperatureLogitsWarper: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.TemperatureLogitsWarper), -/* harmony export */ Tensor: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.Tensor), -/* harmony export */ Text2TextGenerationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.Text2TextGenerationPipeline), -/* harmony export */ TextClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TextClassificationPipeline), -/* harmony export */ TextGenerationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TextGenerationPipeline), -/* harmony export */ TextStreamer: () => (/* reexport safe */ _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__.TextStreamer), -/* harmony export */ TextToAudioPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TextToAudioPipeline), -/* harmony export */ TokenClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TokenClassificationPipeline), -/* harmony export */ TokenClassifierOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TokenClassifierOutput), -/* harmony export */ TokenizerModel: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.TokenizerModel), -/* harmony export */ TopKLogitsWarper: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.TopKLogitsWarper), -/* harmony export */ TopPLogitsWarper: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.TopPLogitsWarper), -/* harmony export */ TrOCRForCausalLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TrOCRForCausalLM), -/* harmony export */ TrOCRPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.TrOCRPreTrainedModel), -/* harmony export */ TranslationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.TranslationPipeline), -/* harmony export */ UltravoxModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UltravoxModel), -/* harmony export */ UltravoxPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UltravoxPreTrainedModel), -/* harmony export */ UltravoxProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.UltravoxProcessor), -/* harmony export */ UniSpeechForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechForCTC), -/* harmony export */ UniSpeechForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechForSequenceClassification), -/* harmony export */ UniSpeechModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechModel), -/* harmony export */ UniSpeechPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechPreTrainedModel), -/* harmony export */ UniSpeechSatForAudioFrameClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForAudioFrameClassification), -/* harmony export */ UniSpeechSatForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForCTC), -/* harmony export */ UniSpeechSatForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatForSequenceClassification), -/* harmony export */ UniSpeechSatModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatModel), -/* harmony export */ UniSpeechSatPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.UniSpeechSatPreTrainedModel), -/* harmony export */ VLChatProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.VLChatProcessor), -/* harmony export */ VLMImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.VLMImageProcessor), -/* harmony export */ ViTFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ViTFeatureExtractor), -/* harmony export */ ViTForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTForImageClassification), -/* harmony export */ ViTImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.ViTImageProcessor), -/* harmony export */ ViTMAEModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMAEModel), -/* harmony export */ ViTMAEPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMAEPreTrainedModel), -/* harmony export */ ViTMSNForImageClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMSNForImageClassification), -/* harmony export */ ViTMSNModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMSNModel), -/* harmony export */ ViTMSNPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTMSNPreTrainedModel), -/* harmony export */ ViTModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTModel), -/* harmony export */ ViTPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.ViTPreTrainedModel), -/* harmony export */ VisionEncoderDecoderModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VisionEncoderDecoderModel), -/* harmony export */ VitMatteForImageMatting: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitMatteForImageMatting), -/* harmony export */ VitMatteImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.VitMatteImageProcessor), -/* harmony export */ VitMattePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitMattePreTrainedModel), -/* harmony export */ VitPoseForPoseEstimation: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitPoseForPoseEstimation), -/* harmony export */ VitPoseImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.VitPoseImageProcessor), -/* harmony export */ VitPosePreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitPosePreTrainedModel), -/* harmony export */ VitsModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsModel), -/* harmony export */ VitsModelOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsModelOutput), -/* harmony export */ VitsPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VitsPreTrainedModel), -/* harmony export */ VitsTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.VitsTokenizer), -/* harmony export */ VoxtralForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.VoxtralForConditionalGeneration), -/* harmony export */ VoxtralProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.VoxtralProcessor), -/* harmony export */ Wav2Vec2BertForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertForCTC), -/* harmony export */ Wav2Vec2BertForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertForSequenceClassification), -/* harmony export */ Wav2Vec2BertModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertModel), -/* harmony export */ Wav2Vec2BertPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2BertPreTrainedModel), -/* harmony export */ Wav2Vec2CTCTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.Wav2Vec2CTCTokenizer), -/* harmony export */ Wav2Vec2FeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.Wav2Vec2FeatureExtractor), -/* harmony export */ Wav2Vec2ForAudioFrameClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForAudioFrameClassification), -/* harmony export */ Wav2Vec2ForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForCTC), -/* harmony export */ Wav2Vec2ForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2ForSequenceClassification), -/* harmony export */ Wav2Vec2Model: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2Model), -/* harmony export */ Wav2Vec2PreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.Wav2Vec2PreTrainedModel), -/* harmony export */ Wav2Vec2Processor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Wav2Vec2Processor), -/* harmony export */ Wav2Vec2ProcessorWithLM: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.Wav2Vec2ProcessorWithLM), -/* harmony export */ WavLMForAudioFrameClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForAudioFrameClassification), -/* harmony export */ WavLMForCTC: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForCTC), -/* harmony export */ WavLMForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForSequenceClassification), -/* harmony export */ WavLMForXVector: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMForXVector), -/* harmony export */ WavLMModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMModel), -/* harmony export */ WavLMPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WavLMPreTrainedModel), -/* harmony export */ WeSpeakerFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.WeSpeakerFeatureExtractor), -/* harmony export */ WeSpeakerResNetModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WeSpeakerResNetModel), -/* harmony export */ WeSpeakerResNetPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WeSpeakerResNetPreTrainedModel), -/* harmony export */ WhisperFeatureExtractor: () => (/* reexport safe */ _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__.WhisperFeatureExtractor), -/* harmony export */ WhisperForConditionalGeneration: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperForConditionalGeneration), -/* harmony export */ WhisperModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperModel), -/* harmony export */ WhisperPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.WhisperPreTrainedModel), -/* harmony export */ WhisperProcessor: () => (/* reexport safe */ _models_processors_js__WEBPACK_IMPORTED_MODULE_17__.WhisperProcessor), -/* harmony export */ WhisperTextStreamer: () => (/* reexport safe */ _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__.WhisperTextStreamer), -/* harmony export */ WhisperTimeStampLogitsProcessor: () => (/* reexport safe */ _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__.WhisperTimeStampLogitsProcessor), -/* harmony export */ WhisperTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.WhisperTokenizer), -/* harmony export */ XLMForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForQuestionAnswering), -/* harmony export */ XLMForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForSequenceClassification), -/* harmony export */ XLMForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMForTokenClassification), -/* harmony export */ XLMModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMModel), -/* harmony export */ XLMPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMPreTrainedModel), -/* harmony export */ XLMRobertaForMaskedLM: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForMaskedLM), -/* harmony export */ XLMRobertaForQuestionAnswering: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForQuestionAnswering), -/* harmony export */ XLMRobertaForSequenceClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForSequenceClassification), -/* harmony export */ XLMRobertaForTokenClassification: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaForTokenClassification), -/* harmony export */ XLMRobertaModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaModel), -/* harmony export */ XLMRobertaPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMRobertaPreTrainedModel), -/* harmony export */ XLMRobertaTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.XLMRobertaTokenizer), -/* harmony export */ XLMTokenizer: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.XLMTokenizer), -/* harmony export */ XLMWithLMHeadModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XLMWithLMHeadModel), -/* harmony export */ XVectorOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.XVectorOutput), -/* harmony export */ YolosFeatureExtractor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.YolosFeatureExtractor), -/* harmony export */ YolosForObjectDetection: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosForObjectDetection), -/* harmony export */ YolosImageProcessor: () => (/* reexport safe */ _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__.YolosImageProcessor), -/* harmony export */ YolosModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosModel), -/* harmony export */ YolosObjectDetectionOutput: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosObjectDetectionOutput), -/* harmony export */ YolosPreTrainedModel: () => (/* reexport safe */ _models_js__WEBPACK_IMPORTED_MODULE_2__.YolosPreTrainedModel), -/* harmony export */ ZeroShotAudioClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotAudioClassificationPipeline), -/* harmony export */ ZeroShotClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotClassificationPipeline), -/* harmony export */ ZeroShotImageClassificationPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotImageClassificationPipeline), -/* harmony export */ ZeroShotObjectDetectionPipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.ZeroShotObjectDetectionPipeline), -/* harmony export */ bankers_round: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.bankers_round), -/* harmony export */ cat: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.cat), -/* harmony export */ cos_sim: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.cos_sim), -/* harmony export */ dot: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.dot), -/* harmony export */ dynamic_time_warping: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.dynamic_time_warping), -/* harmony export */ env: () => (/* reexport safe */ _env_js__WEBPACK_IMPORTED_MODULE_0__.env), -/* harmony export */ full: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.full), -/* harmony export */ full_like: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.full_like), -/* harmony export */ getCacheShapes: () => (/* reexport safe */ _configs_js__WEBPACK_IMPORTED_MODULE_4__.getCacheShapes), -/* harmony export */ hamming: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.hamming), -/* harmony export */ hanning: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.hanning), -/* harmony export */ interpolate: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate), -/* harmony export */ interpolate_4d: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.interpolate_4d), -/* harmony export */ interpolate_data: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.interpolate_data), -/* harmony export */ is_chinese_char: () => (/* reexport safe */ _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__.is_chinese_char), -/* harmony export */ layer_norm: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.layer_norm), -/* harmony export */ load_image: () => (/* reexport safe */ _utils_image_js__WEBPACK_IMPORTED_MODULE_6__.load_image), -/* harmony export */ load_video: () => (/* reexport safe */ _utils_video_js__WEBPACK_IMPORTED_MODULE_7__.load_video), -/* harmony export */ log_softmax: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.log_softmax), -/* harmony export */ magnitude: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.magnitude), -/* harmony export */ matmul: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.matmul), -/* harmony export */ max: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.max), -/* harmony export */ mean: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean), -/* harmony export */ mean_pooling: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.mean_pooling), -/* harmony export */ medianFilter: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.medianFilter), -/* harmony export */ mel_filter_bank: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.mel_filter_bank), -/* harmony export */ min: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.min), -/* harmony export */ ones: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.ones), -/* harmony export */ ones_like: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.ones_like), -/* harmony export */ permute: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.permute), -/* harmony export */ permute_data: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.permute_data), -/* harmony export */ pipeline: () => (/* reexport safe */ _pipelines_js__WEBPACK_IMPORTED_MODULE_1__.pipeline), -/* harmony export */ quantize_embeddings: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.quantize_embeddings), -/* harmony export */ rand: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.rand), -/* harmony export */ read_audio: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.read_audio), -/* harmony export */ rfft: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.rfft), -/* harmony export */ round: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.round), -/* harmony export */ slice: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.slice), -/* harmony export */ softmax: () => (/* reexport safe */ _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__.softmax), -/* harmony export */ spectrogram: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.spectrogram), -/* harmony export */ stack: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.stack), -/* harmony export */ std_mean: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.std_mean), -/* harmony export */ topk: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.topk), -/* harmony export */ window_function: () => (/* reexport safe */ _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__.window_function), -/* harmony export */ zeros: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.zeros), -/* harmony export */ zeros_like: () => (/* reexport safe */ _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__.zeros_like) -/* harmony export */ }); -/* harmony import */ var _env_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env.js */ "./src/env.js"); -/* harmony import */ var _pipelines_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pipelines.js */ "./src/pipelines.js"); -/* harmony import */ var _models_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./models.js */ "./src/models.js"); -/* harmony import */ var _tokenizers_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tokenizers.js */ "./src/tokenizers.js"); -/* harmony import */ var _configs_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./configs.js */ "./src/configs.js"); -/* harmony import */ var _utils_audio_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/audio.js */ "./src/utils/audio.js"); -/* harmony import */ var _utils_image_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/image.js */ "./src/utils/image.js"); -/* harmony import */ var _utils_video_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/video.js */ "./src/utils/video.js"); -/* harmony import */ var _utils_tensor_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/tensor.js */ "./src/utils/tensor.js"); -/* harmony import */ var _utils_maths_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/maths.js */ "./src/utils/maths.js"); -/* harmony import */ var _base_feature_extraction_utils_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./base/feature_extraction_utils.js */ "./src/base/feature_extraction_utils.js"); -/* harmony import */ var _models_feature_extractors_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./models/feature_extractors.js */ "./src/models/feature_extractors.js"); -/* harmony import */ var _models_auto_feature_extraction_auto_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./models/auto/feature_extraction_auto.js */ "./src/models/auto/feature_extraction_auto.js"); -/* harmony import */ var _base_image_processors_utils_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./base/image_processors_utils.js */ "./src/base/image_processors_utils.js"); -/* harmony import */ var _models_image_processors_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./models/image_processors.js */ "./src/models/image_processors.js"); -/* harmony import */ var _models_auto_image_processing_auto_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./models/auto/image_processing_auto.js */ "./src/models/auto/image_processing_auto.js"); -/* harmony import */ var _base_processing_utils_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./base/processing_utils.js */ "./src/base/processing_utils.js"); -/* harmony import */ var _models_processors_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./models/processors.js */ "./src/models/processors.js"); -/* harmony import */ var _models_auto_processing_auto_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./models/auto/processing_auto.js */ "./src/models/auto/processing_auto.js"); -/* harmony import */ var _generation_streamers_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./generation/streamers.js */ "./src/generation/streamers.js"); -/* harmony import */ var _generation_stopping_criteria_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./generation/stopping_criteria.js */ "./src/generation/stopping_criteria.js"); -/* harmony import */ var _generation_logits_process_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./generation/logits_process.js */ "./src/generation/logits_process.js"); -/** - * @file Entry point for the Transformers.js library. Only the exports from this file - * are available to the end user, and are grouped as follows: - * - * 1. [Pipelines](./pipelines) - * 2. [Environment variables](./env) - * 3. [Models](./models) - * 4. [Tokenizers](./tokenizers) - * 5. [Processors](./processors) - * - * @module transformers - */ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +// src/utils/video.js +var RawVideoFrame = class { + /** + * Create a video frame. + * @param {RawImage} image The decoded image for this frame. + * @param {number} timestamp The frame timestamp, in seconds. + */ + constructor(image, timestamp) { + this.image = image; + this.timestamp = timestamp; + } +}; +var RawVideo = class { + /** + * Create a video from decoded frames. + * @param {RawVideoFrame[]|RawImage[]} frames Frames with timestamps, or images to space uniformly across `duration`. + * @param {number} duration Duration in seconds. + */ + constructor(frames, duration) { + if (frames.length > 0 && frames[0] instanceof RawImage) { + frames = frames.map((image, i) => new RawVideoFrame(image, (i + 1) / (frames.length + 1) * duration)); + } + this.frames = /** @type {RawVideoFrame[]} */ + frames; + this.duration = duration; + } + /** + * Width of the video frames, in pixels. + * @returns {number} + */ + get width() { + return this.frames[0].image.width; + } + /** + * Height of the video frames, in pixels. + * @returns {number} + */ + get height() { + return this.frames[0].image.height; + } + /** + * Effective sampled frame rate. + * @returns {number} + */ + get fps() { + return this.frames.length / this.duration; + } +}; +async function load_video(src, { num_frames = null, fps = null } = {}) { + if (!apis.IS_BROWSER_ENV) { + throw new Error("`load_video` is currently only supported in browser environments."); + } + if (num_frames == null && fps == null) { + throw new Error("Either num_frames or fps must be provided."); + } + const frames = []; + const video = document.createElement("video"); + video.crossOrigin = "anonymous"; + video.muted = true; + if (typeof src === "string") { + video.src = src; + } else if (src instanceof Blob) { + video.src = URL.createObjectURL(src); + } else if (src instanceof HTMLVideoElement) { + video.src = src.src; + } else { + throw new Error("Invalid URL or video element provided."); + } + await new Promise((resolve) => video.onloadedmetadata = resolve); + if (video.seekable.start(0) === video.seekable.end(0)) { + const response = await env.fetch(video.src); + const blob = await response.blob(); + video.src = URL.createObjectURL(blob); + await new Promise((resolve) => video.onloadedmetadata = resolve); + } + const duration = video.duration; + let count2, step; + if (num_frames != null) { + count2 = num_frames; + step = num_frames === 1 ? 0 : duration / (num_frames - 1); + } else { + step = 1 / fps; + count2 = Math.floor(duration / step); + } + let sampleTimes = []; + for (let i = 0; i < count2; ++i) { + sampleTimes.push(num_frames === 1 ? duration / 2 : i * step); + } + const canvas = document.createElement("canvas"); + canvas.width = video.videoWidth; + canvas.height = video.videoHeight; + const ctx = canvas.getContext("2d", { willReadFrequently: true }); + for (const t of sampleTimes) { + video.currentTime = t; + await new Promise((resolve) => { + video.onseeked = resolve; + }); + ctx.drawImage(video, 0, 0, canvas.width, canvas.height); + const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + const frameData = new RawImage(imageData.data, canvas.width, canvas.height, 4); + const frame = new RawVideoFrame(frameData, t); + frames.push(frame); + } + video.remove(); + return new RawVideo(frames, duration); +} -// Expose common types used across the library for developers to access -/** - * @typedef {import('./utils/hub.js').PretrainedModelOptions} PretrainedModelOptions - * @typedef {import('./base/processing_utils.js').PretrainedProcessorOptions} PretrainedProcessorOptions - * @typedef {import('./utils/dtypes.js').DataType} DataType - * @typedef {import('./utils/devices.js').DeviceType} DeviceType - */ +// src/utils/model_registry/is_cached.js +async function check_files_cache(modelId, files, options = {}) { + const cache2 = await getCache(options?.cache_dir); + if (!cache2) { + const fileStatuses2 = files.map((filename) => ({ file: filename, cached: false })); + return { allCached: false, files: fileStatuses2 }; + } + const fileStatuses = await Promise.all( + files.map(async (filename) => { + const { localPath, proposedCacheKey } = buildResourcePaths(modelId, filename, options, cache2); + const cached = await checkCachedResource(cache2, localPath, proposedCacheKey); + return { file: filename, cached: !!cached }; + }) + ); + return { allCached: fileStatuses.every((f) => f.cached), files: fileStatuses }; +} +async function is_file_cached(modelId, filename, options = {}) { + const cache2 = await getCache(options?.cache_dir); + if (!cache2) return false; + const { localPath, proposedCacheKey } = buildResourcePaths(modelId, filename, options, cache2); + return !!await checkCachedResource(cache2, localPath, proposedCacheKey); +} +async function is_cached(modelId, options = {}) { + if (!modelId) { + throw new Error("modelId is required"); + } + if (!await is_file_cached(modelId, "config.json", options)) { + return false; + } + const files = await get_files(modelId, options); + const result = await check_files_cache(modelId, files, options); + return result.allCached; +} +async function is_cached_files(modelId, options = {}) { + if (!modelId) { + throw new Error("modelId is required"); + } + const files = await get_files(modelId, options); + return await check_files_cache(modelId, files, options); +} +async function is_pipeline_cached(task, modelId, options = {}) { + if (!task) { + throw new Error("task is required"); + } + if (!modelId) { + throw new Error("modelId is required"); + } + if (!await is_file_cached(modelId, "config.json", options)) { + return false; + } + const files = await get_pipeline_files(task, modelId, options); + const result = await check_files_cache(modelId, files, options); + return result.allCached; +} +async function is_pipeline_cached_files(task, modelId, options = {}) { + if (!task) { + throw new Error("task is required"); + } + if (!modelId) { + throw new Error("modelId is required"); + } + const files = await get_pipeline_files(task, modelId, options); + return await check_files_cache(modelId, files, options); +} -})(); +// src/utils/model_registry/clear_cache.js +async function clear_files_from_cache(modelId, files, options = {}) { + const cache2 = await getCache(options?.cache_dir); + if (!cache2) { + return { + filesDeleted: 0, + filesCached: 0, + files: files.map((filename) => ({ file: filename, deleted: false, wasCached: false })) + }; + } + if (!cache2.delete) { + throw new Error("Cache does not support delete operation"); + } + const results = await Promise.all( + files.map(async (filename) => { + const { localPath, proposedCacheKey } = buildResourcePaths(modelId, filename, options, cache2); + const cached = await checkCachedResource(cache2, localPath, proposedCacheKey); + const wasCached = !!cached; + let deleted = false; + if (wasCached) { + const deletedWithProposed = await cache2.delete(proposedCacheKey); + const deletedWithLocal = !deletedWithProposed && proposedCacheKey !== localPath ? await cache2.delete(localPath) : false; + deleted = deletedWithProposed || deletedWithLocal; + } + return { file: filename, deleted, wasCached }; + }) + ); + return { + filesDeleted: results.filter((r) => r.deleted).length, + filesCached: results.filter((r) => r.wasCached).length, + files: results + }; +} +async function clear_cache(modelId, options = {}) { + if (!modelId) { + throw new Error("modelId is required"); + } + const files = await get_files(modelId, options); + return await clear_files_from_cache(modelId, files, options); +} +async function clear_pipeline_cache(task, modelId, options = {}) { + if (!task) { + throw new Error("task is required"); + } + if (!modelId) { + throw new Error("modelId is required"); + } + const files = await get_pipeline_files(task, modelId, options); + return await clear_files_from_cache(modelId, files, options); +} + +// src/utils/model_registry/get_available_dtypes.js +var CONCRETE_DTYPES = Object.keys(DEFAULT_DTYPE_SUFFIX_MAPPING); +async function get_available_dtypes(modelId, { config = null, model_file_name = null, revision = "main", cache_dir = null, local_files_only = false } = {}) { + config = await get_config(modelId, { config, cache_dir, local_files_only, revision }); + const subfolder = "onnx"; + const modelType = resolve_model_type(config); + const { sessions } = getSessionsConfig(modelType, config, { model_file_name }); + const baseNames = Object.values(sessions); + const metadataOptions = { revision, cache_dir, local_files_only }; + const probeResults = await Promise.all( + CONCRETE_DTYPES.map(async (dtype) => { + const suffix = DEFAULT_DTYPE_SUFFIX_MAPPING[dtype] ?? ""; + const allExist = await Promise.all( + baseNames.map(async (baseName) => { + const filename = `${subfolder}/${baseName}${suffix}.onnx`; + const metadata = await get_file_metadata(modelId, filename, metadataOptions); + return metadata.exists; + }) + ); + return { dtype, available: allExist.every(Boolean) }; + }) + ); + return probeResults.filter((r) => r.available).map((r) => r.dtype); +} -var __webpack_exports__ASTFeatureExtractor = __webpack_exports__.ASTFeatureExtractor; -var __webpack_exports__ASTForAudioClassification = __webpack_exports__.ASTForAudioClassification; -var __webpack_exports__ASTModel = __webpack_exports__.ASTModel; -var __webpack_exports__ASTPreTrainedModel = __webpack_exports__.ASTPreTrainedModel; -var __webpack_exports__AlbertForMaskedLM = __webpack_exports__.AlbertForMaskedLM; -var __webpack_exports__AlbertForQuestionAnswering = __webpack_exports__.AlbertForQuestionAnswering; -var __webpack_exports__AlbertForSequenceClassification = __webpack_exports__.AlbertForSequenceClassification; -var __webpack_exports__AlbertModel = __webpack_exports__.AlbertModel; -var __webpack_exports__AlbertPreTrainedModel = __webpack_exports__.AlbertPreTrainedModel; -var __webpack_exports__AlbertTokenizer = __webpack_exports__.AlbertTokenizer; -var __webpack_exports__ArceeForCausalLM = __webpack_exports__.ArceeForCausalLM; -var __webpack_exports__ArceeModel = __webpack_exports__.ArceeModel; -var __webpack_exports__ArceePreTrainedModel = __webpack_exports__.ArceePreTrainedModel; -var __webpack_exports__AudioClassificationPipeline = __webpack_exports__.AudioClassificationPipeline; -var __webpack_exports__AutoConfig = __webpack_exports__.AutoConfig; -var __webpack_exports__AutoFeatureExtractor = __webpack_exports__.AutoFeatureExtractor; -var __webpack_exports__AutoImageProcessor = __webpack_exports__.AutoImageProcessor; -var __webpack_exports__AutoModel = __webpack_exports__.AutoModel; -var __webpack_exports__AutoModelForAudioClassification = __webpack_exports__.AutoModelForAudioClassification; -var __webpack_exports__AutoModelForAudioFrameClassification = __webpack_exports__.AutoModelForAudioFrameClassification; -var __webpack_exports__AutoModelForAudioTextToText = __webpack_exports__.AutoModelForAudioTextToText; -var __webpack_exports__AutoModelForCTC = __webpack_exports__.AutoModelForCTC; -var __webpack_exports__AutoModelForCausalLM = __webpack_exports__.AutoModelForCausalLM; -var __webpack_exports__AutoModelForDepthEstimation = __webpack_exports__.AutoModelForDepthEstimation; -var __webpack_exports__AutoModelForDocumentQuestionAnswering = __webpack_exports__.AutoModelForDocumentQuestionAnswering; -var __webpack_exports__AutoModelForImageClassification = __webpack_exports__.AutoModelForImageClassification; -var __webpack_exports__AutoModelForImageFeatureExtraction = __webpack_exports__.AutoModelForImageFeatureExtraction; -var __webpack_exports__AutoModelForImageMatting = __webpack_exports__.AutoModelForImageMatting; -var __webpack_exports__AutoModelForImageSegmentation = __webpack_exports__.AutoModelForImageSegmentation; -var __webpack_exports__AutoModelForImageTextToText = __webpack_exports__.AutoModelForImageTextToText; -var __webpack_exports__AutoModelForImageToImage = __webpack_exports__.AutoModelForImageToImage; -var __webpack_exports__AutoModelForMaskGeneration = __webpack_exports__.AutoModelForMaskGeneration; -var __webpack_exports__AutoModelForMaskedLM = __webpack_exports__.AutoModelForMaskedLM; -var __webpack_exports__AutoModelForNormalEstimation = __webpack_exports__.AutoModelForNormalEstimation; -var __webpack_exports__AutoModelForObjectDetection = __webpack_exports__.AutoModelForObjectDetection; -var __webpack_exports__AutoModelForPoseEstimation = __webpack_exports__.AutoModelForPoseEstimation; -var __webpack_exports__AutoModelForQuestionAnswering = __webpack_exports__.AutoModelForQuestionAnswering; -var __webpack_exports__AutoModelForSemanticSegmentation = __webpack_exports__.AutoModelForSemanticSegmentation; -var __webpack_exports__AutoModelForSeq2SeqLM = __webpack_exports__.AutoModelForSeq2SeqLM; -var __webpack_exports__AutoModelForSequenceClassification = __webpack_exports__.AutoModelForSequenceClassification; -var __webpack_exports__AutoModelForSpeechSeq2Seq = __webpack_exports__.AutoModelForSpeechSeq2Seq; -var __webpack_exports__AutoModelForTextToSpectrogram = __webpack_exports__.AutoModelForTextToSpectrogram; -var __webpack_exports__AutoModelForTextToWaveform = __webpack_exports__.AutoModelForTextToWaveform; -var __webpack_exports__AutoModelForTokenClassification = __webpack_exports__.AutoModelForTokenClassification; -var __webpack_exports__AutoModelForUniversalSegmentation = __webpack_exports__.AutoModelForUniversalSegmentation; -var __webpack_exports__AutoModelForVision2Seq = __webpack_exports__.AutoModelForVision2Seq; -var __webpack_exports__AutoModelForXVector = __webpack_exports__.AutoModelForXVector; -var __webpack_exports__AutoModelForZeroShotObjectDetection = __webpack_exports__.AutoModelForZeroShotObjectDetection; -var __webpack_exports__AutoProcessor = __webpack_exports__.AutoProcessor; -var __webpack_exports__AutoTokenizer = __webpack_exports__.AutoTokenizer; -var __webpack_exports__AutomaticSpeechRecognitionPipeline = __webpack_exports__.AutomaticSpeechRecognitionPipeline; -var __webpack_exports__BackgroundRemovalPipeline = __webpack_exports__.BackgroundRemovalPipeline; -var __webpack_exports__BartForConditionalGeneration = __webpack_exports__.BartForConditionalGeneration; -var __webpack_exports__BartForSequenceClassification = __webpack_exports__.BartForSequenceClassification; -var __webpack_exports__BartModel = __webpack_exports__.BartModel; -var __webpack_exports__BartPretrainedModel = __webpack_exports__.BartPretrainedModel; -var __webpack_exports__BartTokenizer = __webpack_exports__.BartTokenizer; -var __webpack_exports__BaseModelOutput = __webpack_exports__.BaseModelOutput; -var __webpack_exports__BaseStreamer = __webpack_exports__.BaseStreamer; -var __webpack_exports__BeitFeatureExtractor = __webpack_exports__.BeitFeatureExtractor; -var __webpack_exports__BeitForImageClassification = __webpack_exports__.BeitForImageClassification; -var __webpack_exports__BeitModel = __webpack_exports__.BeitModel; -var __webpack_exports__BeitPreTrainedModel = __webpack_exports__.BeitPreTrainedModel; -var __webpack_exports__BertForMaskedLM = __webpack_exports__.BertForMaskedLM; -var __webpack_exports__BertForQuestionAnswering = __webpack_exports__.BertForQuestionAnswering; -var __webpack_exports__BertForSequenceClassification = __webpack_exports__.BertForSequenceClassification; -var __webpack_exports__BertForTokenClassification = __webpack_exports__.BertForTokenClassification; -var __webpack_exports__BertModel = __webpack_exports__.BertModel; -var __webpack_exports__BertPreTrainedModel = __webpack_exports__.BertPreTrainedModel; -var __webpack_exports__BertTokenizer = __webpack_exports__.BertTokenizer; -var __webpack_exports__BitImageProcessor = __webpack_exports__.BitImageProcessor; -var __webpack_exports__BlenderbotForConditionalGeneration = __webpack_exports__.BlenderbotForConditionalGeneration; -var __webpack_exports__BlenderbotModel = __webpack_exports__.BlenderbotModel; -var __webpack_exports__BlenderbotPreTrainedModel = __webpack_exports__.BlenderbotPreTrainedModel; -var __webpack_exports__BlenderbotSmallForConditionalGeneration = __webpack_exports__.BlenderbotSmallForConditionalGeneration; -var __webpack_exports__BlenderbotSmallModel = __webpack_exports__.BlenderbotSmallModel; -var __webpack_exports__BlenderbotSmallPreTrainedModel = __webpack_exports__.BlenderbotSmallPreTrainedModel; -var __webpack_exports__BlenderbotSmallTokenizer = __webpack_exports__.BlenderbotSmallTokenizer; -var __webpack_exports__BlenderbotTokenizer = __webpack_exports__.BlenderbotTokenizer; -var __webpack_exports__BloomForCausalLM = __webpack_exports__.BloomForCausalLM; -var __webpack_exports__BloomModel = __webpack_exports__.BloomModel; -var __webpack_exports__BloomPreTrainedModel = __webpack_exports__.BloomPreTrainedModel; -var __webpack_exports__BloomTokenizer = __webpack_exports__.BloomTokenizer; -var __webpack_exports__CLIPFeatureExtractor = __webpack_exports__.CLIPFeatureExtractor; -var __webpack_exports__CLIPImageProcessor = __webpack_exports__.CLIPImageProcessor; -var __webpack_exports__CLIPModel = __webpack_exports__.CLIPModel; -var __webpack_exports__CLIPPreTrainedModel = __webpack_exports__.CLIPPreTrainedModel; -var __webpack_exports__CLIPSegForImageSegmentation = __webpack_exports__.CLIPSegForImageSegmentation; -var __webpack_exports__CLIPSegModel = __webpack_exports__.CLIPSegModel; -var __webpack_exports__CLIPSegPreTrainedModel = __webpack_exports__.CLIPSegPreTrainedModel; -var __webpack_exports__CLIPTextModel = __webpack_exports__.CLIPTextModel; -var __webpack_exports__CLIPTextModelWithProjection = __webpack_exports__.CLIPTextModelWithProjection; -var __webpack_exports__CLIPTokenizer = __webpack_exports__.CLIPTokenizer; -var __webpack_exports__CLIPVisionModel = __webpack_exports__.CLIPVisionModel; -var __webpack_exports__CLIPVisionModelWithProjection = __webpack_exports__.CLIPVisionModelWithProjection; -var __webpack_exports__CamembertForMaskedLM = __webpack_exports__.CamembertForMaskedLM; -var __webpack_exports__CamembertForQuestionAnswering = __webpack_exports__.CamembertForQuestionAnswering; -var __webpack_exports__CamembertForSequenceClassification = __webpack_exports__.CamembertForSequenceClassification; -var __webpack_exports__CamembertForTokenClassification = __webpack_exports__.CamembertForTokenClassification; -var __webpack_exports__CamembertModel = __webpack_exports__.CamembertModel; -var __webpack_exports__CamembertPreTrainedModel = __webpack_exports__.CamembertPreTrainedModel; -var __webpack_exports__CamembertTokenizer = __webpack_exports__.CamembertTokenizer; -var __webpack_exports__CausalLMOutput = __webpack_exports__.CausalLMOutput; -var __webpack_exports__CausalLMOutputWithPast = __webpack_exports__.CausalLMOutputWithPast; -var __webpack_exports__ChineseCLIPFeatureExtractor = __webpack_exports__.ChineseCLIPFeatureExtractor; -var __webpack_exports__ChineseCLIPModel = __webpack_exports__.ChineseCLIPModel; -var __webpack_exports__ChineseCLIPPreTrainedModel = __webpack_exports__.ChineseCLIPPreTrainedModel; -var __webpack_exports__ClapAudioModelWithProjection = __webpack_exports__.ClapAudioModelWithProjection; -var __webpack_exports__ClapFeatureExtractor = __webpack_exports__.ClapFeatureExtractor; -var __webpack_exports__ClapModel = __webpack_exports__.ClapModel; -var __webpack_exports__ClapPreTrainedModel = __webpack_exports__.ClapPreTrainedModel; -var __webpack_exports__ClapTextModelWithProjection = __webpack_exports__.ClapTextModelWithProjection; -var __webpack_exports__ClassifierFreeGuidanceLogitsProcessor = __webpack_exports__.ClassifierFreeGuidanceLogitsProcessor; -var __webpack_exports__CodeGenForCausalLM = __webpack_exports__.CodeGenForCausalLM; -var __webpack_exports__CodeGenModel = __webpack_exports__.CodeGenModel; -var __webpack_exports__CodeGenPreTrainedModel = __webpack_exports__.CodeGenPreTrainedModel; -var __webpack_exports__CodeGenTokenizer = __webpack_exports__.CodeGenTokenizer; -var __webpack_exports__CodeLlamaTokenizer = __webpack_exports__.CodeLlamaTokenizer; -var __webpack_exports__CohereForCausalLM = __webpack_exports__.CohereForCausalLM; -var __webpack_exports__CohereModel = __webpack_exports__.CohereModel; -var __webpack_exports__CoherePreTrainedModel = __webpack_exports__.CoherePreTrainedModel; -var __webpack_exports__CohereTokenizer = __webpack_exports__.CohereTokenizer; -var __webpack_exports__ConvBertForMaskedLM = __webpack_exports__.ConvBertForMaskedLM; -var __webpack_exports__ConvBertForQuestionAnswering = __webpack_exports__.ConvBertForQuestionAnswering; -var __webpack_exports__ConvBertForSequenceClassification = __webpack_exports__.ConvBertForSequenceClassification; -var __webpack_exports__ConvBertForTokenClassification = __webpack_exports__.ConvBertForTokenClassification; -var __webpack_exports__ConvBertModel = __webpack_exports__.ConvBertModel; -var __webpack_exports__ConvBertPreTrainedModel = __webpack_exports__.ConvBertPreTrainedModel; -var __webpack_exports__ConvBertTokenizer = __webpack_exports__.ConvBertTokenizer; -var __webpack_exports__ConvNextFeatureExtractor = __webpack_exports__.ConvNextFeatureExtractor; -var __webpack_exports__ConvNextForImageClassification = __webpack_exports__.ConvNextForImageClassification; -var __webpack_exports__ConvNextImageProcessor = __webpack_exports__.ConvNextImageProcessor; -var __webpack_exports__ConvNextModel = __webpack_exports__.ConvNextModel; -var __webpack_exports__ConvNextPreTrainedModel = __webpack_exports__.ConvNextPreTrainedModel; -var __webpack_exports__ConvNextV2ForImageClassification = __webpack_exports__.ConvNextV2ForImageClassification; -var __webpack_exports__ConvNextV2Model = __webpack_exports__.ConvNextV2Model; -var __webpack_exports__ConvNextV2PreTrainedModel = __webpack_exports__.ConvNextV2PreTrainedModel; -var __webpack_exports__DFineForObjectDetection = __webpack_exports__.DFineForObjectDetection; -var __webpack_exports__DFineModel = __webpack_exports__.DFineModel; -var __webpack_exports__DFinePreTrainedModel = __webpack_exports__.DFinePreTrainedModel; -var __webpack_exports__DINOv3ConvNextModel = __webpack_exports__.DINOv3ConvNextModel; -var __webpack_exports__DINOv3ConvNextPreTrainedModel = __webpack_exports__.DINOv3ConvNextPreTrainedModel; -var __webpack_exports__DINOv3ViTImageProcessor = __webpack_exports__.DINOv3ViTImageProcessor; -var __webpack_exports__DINOv3ViTModel = __webpack_exports__.DINOv3ViTModel; -var __webpack_exports__DINOv3ViTPreTrainedModel = __webpack_exports__.DINOv3ViTPreTrainedModel; -var __webpack_exports__DPTFeatureExtractor = __webpack_exports__.DPTFeatureExtractor; -var __webpack_exports__DPTForDepthEstimation = __webpack_exports__.DPTForDepthEstimation; -var __webpack_exports__DPTImageProcessor = __webpack_exports__.DPTImageProcessor; -var __webpack_exports__DPTModel = __webpack_exports__.DPTModel; -var __webpack_exports__DPTPreTrainedModel = __webpack_exports__.DPTPreTrainedModel; -var __webpack_exports__DacDecoderModel = __webpack_exports__.DacDecoderModel; -var __webpack_exports__DacDecoderOutput = __webpack_exports__.DacDecoderOutput; -var __webpack_exports__DacEncoderModel = __webpack_exports__.DacEncoderModel; -var __webpack_exports__DacEncoderOutput = __webpack_exports__.DacEncoderOutput; -var __webpack_exports__DacFeatureExtractor = __webpack_exports__.DacFeatureExtractor; -var __webpack_exports__DacModel = __webpack_exports__.DacModel; -var __webpack_exports__DacPreTrainedModel = __webpack_exports__.DacPreTrainedModel; -var __webpack_exports__DataTypeMap = __webpack_exports__.DataTypeMap; -var __webpack_exports__DebertaForMaskedLM = __webpack_exports__.DebertaForMaskedLM; -var __webpack_exports__DebertaForQuestionAnswering = __webpack_exports__.DebertaForQuestionAnswering; -var __webpack_exports__DebertaForSequenceClassification = __webpack_exports__.DebertaForSequenceClassification; -var __webpack_exports__DebertaForTokenClassification = __webpack_exports__.DebertaForTokenClassification; -var __webpack_exports__DebertaModel = __webpack_exports__.DebertaModel; -var __webpack_exports__DebertaPreTrainedModel = __webpack_exports__.DebertaPreTrainedModel; -var __webpack_exports__DebertaTokenizer = __webpack_exports__.DebertaTokenizer; -var __webpack_exports__DebertaV2ForMaskedLM = __webpack_exports__.DebertaV2ForMaskedLM; -var __webpack_exports__DebertaV2ForQuestionAnswering = __webpack_exports__.DebertaV2ForQuestionAnswering; -var __webpack_exports__DebertaV2ForSequenceClassification = __webpack_exports__.DebertaV2ForSequenceClassification; -var __webpack_exports__DebertaV2ForTokenClassification = __webpack_exports__.DebertaV2ForTokenClassification; -var __webpack_exports__DebertaV2Model = __webpack_exports__.DebertaV2Model; -var __webpack_exports__DebertaV2PreTrainedModel = __webpack_exports__.DebertaV2PreTrainedModel; -var __webpack_exports__DebertaV2Tokenizer = __webpack_exports__.DebertaV2Tokenizer; -var __webpack_exports__DecisionTransformerModel = __webpack_exports__.DecisionTransformerModel; -var __webpack_exports__DecisionTransformerPreTrainedModel = __webpack_exports__.DecisionTransformerPreTrainedModel; -var __webpack_exports__DeiTFeatureExtractor = __webpack_exports__.DeiTFeatureExtractor; -var __webpack_exports__DeiTForImageClassification = __webpack_exports__.DeiTForImageClassification; -var __webpack_exports__DeiTImageProcessor = __webpack_exports__.DeiTImageProcessor; -var __webpack_exports__DeiTModel = __webpack_exports__.DeiTModel; -var __webpack_exports__DeiTPreTrainedModel = __webpack_exports__.DeiTPreTrainedModel; -var __webpack_exports__DepthAnythingForDepthEstimation = __webpack_exports__.DepthAnythingForDepthEstimation; -var __webpack_exports__DepthAnythingPreTrainedModel = __webpack_exports__.DepthAnythingPreTrainedModel; -var __webpack_exports__DepthEstimationPipeline = __webpack_exports__.DepthEstimationPipeline; -var __webpack_exports__DepthProForDepthEstimation = __webpack_exports__.DepthProForDepthEstimation; -var __webpack_exports__DepthProPreTrainedModel = __webpack_exports__.DepthProPreTrainedModel; -var __webpack_exports__DetrFeatureExtractor = __webpack_exports__.DetrFeatureExtractor; -var __webpack_exports__DetrForObjectDetection = __webpack_exports__.DetrForObjectDetection; -var __webpack_exports__DetrForSegmentation = __webpack_exports__.DetrForSegmentation; -var __webpack_exports__DetrImageProcessor = __webpack_exports__.DetrImageProcessor; -var __webpack_exports__DetrModel = __webpack_exports__.DetrModel; -var __webpack_exports__DetrObjectDetectionOutput = __webpack_exports__.DetrObjectDetectionOutput; -var __webpack_exports__DetrPreTrainedModel = __webpack_exports__.DetrPreTrainedModel; -var __webpack_exports__DetrSegmentationOutput = __webpack_exports__.DetrSegmentationOutput; -var __webpack_exports__Dinov2ForImageClassification = __webpack_exports__.Dinov2ForImageClassification; -var __webpack_exports__Dinov2Model = __webpack_exports__.Dinov2Model; -var __webpack_exports__Dinov2PreTrainedModel = __webpack_exports__.Dinov2PreTrainedModel; -var __webpack_exports__Dinov2WithRegistersForImageClassification = __webpack_exports__.Dinov2WithRegistersForImageClassification; -var __webpack_exports__Dinov2WithRegistersModel = __webpack_exports__.Dinov2WithRegistersModel; -var __webpack_exports__Dinov2WithRegistersPreTrainedModel = __webpack_exports__.Dinov2WithRegistersPreTrainedModel; -var __webpack_exports__DistilBertForMaskedLM = __webpack_exports__.DistilBertForMaskedLM; -var __webpack_exports__DistilBertForQuestionAnswering = __webpack_exports__.DistilBertForQuestionAnswering; -var __webpack_exports__DistilBertForSequenceClassification = __webpack_exports__.DistilBertForSequenceClassification; -var __webpack_exports__DistilBertForTokenClassification = __webpack_exports__.DistilBertForTokenClassification; -var __webpack_exports__DistilBertModel = __webpack_exports__.DistilBertModel; -var __webpack_exports__DistilBertPreTrainedModel = __webpack_exports__.DistilBertPreTrainedModel; -var __webpack_exports__DistilBertTokenizer = __webpack_exports__.DistilBertTokenizer; -var __webpack_exports__DocumentQuestionAnsweringPipeline = __webpack_exports__.DocumentQuestionAnsweringPipeline; -var __webpack_exports__DonutFeatureExtractor = __webpack_exports__.DonutFeatureExtractor; -var __webpack_exports__DonutImageProcessor = __webpack_exports__.DonutImageProcessor; -var __webpack_exports__DonutSwinModel = __webpack_exports__.DonutSwinModel; -var __webpack_exports__DonutSwinPreTrainedModel = __webpack_exports__.DonutSwinPreTrainedModel; -var __webpack_exports__EfficientNetForImageClassification = __webpack_exports__.EfficientNetForImageClassification; -var __webpack_exports__EfficientNetImageProcessor = __webpack_exports__.EfficientNetImageProcessor; -var __webpack_exports__EfficientNetModel = __webpack_exports__.EfficientNetModel; -var __webpack_exports__EfficientNetPreTrainedModel = __webpack_exports__.EfficientNetPreTrainedModel; -var __webpack_exports__ElectraForMaskedLM = __webpack_exports__.ElectraForMaskedLM; -var __webpack_exports__ElectraForQuestionAnswering = __webpack_exports__.ElectraForQuestionAnswering; -var __webpack_exports__ElectraForSequenceClassification = __webpack_exports__.ElectraForSequenceClassification; -var __webpack_exports__ElectraForTokenClassification = __webpack_exports__.ElectraForTokenClassification; -var __webpack_exports__ElectraModel = __webpack_exports__.ElectraModel; -var __webpack_exports__ElectraPreTrainedModel = __webpack_exports__.ElectraPreTrainedModel; -var __webpack_exports__ElectraTokenizer = __webpack_exports__.ElectraTokenizer; -var __webpack_exports__EncodecFeatureExtractor = __webpack_exports__.EncodecFeatureExtractor; -var __webpack_exports__EosTokenCriteria = __webpack_exports__.EosTokenCriteria; -var __webpack_exports__Ernie4_5_ForCausalLM = __webpack_exports__.Ernie4_5_ForCausalLM; -var __webpack_exports__Ernie4_5_Model = __webpack_exports__.Ernie4_5_Model; -var __webpack_exports__Ernie4_5_PretrainedModel = __webpack_exports__.Ernie4_5_PretrainedModel; -var __webpack_exports__Ernie4_5_Tokenizer = __webpack_exports__.Ernie4_5_Tokenizer; -var __webpack_exports__EsmForMaskedLM = __webpack_exports__.EsmForMaskedLM; -var __webpack_exports__EsmForSequenceClassification = __webpack_exports__.EsmForSequenceClassification; -var __webpack_exports__EsmForTokenClassification = __webpack_exports__.EsmForTokenClassification; -var __webpack_exports__EsmModel = __webpack_exports__.EsmModel; -var __webpack_exports__EsmPreTrainedModel = __webpack_exports__.EsmPreTrainedModel; -var __webpack_exports__EsmTokenizer = __webpack_exports__.EsmTokenizer; -var __webpack_exports__ExaoneForCausalLM = __webpack_exports__.ExaoneForCausalLM; -var __webpack_exports__ExaoneModel = __webpack_exports__.ExaoneModel; -var __webpack_exports__ExaonePreTrainedModel = __webpack_exports__.ExaonePreTrainedModel; -var __webpack_exports__FFT = __webpack_exports__.FFT; -var __webpack_exports__FalconForCausalLM = __webpack_exports__.FalconForCausalLM; -var __webpack_exports__FalconModel = __webpack_exports__.FalconModel; -var __webpack_exports__FalconPreTrainedModel = __webpack_exports__.FalconPreTrainedModel; -var __webpack_exports__FalconTokenizer = __webpack_exports__.FalconTokenizer; -var __webpack_exports__FastViTForImageClassification = __webpack_exports__.FastViTForImageClassification; -var __webpack_exports__FastViTModel = __webpack_exports__.FastViTModel; -var __webpack_exports__FastViTPreTrainedModel = __webpack_exports__.FastViTPreTrainedModel; -var __webpack_exports__FeatureExtractionPipeline = __webpack_exports__.FeatureExtractionPipeline; -var __webpack_exports__FeatureExtractor = __webpack_exports__.FeatureExtractor; -var __webpack_exports__FillMaskPipeline = __webpack_exports__.FillMaskPipeline; -var __webpack_exports__Florence2ForConditionalGeneration = __webpack_exports__.Florence2ForConditionalGeneration; -var __webpack_exports__Florence2PreTrainedModel = __webpack_exports__.Florence2PreTrainedModel; -var __webpack_exports__Florence2Processor = __webpack_exports__.Florence2Processor; -var __webpack_exports__ForcedBOSTokenLogitsProcessor = __webpack_exports__.ForcedBOSTokenLogitsProcessor; -var __webpack_exports__ForcedEOSTokenLogitsProcessor = __webpack_exports__.ForcedEOSTokenLogitsProcessor; -var __webpack_exports__GLPNFeatureExtractor = __webpack_exports__.GLPNFeatureExtractor; -var __webpack_exports__GLPNForDepthEstimation = __webpack_exports__.GLPNForDepthEstimation; -var __webpack_exports__GLPNModel = __webpack_exports__.GLPNModel; -var __webpack_exports__GLPNPreTrainedModel = __webpack_exports__.GLPNPreTrainedModel; -var __webpack_exports__GPT2LMHeadModel = __webpack_exports__.GPT2LMHeadModel; -var __webpack_exports__GPT2Model = __webpack_exports__.GPT2Model; -var __webpack_exports__GPT2PreTrainedModel = __webpack_exports__.GPT2PreTrainedModel; -var __webpack_exports__GPT2Tokenizer = __webpack_exports__.GPT2Tokenizer; -var __webpack_exports__GPTBigCodeForCausalLM = __webpack_exports__.GPTBigCodeForCausalLM; -var __webpack_exports__GPTBigCodeModel = __webpack_exports__.GPTBigCodeModel; -var __webpack_exports__GPTBigCodePreTrainedModel = __webpack_exports__.GPTBigCodePreTrainedModel; -var __webpack_exports__GPTJForCausalLM = __webpack_exports__.GPTJForCausalLM; -var __webpack_exports__GPTJModel = __webpack_exports__.GPTJModel; -var __webpack_exports__GPTJPreTrainedModel = __webpack_exports__.GPTJPreTrainedModel; -var __webpack_exports__GPTNeoForCausalLM = __webpack_exports__.GPTNeoForCausalLM; -var __webpack_exports__GPTNeoModel = __webpack_exports__.GPTNeoModel; -var __webpack_exports__GPTNeoPreTrainedModel = __webpack_exports__.GPTNeoPreTrainedModel; -var __webpack_exports__GPTNeoXForCausalLM = __webpack_exports__.GPTNeoXForCausalLM; -var __webpack_exports__GPTNeoXModel = __webpack_exports__.GPTNeoXModel; -var __webpack_exports__GPTNeoXPreTrainedModel = __webpack_exports__.GPTNeoXPreTrainedModel; -var __webpack_exports__GPTNeoXTokenizer = __webpack_exports__.GPTNeoXTokenizer; -var __webpack_exports__Gemma2ForCausalLM = __webpack_exports__.Gemma2ForCausalLM; -var __webpack_exports__Gemma2Model = __webpack_exports__.Gemma2Model; -var __webpack_exports__Gemma2PreTrainedModel = __webpack_exports__.Gemma2PreTrainedModel; -var __webpack_exports__Gemma3ForCausalLM = __webpack_exports__.Gemma3ForCausalLM; -var __webpack_exports__Gemma3Model = __webpack_exports__.Gemma3Model; -var __webpack_exports__Gemma3PreTrainedModel = __webpack_exports__.Gemma3PreTrainedModel; -var __webpack_exports__Gemma3nAudioFeatureExtractor = __webpack_exports__.Gemma3nAudioFeatureExtractor; -var __webpack_exports__Gemma3nForConditionalGeneration = __webpack_exports__.Gemma3nForConditionalGeneration; -var __webpack_exports__Gemma3nPreTrainedModel = __webpack_exports__.Gemma3nPreTrainedModel; -var __webpack_exports__Gemma3nProcessor = __webpack_exports__.Gemma3nProcessor; -var __webpack_exports__GemmaForCausalLM = __webpack_exports__.GemmaForCausalLM; -var __webpack_exports__GemmaModel = __webpack_exports__.GemmaModel; -var __webpack_exports__GemmaPreTrainedModel = __webpack_exports__.GemmaPreTrainedModel; -var __webpack_exports__GemmaTokenizer = __webpack_exports__.GemmaTokenizer; -var __webpack_exports__GlmForCausalLM = __webpack_exports__.GlmForCausalLM; -var __webpack_exports__GlmModel = __webpack_exports__.GlmModel; -var __webpack_exports__GlmPreTrainedModel = __webpack_exports__.GlmPreTrainedModel; -var __webpack_exports__GraniteForCausalLM = __webpack_exports__.GraniteForCausalLM; -var __webpack_exports__GraniteModel = __webpack_exports__.GraniteModel; -var __webpack_exports__GranitePreTrainedModel = __webpack_exports__.GranitePreTrainedModel; -var __webpack_exports__Grok1Tokenizer = __webpack_exports__.Grok1Tokenizer; -var __webpack_exports__GroundingDinoForObjectDetection = __webpack_exports__.GroundingDinoForObjectDetection; -var __webpack_exports__GroundingDinoImageProcessor = __webpack_exports__.GroundingDinoImageProcessor; -var __webpack_exports__GroundingDinoPreTrainedModel = __webpack_exports__.GroundingDinoPreTrainedModel; -var __webpack_exports__GroundingDinoProcessor = __webpack_exports__.GroundingDinoProcessor; -var __webpack_exports__GroupViTModel = __webpack_exports__.GroupViTModel; -var __webpack_exports__GroupViTPreTrainedModel = __webpack_exports__.GroupViTPreTrainedModel; -var __webpack_exports__HeliumForCausalLM = __webpack_exports__.HeliumForCausalLM; -var __webpack_exports__HeliumModel = __webpack_exports__.HeliumModel; -var __webpack_exports__HeliumPreTrainedModel = __webpack_exports__.HeliumPreTrainedModel; -var __webpack_exports__HerbertTokenizer = __webpack_exports__.HerbertTokenizer; -var __webpack_exports__HieraForImageClassification = __webpack_exports__.HieraForImageClassification; -var __webpack_exports__HieraModel = __webpack_exports__.HieraModel; -var __webpack_exports__HieraPreTrainedModel = __webpack_exports__.HieraPreTrainedModel; -var __webpack_exports__HubertForCTC = __webpack_exports__.HubertForCTC; -var __webpack_exports__HubertForSequenceClassification = __webpack_exports__.HubertForSequenceClassification; -var __webpack_exports__HubertModel = __webpack_exports__.HubertModel; -var __webpack_exports__HubertPreTrainedModel = __webpack_exports__.HubertPreTrainedModel; -var __webpack_exports__IJepaForImageClassification = __webpack_exports__.IJepaForImageClassification; -var __webpack_exports__IJepaModel = __webpack_exports__.IJepaModel; -var __webpack_exports__IJepaPreTrainedModel = __webpack_exports__.IJepaPreTrainedModel; -var __webpack_exports__Idefics3ForConditionalGeneration = __webpack_exports__.Idefics3ForConditionalGeneration; -var __webpack_exports__Idefics3ImageProcessor = __webpack_exports__.Idefics3ImageProcessor; -var __webpack_exports__Idefics3PreTrainedModel = __webpack_exports__.Idefics3PreTrainedModel; -var __webpack_exports__Idefics3Processor = __webpack_exports__.Idefics3Processor; -var __webpack_exports__ImageClassificationPipeline = __webpack_exports__.ImageClassificationPipeline; -var __webpack_exports__ImageFeatureExtractionPipeline = __webpack_exports__.ImageFeatureExtractionPipeline; -var __webpack_exports__ImageFeatureExtractor = __webpack_exports__.ImageFeatureExtractor; -var __webpack_exports__ImageMattingOutput = __webpack_exports__.ImageMattingOutput; -var __webpack_exports__ImageProcessor = __webpack_exports__.ImageProcessor; -var __webpack_exports__ImageSegmentationPipeline = __webpack_exports__.ImageSegmentationPipeline; -var __webpack_exports__ImageToImagePipeline = __webpack_exports__.ImageToImagePipeline; -var __webpack_exports__ImageToTextPipeline = __webpack_exports__.ImageToTextPipeline; -var __webpack_exports__InterruptableStoppingCriteria = __webpack_exports__.InterruptableStoppingCriteria; -var __webpack_exports__JAISLMHeadModel = __webpack_exports__.JAISLMHeadModel; -var __webpack_exports__JAISModel = __webpack_exports__.JAISModel; -var __webpack_exports__JAISPreTrainedModel = __webpack_exports__.JAISPreTrainedModel; -var __webpack_exports__JinaCLIPImageProcessor = __webpack_exports__.JinaCLIPImageProcessor; -var __webpack_exports__JinaCLIPModel = __webpack_exports__.JinaCLIPModel; -var __webpack_exports__JinaCLIPPreTrainedModel = __webpack_exports__.JinaCLIPPreTrainedModel; -var __webpack_exports__JinaCLIPProcessor = __webpack_exports__.JinaCLIPProcessor; -var __webpack_exports__JinaCLIPTextModel = __webpack_exports__.JinaCLIPTextModel; -var __webpack_exports__JinaCLIPVisionModel = __webpack_exports__.JinaCLIPVisionModel; -var __webpack_exports__Lfm2ForCausalLM = __webpack_exports__.Lfm2ForCausalLM; -var __webpack_exports__Lfm2Model = __webpack_exports__.Lfm2Model; -var __webpack_exports__Lfm2PreTrainedModel = __webpack_exports__.Lfm2PreTrainedModel; -var __webpack_exports__LiteWhisperForConditionalGeneration = __webpack_exports__.LiteWhisperForConditionalGeneration; -var __webpack_exports__LlamaForCausalLM = __webpack_exports__.LlamaForCausalLM; -var __webpack_exports__LlamaModel = __webpack_exports__.LlamaModel; -var __webpack_exports__LlamaPreTrainedModel = __webpack_exports__.LlamaPreTrainedModel; -var __webpack_exports__LlamaTokenizer = __webpack_exports__.LlamaTokenizer; -var __webpack_exports__LlavaForConditionalGeneration = __webpack_exports__.LlavaForConditionalGeneration; -var __webpack_exports__LlavaOnevisionForConditionalGeneration = __webpack_exports__.LlavaOnevisionForConditionalGeneration; -var __webpack_exports__LlavaOnevisionImageProcessor = __webpack_exports__.LlavaOnevisionImageProcessor; -var __webpack_exports__LlavaPreTrainedModel = __webpack_exports__.LlavaPreTrainedModel; -var __webpack_exports__LlavaProcessor = __webpack_exports__.LlavaProcessor; -var __webpack_exports__LlavaQwen2ForCausalLM = __webpack_exports__.LlavaQwen2ForCausalLM; -var __webpack_exports__LogitsProcessor = __webpack_exports__.LogitsProcessor; -var __webpack_exports__LogitsProcessorList = __webpack_exports__.LogitsProcessorList; -var __webpack_exports__LogitsWarper = __webpack_exports__.LogitsWarper; -var __webpack_exports__LongT5ForConditionalGeneration = __webpack_exports__.LongT5ForConditionalGeneration; -var __webpack_exports__LongT5Model = __webpack_exports__.LongT5Model; -var __webpack_exports__LongT5PreTrainedModel = __webpack_exports__.LongT5PreTrainedModel; -var __webpack_exports__M2M100ForConditionalGeneration = __webpack_exports__.M2M100ForConditionalGeneration; -var __webpack_exports__M2M100Model = __webpack_exports__.M2M100Model; -var __webpack_exports__M2M100PreTrainedModel = __webpack_exports__.M2M100PreTrainedModel; -var __webpack_exports__M2M100Tokenizer = __webpack_exports__.M2M100Tokenizer; -var __webpack_exports__MBart50Tokenizer = __webpack_exports__.MBart50Tokenizer; -var __webpack_exports__MBartForCausalLM = __webpack_exports__.MBartForCausalLM; -var __webpack_exports__MBartForConditionalGeneration = __webpack_exports__.MBartForConditionalGeneration; -var __webpack_exports__MBartForSequenceClassification = __webpack_exports__.MBartForSequenceClassification; -var __webpack_exports__MBartModel = __webpack_exports__.MBartModel; -var __webpack_exports__MBartPreTrainedModel = __webpack_exports__.MBartPreTrainedModel; -var __webpack_exports__MBartTokenizer = __webpack_exports__.MBartTokenizer; -var __webpack_exports__MPNetForMaskedLM = __webpack_exports__.MPNetForMaskedLM; -var __webpack_exports__MPNetForQuestionAnswering = __webpack_exports__.MPNetForQuestionAnswering; -var __webpack_exports__MPNetForSequenceClassification = __webpack_exports__.MPNetForSequenceClassification; -var __webpack_exports__MPNetForTokenClassification = __webpack_exports__.MPNetForTokenClassification; -var __webpack_exports__MPNetModel = __webpack_exports__.MPNetModel; -var __webpack_exports__MPNetPreTrainedModel = __webpack_exports__.MPNetPreTrainedModel; -var __webpack_exports__MPNetTokenizer = __webpack_exports__.MPNetTokenizer; -var __webpack_exports__MT5ForConditionalGeneration = __webpack_exports__.MT5ForConditionalGeneration; -var __webpack_exports__MT5Model = __webpack_exports__.MT5Model; -var __webpack_exports__MT5PreTrainedModel = __webpack_exports__.MT5PreTrainedModel; -var __webpack_exports__MarianMTModel = __webpack_exports__.MarianMTModel; -var __webpack_exports__MarianModel = __webpack_exports__.MarianModel; -var __webpack_exports__MarianPreTrainedModel = __webpack_exports__.MarianPreTrainedModel; -var __webpack_exports__MarianTokenizer = __webpack_exports__.MarianTokenizer; -var __webpack_exports__Mask2FormerImageProcessor = __webpack_exports__.Mask2FormerImageProcessor; -var __webpack_exports__MaskFormerFeatureExtractor = __webpack_exports__.MaskFormerFeatureExtractor; -var __webpack_exports__MaskFormerForInstanceSegmentation = __webpack_exports__.MaskFormerForInstanceSegmentation; -var __webpack_exports__MaskFormerImageProcessor = __webpack_exports__.MaskFormerImageProcessor; -var __webpack_exports__MaskFormerModel = __webpack_exports__.MaskFormerModel; -var __webpack_exports__MaskFormerPreTrainedModel = __webpack_exports__.MaskFormerPreTrainedModel; -var __webpack_exports__MaskedLMOutput = __webpack_exports__.MaskedLMOutput; -var __webpack_exports__MaxLengthCriteria = __webpack_exports__.MaxLengthCriteria; -var __webpack_exports__Metric3DForDepthEstimation = __webpack_exports__.Metric3DForDepthEstimation; -var __webpack_exports__Metric3DPreTrainedModel = __webpack_exports__.Metric3DPreTrainedModel; -var __webpack_exports__Metric3Dv2ForDepthEstimation = __webpack_exports__.Metric3Dv2ForDepthEstimation; -var __webpack_exports__Metric3Dv2PreTrainedModel = __webpack_exports__.Metric3Dv2PreTrainedModel; -var __webpack_exports__MgpstrForSceneTextRecognition = __webpack_exports__.MgpstrForSceneTextRecognition; -var __webpack_exports__MgpstrModelOutput = __webpack_exports__.MgpstrModelOutput; -var __webpack_exports__MgpstrPreTrainedModel = __webpack_exports__.MgpstrPreTrainedModel; -var __webpack_exports__MgpstrProcessor = __webpack_exports__.MgpstrProcessor; -var __webpack_exports__MgpstrTokenizer = __webpack_exports__.MgpstrTokenizer; -var __webpack_exports__MimiDecoderModel = __webpack_exports__.MimiDecoderModel; -var __webpack_exports__MimiDecoderOutput = __webpack_exports__.MimiDecoderOutput; -var __webpack_exports__MimiEncoderModel = __webpack_exports__.MimiEncoderModel; -var __webpack_exports__MimiEncoderOutput = __webpack_exports__.MimiEncoderOutput; -var __webpack_exports__MimiModel = __webpack_exports__.MimiModel; -var __webpack_exports__MimiPreTrainedModel = __webpack_exports__.MimiPreTrainedModel; -var __webpack_exports__MinLengthLogitsProcessor = __webpack_exports__.MinLengthLogitsProcessor; -var __webpack_exports__MinNewTokensLengthLogitsProcessor = __webpack_exports__.MinNewTokensLengthLogitsProcessor; -var __webpack_exports__MistralForCausalLM = __webpack_exports__.MistralForCausalLM; -var __webpack_exports__MistralModel = __webpack_exports__.MistralModel; -var __webpack_exports__MistralPreTrainedModel = __webpack_exports__.MistralPreTrainedModel; -var __webpack_exports__MobileBertForMaskedLM = __webpack_exports__.MobileBertForMaskedLM; -var __webpack_exports__MobileBertForQuestionAnswering = __webpack_exports__.MobileBertForQuestionAnswering; -var __webpack_exports__MobileBertForSequenceClassification = __webpack_exports__.MobileBertForSequenceClassification; -var __webpack_exports__MobileBertModel = __webpack_exports__.MobileBertModel; -var __webpack_exports__MobileBertPreTrainedModel = __webpack_exports__.MobileBertPreTrainedModel; -var __webpack_exports__MobileBertTokenizer = __webpack_exports__.MobileBertTokenizer; -var __webpack_exports__MobileLLMForCausalLM = __webpack_exports__.MobileLLMForCausalLM; -var __webpack_exports__MobileLLMModel = __webpack_exports__.MobileLLMModel; -var __webpack_exports__MobileLLMPreTrainedModel = __webpack_exports__.MobileLLMPreTrainedModel; -var __webpack_exports__MobileNetV1FeatureExtractor = __webpack_exports__.MobileNetV1FeatureExtractor; -var __webpack_exports__MobileNetV1ForImageClassification = __webpack_exports__.MobileNetV1ForImageClassification; -var __webpack_exports__MobileNetV1ForSemanticSegmentation = __webpack_exports__.MobileNetV1ForSemanticSegmentation; -var __webpack_exports__MobileNetV1ImageProcessor = __webpack_exports__.MobileNetV1ImageProcessor; -var __webpack_exports__MobileNetV1Model = __webpack_exports__.MobileNetV1Model; -var __webpack_exports__MobileNetV1PreTrainedModel = __webpack_exports__.MobileNetV1PreTrainedModel; -var __webpack_exports__MobileNetV2FeatureExtractor = __webpack_exports__.MobileNetV2FeatureExtractor; -var __webpack_exports__MobileNetV2ForImageClassification = __webpack_exports__.MobileNetV2ForImageClassification; -var __webpack_exports__MobileNetV2ForSemanticSegmentation = __webpack_exports__.MobileNetV2ForSemanticSegmentation; -var __webpack_exports__MobileNetV2ImageProcessor = __webpack_exports__.MobileNetV2ImageProcessor; -var __webpack_exports__MobileNetV2Model = __webpack_exports__.MobileNetV2Model; -var __webpack_exports__MobileNetV2PreTrainedModel = __webpack_exports__.MobileNetV2PreTrainedModel; -var __webpack_exports__MobileNetV3FeatureExtractor = __webpack_exports__.MobileNetV3FeatureExtractor; -var __webpack_exports__MobileNetV3ForImageClassification = __webpack_exports__.MobileNetV3ForImageClassification; -var __webpack_exports__MobileNetV3ForSemanticSegmentation = __webpack_exports__.MobileNetV3ForSemanticSegmentation; -var __webpack_exports__MobileNetV3ImageProcessor = __webpack_exports__.MobileNetV3ImageProcessor; -var __webpack_exports__MobileNetV3Model = __webpack_exports__.MobileNetV3Model; -var __webpack_exports__MobileNetV3PreTrainedModel = __webpack_exports__.MobileNetV3PreTrainedModel; -var __webpack_exports__MobileNetV4FeatureExtractor = __webpack_exports__.MobileNetV4FeatureExtractor; -var __webpack_exports__MobileNetV4ForImageClassification = __webpack_exports__.MobileNetV4ForImageClassification; -var __webpack_exports__MobileNetV4ForSemanticSegmentation = __webpack_exports__.MobileNetV4ForSemanticSegmentation; -var __webpack_exports__MobileNetV4ImageProcessor = __webpack_exports__.MobileNetV4ImageProcessor; -var __webpack_exports__MobileNetV4Model = __webpack_exports__.MobileNetV4Model; -var __webpack_exports__MobileNetV4PreTrainedModel = __webpack_exports__.MobileNetV4PreTrainedModel; -var __webpack_exports__MobileViTFeatureExtractor = __webpack_exports__.MobileViTFeatureExtractor; -var __webpack_exports__MobileViTForImageClassification = __webpack_exports__.MobileViTForImageClassification; -var __webpack_exports__MobileViTImageProcessor = __webpack_exports__.MobileViTImageProcessor; -var __webpack_exports__MobileViTModel = __webpack_exports__.MobileViTModel; -var __webpack_exports__MobileViTPreTrainedModel = __webpack_exports__.MobileViTPreTrainedModel; -var __webpack_exports__MobileViTV2ForImageClassification = __webpack_exports__.MobileViTV2ForImageClassification; -var __webpack_exports__MobileViTV2Model = __webpack_exports__.MobileViTV2Model; -var __webpack_exports__MobileViTV2PreTrainedModel = __webpack_exports__.MobileViTV2PreTrainedModel; -var __webpack_exports__ModelOutput = __webpack_exports__.ModelOutput; -var __webpack_exports__ModernBertDecoderForCausalLM = __webpack_exports__.ModernBertDecoderForCausalLM; -var __webpack_exports__ModernBertDecoderModel = __webpack_exports__.ModernBertDecoderModel; -var __webpack_exports__ModernBertDecoderPreTrainedModel = __webpack_exports__.ModernBertDecoderPreTrainedModel; -var __webpack_exports__ModernBertForMaskedLM = __webpack_exports__.ModernBertForMaskedLM; -var __webpack_exports__ModernBertForSequenceClassification = __webpack_exports__.ModernBertForSequenceClassification; -var __webpack_exports__ModernBertForTokenClassification = __webpack_exports__.ModernBertForTokenClassification; -var __webpack_exports__ModernBertModel = __webpack_exports__.ModernBertModel; -var __webpack_exports__ModernBertPreTrainedModel = __webpack_exports__.ModernBertPreTrainedModel; -var __webpack_exports__Moondream1ForConditionalGeneration = __webpack_exports__.Moondream1ForConditionalGeneration; -var __webpack_exports__MoonshineFeatureExtractor = __webpack_exports__.MoonshineFeatureExtractor; -var __webpack_exports__MoonshineForConditionalGeneration = __webpack_exports__.MoonshineForConditionalGeneration; -var __webpack_exports__MoonshineModel = __webpack_exports__.MoonshineModel; -var __webpack_exports__MoonshinePreTrainedModel = __webpack_exports__.MoonshinePreTrainedModel; -var __webpack_exports__MoonshineProcessor = __webpack_exports__.MoonshineProcessor; -var __webpack_exports__MptForCausalLM = __webpack_exports__.MptForCausalLM; -var __webpack_exports__MptModel = __webpack_exports__.MptModel; -var __webpack_exports__MptPreTrainedModel = __webpack_exports__.MptPreTrainedModel; -var __webpack_exports__MultiModalityCausalLM = __webpack_exports__.MultiModalityCausalLM; -var __webpack_exports__MultiModalityPreTrainedModel = __webpack_exports__.MultiModalityPreTrainedModel; -var __webpack_exports__MusicgenForCausalLM = __webpack_exports__.MusicgenForCausalLM; -var __webpack_exports__MusicgenForConditionalGeneration = __webpack_exports__.MusicgenForConditionalGeneration; -var __webpack_exports__MusicgenModel = __webpack_exports__.MusicgenModel; -var __webpack_exports__MusicgenPreTrainedModel = __webpack_exports__.MusicgenPreTrainedModel; -var __webpack_exports__NeoBertForMaskedLM = __webpack_exports__.NeoBertForMaskedLM; -var __webpack_exports__NeoBertForQuestionAnswering = __webpack_exports__.NeoBertForQuestionAnswering; -var __webpack_exports__NeoBertForSequenceClassification = __webpack_exports__.NeoBertForSequenceClassification; -var __webpack_exports__NeoBertForTokenClassification = __webpack_exports__.NeoBertForTokenClassification; -var __webpack_exports__NeoBertModel = __webpack_exports__.NeoBertModel; -var __webpack_exports__NeoBertPreTrainedModel = __webpack_exports__.NeoBertPreTrainedModel; -var __webpack_exports__NllbTokenizer = __webpack_exports__.NllbTokenizer; -var __webpack_exports__NoBadWordsLogitsProcessor = __webpack_exports__.NoBadWordsLogitsProcessor; -var __webpack_exports__NoRepeatNGramLogitsProcessor = __webpack_exports__.NoRepeatNGramLogitsProcessor; -var __webpack_exports__NomicBertModel = __webpack_exports__.NomicBertModel; -var __webpack_exports__NomicBertPreTrainedModel = __webpack_exports__.NomicBertPreTrainedModel; -var __webpack_exports__NougatImageProcessor = __webpack_exports__.NougatImageProcessor; -var __webpack_exports__NougatTokenizer = __webpack_exports__.NougatTokenizer; -var __webpack_exports__OPTForCausalLM = __webpack_exports__.OPTForCausalLM; -var __webpack_exports__OPTModel = __webpack_exports__.OPTModel; -var __webpack_exports__OPTPreTrainedModel = __webpack_exports__.OPTPreTrainedModel; -var __webpack_exports__ObjectDetectionPipeline = __webpack_exports__.ObjectDetectionPipeline; -var __webpack_exports__Olmo2ForCausalLM = __webpack_exports__.Olmo2ForCausalLM; -var __webpack_exports__Olmo2Model = __webpack_exports__.Olmo2Model; -var __webpack_exports__Olmo2PreTrainedModel = __webpack_exports__.Olmo2PreTrainedModel; -var __webpack_exports__OlmoForCausalLM = __webpack_exports__.OlmoForCausalLM; -var __webpack_exports__OlmoModel = __webpack_exports__.OlmoModel; -var __webpack_exports__OlmoPreTrainedModel = __webpack_exports__.OlmoPreTrainedModel; -var __webpack_exports__OpenELMForCausalLM = __webpack_exports__.OpenELMForCausalLM; -var __webpack_exports__OpenELMModel = __webpack_exports__.OpenELMModel; -var __webpack_exports__OpenELMPreTrainedModel = __webpack_exports__.OpenELMPreTrainedModel; -var __webpack_exports__OwlViTFeatureExtractor = __webpack_exports__.OwlViTFeatureExtractor; -var __webpack_exports__OwlViTForObjectDetection = __webpack_exports__.OwlViTForObjectDetection; -var __webpack_exports__OwlViTImageProcessor = __webpack_exports__.OwlViTImageProcessor; -var __webpack_exports__OwlViTModel = __webpack_exports__.OwlViTModel; -var __webpack_exports__OwlViTPreTrainedModel = __webpack_exports__.OwlViTPreTrainedModel; -var __webpack_exports__OwlViTProcessor = __webpack_exports__.OwlViTProcessor; -var __webpack_exports__Owlv2ForObjectDetection = __webpack_exports__.Owlv2ForObjectDetection; -var __webpack_exports__Owlv2ImageProcessor = __webpack_exports__.Owlv2ImageProcessor; -var __webpack_exports__Owlv2Model = __webpack_exports__.Owlv2Model; -var __webpack_exports__Owlv2PreTrainedModel = __webpack_exports__.Owlv2PreTrainedModel; -var __webpack_exports__PaliGemmaForConditionalGeneration = __webpack_exports__.PaliGemmaForConditionalGeneration; -var __webpack_exports__PaliGemmaPreTrainedModel = __webpack_exports__.PaliGemmaPreTrainedModel; -var __webpack_exports__PaliGemmaProcessor = __webpack_exports__.PaliGemmaProcessor; -var __webpack_exports__PatchTSMixerForPrediction = __webpack_exports__.PatchTSMixerForPrediction; -var __webpack_exports__PatchTSMixerModel = __webpack_exports__.PatchTSMixerModel; -var __webpack_exports__PatchTSMixerPreTrainedModel = __webpack_exports__.PatchTSMixerPreTrainedModel; -var __webpack_exports__PatchTSTForPrediction = __webpack_exports__.PatchTSTForPrediction; -var __webpack_exports__PatchTSTModel = __webpack_exports__.PatchTSTModel; -var __webpack_exports__PatchTSTPreTrainedModel = __webpack_exports__.PatchTSTPreTrainedModel; -var __webpack_exports__Phi3ForCausalLM = __webpack_exports__.Phi3ForCausalLM; -var __webpack_exports__Phi3Model = __webpack_exports__.Phi3Model; -var __webpack_exports__Phi3PreTrainedModel = __webpack_exports__.Phi3PreTrainedModel; -var __webpack_exports__Phi3VForCausalLM = __webpack_exports__.Phi3VForCausalLM; -var __webpack_exports__Phi3VImageProcessor = __webpack_exports__.Phi3VImageProcessor; -var __webpack_exports__Phi3VPreTrainedModel = __webpack_exports__.Phi3VPreTrainedModel; -var __webpack_exports__Phi3VProcessor = __webpack_exports__.Phi3VProcessor; -var __webpack_exports__PhiForCausalLM = __webpack_exports__.PhiForCausalLM; -var __webpack_exports__PhiModel = __webpack_exports__.PhiModel; -var __webpack_exports__PhiPreTrainedModel = __webpack_exports__.PhiPreTrainedModel; -var __webpack_exports__Pipeline = __webpack_exports__.Pipeline; -var __webpack_exports__PreTrainedModel = __webpack_exports__.PreTrainedModel; -var __webpack_exports__PreTrainedTokenizer = __webpack_exports__.PreTrainedTokenizer; -var __webpack_exports__PretrainedConfig = __webpack_exports__.PretrainedConfig; -var __webpack_exports__PretrainedMixin = __webpack_exports__.PretrainedMixin; -var __webpack_exports__Processor = __webpack_exports__.Processor; -var __webpack_exports__PvtForImageClassification = __webpack_exports__.PvtForImageClassification; -var __webpack_exports__PvtImageProcessor = __webpack_exports__.PvtImageProcessor; -var __webpack_exports__PvtModel = __webpack_exports__.PvtModel; -var __webpack_exports__PvtPreTrainedModel = __webpack_exports__.PvtPreTrainedModel; -var __webpack_exports__PyAnnoteFeatureExtractor = __webpack_exports__.PyAnnoteFeatureExtractor; -var __webpack_exports__PyAnnoteForAudioFrameClassification = __webpack_exports__.PyAnnoteForAudioFrameClassification; -var __webpack_exports__PyAnnoteModel = __webpack_exports__.PyAnnoteModel; -var __webpack_exports__PyAnnotePreTrainedModel = __webpack_exports__.PyAnnotePreTrainedModel; -var __webpack_exports__PyAnnoteProcessor = __webpack_exports__.PyAnnoteProcessor; -var __webpack_exports__QuestionAnsweringModelOutput = __webpack_exports__.QuestionAnsweringModelOutput; -var __webpack_exports__QuestionAnsweringPipeline = __webpack_exports__.QuestionAnsweringPipeline; -var __webpack_exports__Qwen2ForCausalLM = __webpack_exports__.Qwen2ForCausalLM; -var __webpack_exports__Qwen2Model = __webpack_exports__.Qwen2Model; -var __webpack_exports__Qwen2PreTrainedModel = __webpack_exports__.Qwen2PreTrainedModel; -var __webpack_exports__Qwen2Tokenizer = __webpack_exports__.Qwen2Tokenizer; -var __webpack_exports__Qwen2VLForConditionalGeneration = __webpack_exports__.Qwen2VLForConditionalGeneration; -var __webpack_exports__Qwen2VLImageProcessor = __webpack_exports__.Qwen2VLImageProcessor; -var __webpack_exports__Qwen2VLPreTrainedModel = __webpack_exports__.Qwen2VLPreTrainedModel; -var __webpack_exports__Qwen2VLProcessor = __webpack_exports__.Qwen2VLProcessor; -var __webpack_exports__Qwen3ForCausalLM = __webpack_exports__.Qwen3ForCausalLM; -var __webpack_exports__Qwen3Model = __webpack_exports__.Qwen3Model; -var __webpack_exports__Qwen3PreTrainedModel = __webpack_exports__.Qwen3PreTrainedModel; -var __webpack_exports__RFDetrForObjectDetection = __webpack_exports__.RFDetrForObjectDetection; -var __webpack_exports__RFDetrModel = __webpack_exports__.RFDetrModel; -var __webpack_exports__RFDetrObjectDetectionOutput = __webpack_exports__.RFDetrObjectDetectionOutput; -var __webpack_exports__RFDetrPreTrainedModel = __webpack_exports__.RFDetrPreTrainedModel; -var __webpack_exports__RTDetrForObjectDetection = __webpack_exports__.RTDetrForObjectDetection; -var __webpack_exports__RTDetrImageProcessor = __webpack_exports__.RTDetrImageProcessor; -var __webpack_exports__RTDetrModel = __webpack_exports__.RTDetrModel; -var __webpack_exports__RTDetrObjectDetectionOutput = __webpack_exports__.RTDetrObjectDetectionOutput; -var __webpack_exports__RTDetrPreTrainedModel = __webpack_exports__.RTDetrPreTrainedModel; -var __webpack_exports__RTDetrV2ForObjectDetection = __webpack_exports__.RTDetrV2ForObjectDetection; -var __webpack_exports__RTDetrV2Model = __webpack_exports__.RTDetrV2Model; -var __webpack_exports__RTDetrV2ObjectDetectionOutput = __webpack_exports__.RTDetrV2ObjectDetectionOutput; -var __webpack_exports__RTDetrV2PreTrainedModel = __webpack_exports__.RTDetrV2PreTrainedModel; -var __webpack_exports__RawAudio = __webpack_exports__.RawAudio; -var __webpack_exports__RawImage = __webpack_exports__.RawImage; -var __webpack_exports__RawVideo = __webpack_exports__.RawVideo; -var __webpack_exports__RawVideoFrame = __webpack_exports__.RawVideoFrame; -var __webpack_exports__RepetitionPenaltyLogitsProcessor = __webpack_exports__.RepetitionPenaltyLogitsProcessor; -var __webpack_exports__ResNetForImageClassification = __webpack_exports__.ResNetForImageClassification; -var __webpack_exports__ResNetModel = __webpack_exports__.ResNetModel; -var __webpack_exports__ResNetPreTrainedModel = __webpack_exports__.ResNetPreTrainedModel; -var __webpack_exports__RoFormerForMaskedLM = __webpack_exports__.RoFormerForMaskedLM; -var __webpack_exports__RoFormerForQuestionAnswering = __webpack_exports__.RoFormerForQuestionAnswering; -var __webpack_exports__RoFormerForSequenceClassification = __webpack_exports__.RoFormerForSequenceClassification; -var __webpack_exports__RoFormerForTokenClassification = __webpack_exports__.RoFormerForTokenClassification; -var __webpack_exports__RoFormerModel = __webpack_exports__.RoFormerModel; -var __webpack_exports__RoFormerPreTrainedModel = __webpack_exports__.RoFormerPreTrainedModel; -var __webpack_exports__RoFormerTokenizer = __webpack_exports__.RoFormerTokenizer; -var __webpack_exports__RobertaForMaskedLM = __webpack_exports__.RobertaForMaskedLM; -var __webpack_exports__RobertaForQuestionAnswering = __webpack_exports__.RobertaForQuestionAnswering; -var __webpack_exports__RobertaForSequenceClassification = __webpack_exports__.RobertaForSequenceClassification; -var __webpack_exports__RobertaForTokenClassification = __webpack_exports__.RobertaForTokenClassification; -var __webpack_exports__RobertaModel = __webpack_exports__.RobertaModel; -var __webpack_exports__RobertaPreTrainedModel = __webpack_exports__.RobertaPreTrainedModel; -var __webpack_exports__RobertaTokenizer = __webpack_exports__.RobertaTokenizer; -var __webpack_exports__SamImageProcessor = __webpack_exports__.SamImageProcessor; -var __webpack_exports__SamImageSegmentationOutput = __webpack_exports__.SamImageSegmentationOutput; -var __webpack_exports__SamModel = __webpack_exports__.SamModel; -var __webpack_exports__SamPreTrainedModel = __webpack_exports__.SamPreTrainedModel; -var __webpack_exports__SamProcessor = __webpack_exports__.SamProcessor; -var __webpack_exports__SapiensForDepthEstimation = __webpack_exports__.SapiensForDepthEstimation; -var __webpack_exports__SapiensForNormalEstimation = __webpack_exports__.SapiensForNormalEstimation; -var __webpack_exports__SapiensForSemanticSegmentation = __webpack_exports__.SapiensForSemanticSegmentation; -var __webpack_exports__SapiensPreTrainedModel = __webpack_exports__.SapiensPreTrainedModel; -var __webpack_exports__SeamlessM4TFeatureExtractor = __webpack_exports__.SeamlessM4TFeatureExtractor; -var __webpack_exports__SegformerFeatureExtractor = __webpack_exports__.SegformerFeatureExtractor; -var __webpack_exports__SegformerForImageClassification = __webpack_exports__.SegformerForImageClassification; -var __webpack_exports__SegformerForSemanticSegmentation = __webpack_exports__.SegformerForSemanticSegmentation; -var __webpack_exports__SegformerImageProcessor = __webpack_exports__.SegformerImageProcessor; -var __webpack_exports__SegformerModel = __webpack_exports__.SegformerModel; -var __webpack_exports__SegformerPreTrainedModel = __webpack_exports__.SegformerPreTrainedModel; -var __webpack_exports__Seq2SeqLMOutput = __webpack_exports__.Seq2SeqLMOutput; -var __webpack_exports__SequenceClassifierOutput = __webpack_exports__.SequenceClassifierOutput; -var __webpack_exports__SiglipImageProcessor = __webpack_exports__.SiglipImageProcessor; -var __webpack_exports__SiglipModel = __webpack_exports__.SiglipModel; -var __webpack_exports__SiglipPreTrainedModel = __webpack_exports__.SiglipPreTrainedModel; -var __webpack_exports__SiglipTextModel = __webpack_exports__.SiglipTextModel; -var __webpack_exports__SiglipTokenizer = __webpack_exports__.SiglipTokenizer; -var __webpack_exports__SiglipVisionModel = __webpack_exports__.SiglipVisionModel; -var __webpack_exports__SmolLM3ForCausalLM = __webpack_exports__.SmolLM3ForCausalLM; -var __webpack_exports__SmolLM3Model = __webpack_exports__.SmolLM3Model; -var __webpack_exports__SmolLM3PreTrainedModel = __webpack_exports__.SmolLM3PreTrainedModel; -var __webpack_exports__SmolVLMForConditionalGeneration = __webpack_exports__.SmolVLMForConditionalGeneration; -var __webpack_exports__SmolVLMImageProcessor = __webpack_exports__.SmolVLMImageProcessor; -var __webpack_exports__SmolVLMProcessor = __webpack_exports__.SmolVLMProcessor; -var __webpack_exports__SnacDecoderModel = __webpack_exports__.SnacDecoderModel; -var __webpack_exports__SnacEncoderModel = __webpack_exports__.SnacEncoderModel; -var __webpack_exports__SnacFeatureExtractor = __webpack_exports__.SnacFeatureExtractor; -var __webpack_exports__SnacModel = __webpack_exports__.SnacModel; -var __webpack_exports__SnacPreTrainedModel = __webpack_exports__.SnacPreTrainedModel; -var __webpack_exports__SpeechT5FeatureExtractor = __webpack_exports__.SpeechT5FeatureExtractor; -var __webpack_exports__SpeechT5ForSpeechToText = __webpack_exports__.SpeechT5ForSpeechToText; -var __webpack_exports__SpeechT5ForTextToSpeech = __webpack_exports__.SpeechT5ForTextToSpeech; -var __webpack_exports__SpeechT5HifiGan = __webpack_exports__.SpeechT5HifiGan; -var __webpack_exports__SpeechT5Model = __webpack_exports__.SpeechT5Model; -var __webpack_exports__SpeechT5PreTrainedModel = __webpack_exports__.SpeechT5PreTrainedModel; -var __webpack_exports__SpeechT5Processor = __webpack_exports__.SpeechT5Processor; -var __webpack_exports__SpeechT5Tokenizer = __webpack_exports__.SpeechT5Tokenizer; -var __webpack_exports__SqueezeBertForMaskedLM = __webpack_exports__.SqueezeBertForMaskedLM; -var __webpack_exports__SqueezeBertForQuestionAnswering = __webpack_exports__.SqueezeBertForQuestionAnswering; -var __webpack_exports__SqueezeBertForSequenceClassification = __webpack_exports__.SqueezeBertForSequenceClassification; -var __webpack_exports__SqueezeBertModel = __webpack_exports__.SqueezeBertModel; -var __webpack_exports__SqueezeBertPreTrainedModel = __webpack_exports__.SqueezeBertPreTrainedModel; -var __webpack_exports__SqueezeBertTokenizer = __webpack_exports__.SqueezeBertTokenizer; -var __webpack_exports__StableLmForCausalLM = __webpack_exports__.StableLmForCausalLM; -var __webpack_exports__StableLmModel = __webpack_exports__.StableLmModel; -var __webpack_exports__StableLmPreTrainedModel = __webpack_exports__.StableLmPreTrainedModel; -var __webpack_exports__Starcoder2ForCausalLM = __webpack_exports__.Starcoder2ForCausalLM; -var __webpack_exports__Starcoder2Model = __webpack_exports__.Starcoder2Model; -var __webpack_exports__Starcoder2PreTrainedModel = __webpack_exports__.Starcoder2PreTrainedModel; -var __webpack_exports__StoppingCriteria = __webpack_exports__.StoppingCriteria; -var __webpack_exports__StoppingCriteriaList = __webpack_exports__.StoppingCriteriaList; -var __webpack_exports__StyleTextToSpeech2Model = __webpack_exports__.StyleTextToSpeech2Model; -var __webpack_exports__StyleTextToSpeech2PreTrainedModel = __webpack_exports__.StyleTextToSpeech2PreTrainedModel; -var __webpack_exports__SummarizationPipeline = __webpack_exports__.SummarizationPipeline; -var __webpack_exports__SuppressTokensAtBeginLogitsProcessor = __webpack_exports__.SuppressTokensAtBeginLogitsProcessor; -var __webpack_exports__Swin2SRForImageSuperResolution = __webpack_exports__.Swin2SRForImageSuperResolution; -var __webpack_exports__Swin2SRImageProcessor = __webpack_exports__.Swin2SRImageProcessor; -var __webpack_exports__Swin2SRModel = __webpack_exports__.Swin2SRModel; -var __webpack_exports__Swin2SRPreTrainedModel = __webpack_exports__.Swin2SRPreTrainedModel; -var __webpack_exports__SwinForImageClassification = __webpack_exports__.SwinForImageClassification; -var __webpack_exports__SwinForSemanticSegmentation = __webpack_exports__.SwinForSemanticSegmentation; -var __webpack_exports__SwinModel = __webpack_exports__.SwinModel; -var __webpack_exports__SwinPreTrainedModel = __webpack_exports__.SwinPreTrainedModel; -var __webpack_exports__T5ForConditionalGeneration = __webpack_exports__.T5ForConditionalGeneration; -var __webpack_exports__T5Model = __webpack_exports__.T5Model; -var __webpack_exports__T5PreTrainedModel = __webpack_exports__.T5PreTrainedModel; -var __webpack_exports__T5Tokenizer = __webpack_exports__.T5Tokenizer; -var __webpack_exports__TableTransformerForObjectDetection = __webpack_exports__.TableTransformerForObjectDetection; -var __webpack_exports__TableTransformerModel = __webpack_exports__.TableTransformerModel; -var __webpack_exports__TableTransformerObjectDetectionOutput = __webpack_exports__.TableTransformerObjectDetectionOutput; -var __webpack_exports__TableTransformerPreTrainedModel = __webpack_exports__.TableTransformerPreTrainedModel; -var __webpack_exports__TemperatureLogitsWarper = __webpack_exports__.TemperatureLogitsWarper; -var __webpack_exports__Tensor = __webpack_exports__.Tensor; -var __webpack_exports__Text2TextGenerationPipeline = __webpack_exports__.Text2TextGenerationPipeline; -var __webpack_exports__TextClassificationPipeline = __webpack_exports__.TextClassificationPipeline; -var __webpack_exports__TextGenerationPipeline = __webpack_exports__.TextGenerationPipeline; -var __webpack_exports__TextStreamer = __webpack_exports__.TextStreamer; -var __webpack_exports__TextToAudioPipeline = __webpack_exports__.TextToAudioPipeline; -var __webpack_exports__TokenClassificationPipeline = __webpack_exports__.TokenClassificationPipeline; -var __webpack_exports__TokenClassifierOutput = __webpack_exports__.TokenClassifierOutput; -var __webpack_exports__TokenizerModel = __webpack_exports__.TokenizerModel; -var __webpack_exports__TopKLogitsWarper = __webpack_exports__.TopKLogitsWarper; -var __webpack_exports__TopPLogitsWarper = __webpack_exports__.TopPLogitsWarper; -var __webpack_exports__TrOCRForCausalLM = __webpack_exports__.TrOCRForCausalLM; -var __webpack_exports__TrOCRPreTrainedModel = __webpack_exports__.TrOCRPreTrainedModel; -var __webpack_exports__TranslationPipeline = __webpack_exports__.TranslationPipeline; -var __webpack_exports__UltravoxModel = __webpack_exports__.UltravoxModel; -var __webpack_exports__UltravoxPreTrainedModel = __webpack_exports__.UltravoxPreTrainedModel; -var __webpack_exports__UltravoxProcessor = __webpack_exports__.UltravoxProcessor; -var __webpack_exports__UniSpeechForCTC = __webpack_exports__.UniSpeechForCTC; -var __webpack_exports__UniSpeechForSequenceClassification = __webpack_exports__.UniSpeechForSequenceClassification; -var __webpack_exports__UniSpeechModel = __webpack_exports__.UniSpeechModel; -var __webpack_exports__UniSpeechPreTrainedModel = __webpack_exports__.UniSpeechPreTrainedModel; -var __webpack_exports__UniSpeechSatForAudioFrameClassification = __webpack_exports__.UniSpeechSatForAudioFrameClassification; -var __webpack_exports__UniSpeechSatForCTC = __webpack_exports__.UniSpeechSatForCTC; -var __webpack_exports__UniSpeechSatForSequenceClassification = __webpack_exports__.UniSpeechSatForSequenceClassification; -var __webpack_exports__UniSpeechSatModel = __webpack_exports__.UniSpeechSatModel; -var __webpack_exports__UniSpeechSatPreTrainedModel = __webpack_exports__.UniSpeechSatPreTrainedModel; -var __webpack_exports__VLChatProcessor = __webpack_exports__.VLChatProcessor; -var __webpack_exports__VLMImageProcessor = __webpack_exports__.VLMImageProcessor; -var __webpack_exports__ViTFeatureExtractor = __webpack_exports__.ViTFeatureExtractor; -var __webpack_exports__ViTForImageClassification = __webpack_exports__.ViTForImageClassification; -var __webpack_exports__ViTImageProcessor = __webpack_exports__.ViTImageProcessor; -var __webpack_exports__ViTMAEModel = __webpack_exports__.ViTMAEModel; -var __webpack_exports__ViTMAEPreTrainedModel = __webpack_exports__.ViTMAEPreTrainedModel; -var __webpack_exports__ViTMSNForImageClassification = __webpack_exports__.ViTMSNForImageClassification; -var __webpack_exports__ViTMSNModel = __webpack_exports__.ViTMSNModel; -var __webpack_exports__ViTMSNPreTrainedModel = __webpack_exports__.ViTMSNPreTrainedModel; -var __webpack_exports__ViTModel = __webpack_exports__.ViTModel; -var __webpack_exports__ViTPreTrainedModel = __webpack_exports__.ViTPreTrainedModel; -var __webpack_exports__VisionEncoderDecoderModel = __webpack_exports__.VisionEncoderDecoderModel; -var __webpack_exports__VitMatteForImageMatting = __webpack_exports__.VitMatteForImageMatting; -var __webpack_exports__VitMatteImageProcessor = __webpack_exports__.VitMatteImageProcessor; -var __webpack_exports__VitMattePreTrainedModel = __webpack_exports__.VitMattePreTrainedModel; -var __webpack_exports__VitPoseForPoseEstimation = __webpack_exports__.VitPoseForPoseEstimation; -var __webpack_exports__VitPoseImageProcessor = __webpack_exports__.VitPoseImageProcessor; -var __webpack_exports__VitPosePreTrainedModel = __webpack_exports__.VitPosePreTrainedModel; -var __webpack_exports__VitsModel = __webpack_exports__.VitsModel; -var __webpack_exports__VitsModelOutput = __webpack_exports__.VitsModelOutput; -var __webpack_exports__VitsPreTrainedModel = __webpack_exports__.VitsPreTrainedModel; -var __webpack_exports__VitsTokenizer = __webpack_exports__.VitsTokenizer; -var __webpack_exports__VoxtralForConditionalGeneration = __webpack_exports__.VoxtralForConditionalGeneration; -var __webpack_exports__VoxtralProcessor = __webpack_exports__.VoxtralProcessor; -var __webpack_exports__Wav2Vec2BertForCTC = __webpack_exports__.Wav2Vec2BertForCTC; -var __webpack_exports__Wav2Vec2BertForSequenceClassification = __webpack_exports__.Wav2Vec2BertForSequenceClassification; -var __webpack_exports__Wav2Vec2BertModel = __webpack_exports__.Wav2Vec2BertModel; -var __webpack_exports__Wav2Vec2BertPreTrainedModel = __webpack_exports__.Wav2Vec2BertPreTrainedModel; -var __webpack_exports__Wav2Vec2CTCTokenizer = __webpack_exports__.Wav2Vec2CTCTokenizer; -var __webpack_exports__Wav2Vec2FeatureExtractor = __webpack_exports__.Wav2Vec2FeatureExtractor; -var __webpack_exports__Wav2Vec2ForAudioFrameClassification = __webpack_exports__.Wav2Vec2ForAudioFrameClassification; -var __webpack_exports__Wav2Vec2ForCTC = __webpack_exports__.Wav2Vec2ForCTC; -var __webpack_exports__Wav2Vec2ForSequenceClassification = __webpack_exports__.Wav2Vec2ForSequenceClassification; -var __webpack_exports__Wav2Vec2Model = __webpack_exports__.Wav2Vec2Model; -var __webpack_exports__Wav2Vec2PreTrainedModel = __webpack_exports__.Wav2Vec2PreTrainedModel; -var __webpack_exports__Wav2Vec2Processor = __webpack_exports__.Wav2Vec2Processor; -var __webpack_exports__Wav2Vec2ProcessorWithLM = __webpack_exports__.Wav2Vec2ProcessorWithLM; -var __webpack_exports__WavLMForAudioFrameClassification = __webpack_exports__.WavLMForAudioFrameClassification; -var __webpack_exports__WavLMForCTC = __webpack_exports__.WavLMForCTC; -var __webpack_exports__WavLMForSequenceClassification = __webpack_exports__.WavLMForSequenceClassification; -var __webpack_exports__WavLMForXVector = __webpack_exports__.WavLMForXVector; -var __webpack_exports__WavLMModel = __webpack_exports__.WavLMModel; -var __webpack_exports__WavLMPreTrainedModel = __webpack_exports__.WavLMPreTrainedModel; -var __webpack_exports__WeSpeakerFeatureExtractor = __webpack_exports__.WeSpeakerFeatureExtractor; -var __webpack_exports__WeSpeakerResNetModel = __webpack_exports__.WeSpeakerResNetModel; -var __webpack_exports__WeSpeakerResNetPreTrainedModel = __webpack_exports__.WeSpeakerResNetPreTrainedModel; -var __webpack_exports__WhisperFeatureExtractor = __webpack_exports__.WhisperFeatureExtractor; -var __webpack_exports__WhisperForConditionalGeneration = __webpack_exports__.WhisperForConditionalGeneration; -var __webpack_exports__WhisperModel = __webpack_exports__.WhisperModel; -var __webpack_exports__WhisperPreTrainedModel = __webpack_exports__.WhisperPreTrainedModel; -var __webpack_exports__WhisperProcessor = __webpack_exports__.WhisperProcessor; -var __webpack_exports__WhisperTextStreamer = __webpack_exports__.WhisperTextStreamer; -var __webpack_exports__WhisperTimeStampLogitsProcessor = __webpack_exports__.WhisperTimeStampLogitsProcessor; -var __webpack_exports__WhisperTokenizer = __webpack_exports__.WhisperTokenizer; -var __webpack_exports__XLMForQuestionAnswering = __webpack_exports__.XLMForQuestionAnswering; -var __webpack_exports__XLMForSequenceClassification = __webpack_exports__.XLMForSequenceClassification; -var __webpack_exports__XLMForTokenClassification = __webpack_exports__.XLMForTokenClassification; -var __webpack_exports__XLMModel = __webpack_exports__.XLMModel; -var __webpack_exports__XLMPreTrainedModel = __webpack_exports__.XLMPreTrainedModel; -var __webpack_exports__XLMRobertaForMaskedLM = __webpack_exports__.XLMRobertaForMaskedLM; -var __webpack_exports__XLMRobertaForQuestionAnswering = __webpack_exports__.XLMRobertaForQuestionAnswering; -var __webpack_exports__XLMRobertaForSequenceClassification = __webpack_exports__.XLMRobertaForSequenceClassification; -var __webpack_exports__XLMRobertaForTokenClassification = __webpack_exports__.XLMRobertaForTokenClassification; -var __webpack_exports__XLMRobertaModel = __webpack_exports__.XLMRobertaModel; -var __webpack_exports__XLMRobertaPreTrainedModel = __webpack_exports__.XLMRobertaPreTrainedModel; -var __webpack_exports__XLMRobertaTokenizer = __webpack_exports__.XLMRobertaTokenizer; -var __webpack_exports__XLMTokenizer = __webpack_exports__.XLMTokenizer; -var __webpack_exports__XLMWithLMHeadModel = __webpack_exports__.XLMWithLMHeadModel; -var __webpack_exports__XVectorOutput = __webpack_exports__.XVectorOutput; -var __webpack_exports__YolosFeatureExtractor = __webpack_exports__.YolosFeatureExtractor; -var __webpack_exports__YolosForObjectDetection = __webpack_exports__.YolosForObjectDetection; -var __webpack_exports__YolosImageProcessor = __webpack_exports__.YolosImageProcessor; -var __webpack_exports__YolosModel = __webpack_exports__.YolosModel; -var __webpack_exports__YolosObjectDetectionOutput = __webpack_exports__.YolosObjectDetectionOutput; -var __webpack_exports__YolosPreTrainedModel = __webpack_exports__.YolosPreTrainedModel; -var __webpack_exports__ZeroShotAudioClassificationPipeline = __webpack_exports__.ZeroShotAudioClassificationPipeline; -var __webpack_exports__ZeroShotClassificationPipeline = __webpack_exports__.ZeroShotClassificationPipeline; -var __webpack_exports__ZeroShotImageClassificationPipeline = __webpack_exports__.ZeroShotImageClassificationPipeline; -var __webpack_exports__ZeroShotObjectDetectionPipeline = __webpack_exports__.ZeroShotObjectDetectionPipeline; -var __webpack_exports__bankers_round = __webpack_exports__.bankers_round; -var __webpack_exports__cat = __webpack_exports__.cat; -var __webpack_exports__cos_sim = __webpack_exports__.cos_sim; -var __webpack_exports__dot = __webpack_exports__.dot; -var __webpack_exports__dynamic_time_warping = __webpack_exports__.dynamic_time_warping; -var __webpack_exports__env = __webpack_exports__.env; -var __webpack_exports__full = __webpack_exports__.full; -var __webpack_exports__full_like = __webpack_exports__.full_like; -var __webpack_exports__getCacheShapes = __webpack_exports__.getCacheShapes; -var __webpack_exports__hamming = __webpack_exports__.hamming; -var __webpack_exports__hanning = __webpack_exports__.hanning; -var __webpack_exports__interpolate = __webpack_exports__.interpolate; -var __webpack_exports__interpolate_4d = __webpack_exports__.interpolate_4d; -var __webpack_exports__interpolate_data = __webpack_exports__.interpolate_data; -var __webpack_exports__is_chinese_char = __webpack_exports__.is_chinese_char; -var __webpack_exports__layer_norm = __webpack_exports__.layer_norm; -var __webpack_exports__load_image = __webpack_exports__.load_image; -var __webpack_exports__load_video = __webpack_exports__.load_video; -var __webpack_exports__log_softmax = __webpack_exports__.log_softmax; -var __webpack_exports__magnitude = __webpack_exports__.magnitude; -var __webpack_exports__matmul = __webpack_exports__.matmul; -var __webpack_exports__max = __webpack_exports__.max; -var __webpack_exports__mean = __webpack_exports__.mean; -var __webpack_exports__mean_pooling = __webpack_exports__.mean_pooling; -var __webpack_exports__medianFilter = __webpack_exports__.medianFilter; -var __webpack_exports__mel_filter_bank = __webpack_exports__.mel_filter_bank; -var __webpack_exports__min = __webpack_exports__.min; -var __webpack_exports__ones = __webpack_exports__.ones; -var __webpack_exports__ones_like = __webpack_exports__.ones_like; -var __webpack_exports__permute = __webpack_exports__.permute; -var __webpack_exports__permute_data = __webpack_exports__.permute_data; -var __webpack_exports__pipeline = __webpack_exports__.pipeline; -var __webpack_exports__quantize_embeddings = __webpack_exports__.quantize_embeddings; -var __webpack_exports__rand = __webpack_exports__.rand; -var __webpack_exports__read_audio = __webpack_exports__.read_audio; -var __webpack_exports__rfft = __webpack_exports__.rfft; -var __webpack_exports__round = __webpack_exports__.round; -var __webpack_exports__slice = __webpack_exports__.slice; -var __webpack_exports__softmax = __webpack_exports__.softmax; -var __webpack_exports__spectrogram = __webpack_exports__.spectrogram; -var __webpack_exports__stack = __webpack_exports__.stack; -var __webpack_exports__std_mean = __webpack_exports__.std_mean; -var __webpack_exports__topk = __webpack_exports__.topk; -var __webpack_exports__window_function = __webpack_exports__.window_function; -var __webpack_exports__zeros = __webpack_exports__.zeros; -var __webpack_exports__zeros_like = __webpack_exports__.zeros_like; -export { __webpack_exports__ASTFeatureExtractor as ASTFeatureExtractor, __webpack_exports__ASTForAudioClassification as ASTForAudioClassification, __webpack_exports__ASTModel as ASTModel, __webpack_exports__ASTPreTrainedModel as ASTPreTrainedModel, __webpack_exports__AlbertForMaskedLM as AlbertForMaskedLM, __webpack_exports__AlbertForQuestionAnswering as AlbertForQuestionAnswering, __webpack_exports__AlbertForSequenceClassification as AlbertForSequenceClassification, __webpack_exports__AlbertModel as AlbertModel, __webpack_exports__AlbertPreTrainedModel as AlbertPreTrainedModel, __webpack_exports__AlbertTokenizer as AlbertTokenizer, __webpack_exports__ArceeForCausalLM as ArceeForCausalLM, __webpack_exports__ArceeModel as ArceeModel, __webpack_exports__ArceePreTrainedModel as ArceePreTrainedModel, __webpack_exports__AudioClassificationPipeline as AudioClassificationPipeline, __webpack_exports__AutoConfig as AutoConfig, __webpack_exports__AutoFeatureExtractor as AutoFeatureExtractor, __webpack_exports__AutoImageProcessor as AutoImageProcessor, __webpack_exports__AutoModel as AutoModel, __webpack_exports__AutoModelForAudioClassification as AutoModelForAudioClassification, __webpack_exports__AutoModelForAudioFrameClassification as AutoModelForAudioFrameClassification, __webpack_exports__AutoModelForAudioTextToText as AutoModelForAudioTextToText, __webpack_exports__AutoModelForCTC as AutoModelForCTC, __webpack_exports__AutoModelForCausalLM as AutoModelForCausalLM, __webpack_exports__AutoModelForDepthEstimation as AutoModelForDepthEstimation, __webpack_exports__AutoModelForDocumentQuestionAnswering as AutoModelForDocumentQuestionAnswering, __webpack_exports__AutoModelForImageClassification as AutoModelForImageClassification, __webpack_exports__AutoModelForImageFeatureExtraction as AutoModelForImageFeatureExtraction, __webpack_exports__AutoModelForImageMatting as AutoModelForImageMatting, __webpack_exports__AutoModelForImageSegmentation as AutoModelForImageSegmentation, __webpack_exports__AutoModelForImageTextToText as AutoModelForImageTextToText, __webpack_exports__AutoModelForImageToImage as AutoModelForImageToImage, __webpack_exports__AutoModelForMaskGeneration as AutoModelForMaskGeneration, __webpack_exports__AutoModelForMaskedLM as AutoModelForMaskedLM, __webpack_exports__AutoModelForNormalEstimation as AutoModelForNormalEstimation, __webpack_exports__AutoModelForObjectDetection as AutoModelForObjectDetection, __webpack_exports__AutoModelForPoseEstimation as AutoModelForPoseEstimation, __webpack_exports__AutoModelForQuestionAnswering as AutoModelForQuestionAnswering, __webpack_exports__AutoModelForSemanticSegmentation as AutoModelForSemanticSegmentation, __webpack_exports__AutoModelForSeq2SeqLM as AutoModelForSeq2SeqLM, __webpack_exports__AutoModelForSequenceClassification as AutoModelForSequenceClassification, __webpack_exports__AutoModelForSpeechSeq2Seq as AutoModelForSpeechSeq2Seq, __webpack_exports__AutoModelForTextToSpectrogram as AutoModelForTextToSpectrogram, __webpack_exports__AutoModelForTextToWaveform as AutoModelForTextToWaveform, __webpack_exports__AutoModelForTokenClassification as AutoModelForTokenClassification, __webpack_exports__AutoModelForUniversalSegmentation as AutoModelForUniversalSegmentation, __webpack_exports__AutoModelForVision2Seq as AutoModelForVision2Seq, __webpack_exports__AutoModelForXVector as AutoModelForXVector, __webpack_exports__AutoModelForZeroShotObjectDetection as AutoModelForZeroShotObjectDetection, __webpack_exports__AutoProcessor as AutoProcessor, __webpack_exports__AutoTokenizer as AutoTokenizer, __webpack_exports__AutomaticSpeechRecognitionPipeline as AutomaticSpeechRecognitionPipeline, __webpack_exports__BackgroundRemovalPipeline as BackgroundRemovalPipeline, __webpack_exports__BartForConditionalGeneration as BartForConditionalGeneration, __webpack_exports__BartForSequenceClassification as BartForSequenceClassification, __webpack_exports__BartModel as BartModel, __webpack_exports__BartPretrainedModel as BartPretrainedModel, __webpack_exports__BartTokenizer as BartTokenizer, __webpack_exports__BaseModelOutput as BaseModelOutput, __webpack_exports__BaseStreamer as BaseStreamer, __webpack_exports__BeitFeatureExtractor as BeitFeatureExtractor, __webpack_exports__BeitForImageClassification as BeitForImageClassification, __webpack_exports__BeitModel as BeitModel, __webpack_exports__BeitPreTrainedModel as BeitPreTrainedModel, __webpack_exports__BertForMaskedLM as BertForMaskedLM, __webpack_exports__BertForQuestionAnswering as BertForQuestionAnswering, __webpack_exports__BertForSequenceClassification as BertForSequenceClassification, __webpack_exports__BertForTokenClassification as BertForTokenClassification, __webpack_exports__BertModel as BertModel, __webpack_exports__BertPreTrainedModel as BertPreTrainedModel, __webpack_exports__BertTokenizer as BertTokenizer, __webpack_exports__BitImageProcessor as BitImageProcessor, __webpack_exports__BlenderbotForConditionalGeneration as BlenderbotForConditionalGeneration, __webpack_exports__BlenderbotModel as BlenderbotModel, __webpack_exports__BlenderbotPreTrainedModel as BlenderbotPreTrainedModel, __webpack_exports__BlenderbotSmallForConditionalGeneration as BlenderbotSmallForConditionalGeneration, __webpack_exports__BlenderbotSmallModel as BlenderbotSmallModel, __webpack_exports__BlenderbotSmallPreTrainedModel as BlenderbotSmallPreTrainedModel, __webpack_exports__BlenderbotSmallTokenizer as BlenderbotSmallTokenizer, __webpack_exports__BlenderbotTokenizer as BlenderbotTokenizer, __webpack_exports__BloomForCausalLM as BloomForCausalLM, __webpack_exports__BloomModel as BloomModel, __webpack_exports__BloomPreTrainedModel as BloomPreTrainedModel, __webpack_exports__BloomTokenizer as BloomTokenizer, __webpack_exports__CLIPFeatureExtractor as CLIPFeatureExtractor, __webpack_exports__CLIPImageProcessor as CLIPImageProcessor, __webpack_exports__CLIPModel as CLIPModel, __webpack_exports__CLIPPreTrainedModel as CLIPPreTrainedModel, __webpack_exports__CLIPSegForImageSegmentation as CLIPSegForImageSegmentation, __webpack_exports__CLIPSegModel as CLIPSegModel, __webpack_exports__CLIPSegPreTrainedModel as CLIPSegPreTrainedModel, __webpack_exports__CLIPTextModel as CLIPTextModel, __webpack_exports__CLIPTextModelWithProjection as CLIPTextModelWithProjection, __webpack_exports__CLIPTokenizer as CLIPTokenizer, __webpack_exports__CLIPVisionModel as CLIPVisionModel, __webpack_exports__CLIPVisionModelWithProjection as CLIPVisionModelWithProjection, __webpack_exports__CamembertForMaskedLM as CamembertForMaskedLM, __webpack_exports__CamembertForQuestionAnswering as CamembertForQuestionAnswering, __webpack_exports__CamembertForSequenceClassification as CamembertForSequenceClassification, __webpack_exports__CamembertForTokenClassification as CamembertForTokenClassification, __webpack_exports__CamembertModel as CamembertModel, __webpack_exports__CamembertPreTrainedModel as CamembertPreTrainedModel, __webpack_exports__CamembertTokenizer as CamembertTokenizer, __webpack_exports__CausalLMOutput as CausalLMOutput, __webpack_exports__CausalLMOutputWithPast as CausalLMOutputWithPast, __webpack_exports__ChineseCLIPFeatureExtractor as ChineseCLIPFeatureExtractor, __webpack_exports__ChineseCLIPModel as ChineseCLIPModel, __webpack_exports__ChineseCLIPPreTrainedModel as ChineseCLIPPreTrainedModel, __webpack_exports__ClapAudioModelWithProjection as ClapAudioModelWithProjection, __webpack_exports__ClapFeatureExtractor as ClapFeatureExtractor, __webpack_exports__ClapModel as ClapModel, __webpack_exports__ClapPreTrainedModel as ClapPreTrainedModel, __webpack_exports__ClapTextModelWithProjection as ClapTextModelWithProjection, __webpack_exports__ClassifierFreeGuidanceLogitsProcessor as ClassifierFreeGuidanceLogitsProcessor, __webpack_exports__CodeGenForCausalLM as CodeGenForCausalLM, __webpack_exports__CodeGenModel as CodeGenModel, __webpack_exports__CodeGenPreTrainedModel as CodeGenPreTrainedModel, __webpack_exports__CodeGenTokenizer as CodeGenTokenizer, __webpack_exports__CodeLlamaTokenizer as CodeLlamaTokenizer, __webpack_exports__CohereForCausalLM as CohereForCausalLM, __webpack_exports__CohereModel as CohereModel, __webpack_exports__CoherePreTrainedModel as CoherePreTrainedModel, __webpack_exports__CohereTokenizer as CohereTokenizer, __webpack_exports__ConvBertForMaskedLM as ConvBertForMaskedLM, __webpack_exports__ConvBertForQuestionAnswering as ConvBertForQuestionAnswering, __webpack_exports__ConvBertForSequenceClassification as ConvBertForSequenceClassification, __webpack_exports__ConvBertForTokenClassification as ConvBertForTokenClassification, __webpack_exports__ConvBertModel as ConvBertModel, __webpack_exports__ConvBertPreTrainedModel as ConvBertPreTrainedModel, __webpack_exports__ConvBertTokenizer as ConvBertTokenizer, __webpack_exports__ConvNextFeatureExtractor as ConvNextFeatureExtractor, __webpack_exports__ConvNextForImageClassification as ConvNextForImageClassification, __webpack_exports__ConvNextImageProcessor as ConvNextImageProcessor, __webpack_exports__ConvNextModel as ConvNextModel, __webpack_exports__ConvNextPreTrainedModel as ConvNextPreTrainedModel, __webpack_exports__ConvNextV2ForImageClassification as ConvNextV2ForImageClassification, __webpack_exports__ConvNextV2Model as ConvNextV2Model, __webpack_exports__ConvNextV2PreTrainedModel as ConvNextV2PreTrainedModel, __webpack_exports__DFineForObjectDetection as DFineForObjectDetection, __webpack_exports__DFineModel as DFineModel, __webpack_exports__DFinePreTrainedModel as DFinePreTrainedModel, __webpack_exports__DINOv3ConvNextModel as DINOv3ConvNextModel, __webpack_exports__DINOv3ConvNextPreTrainedModel as DINOv3ConvNextPreTrainedModel, __webpack_exports__DINOv3ViTImageProcessor as DINOv3ViTImageProcessor, __webpack_exports__DINOv3ViTModel as DINOv3ViTModel, __webpack_exports__DINOv3ViTPreTrainedModel as DINOv3ViTPreTrainedModel, __webpack_exports__DPTFeatureExtractor as DPTFeatureExtractor, __webpack_exports__DPTForDepthEstimation as DPTForDepthEstimation, __webpack_exports__DPTImageProcessor as DPTImageProcessor, __webpack_exports__DPTModel as DPTModel, __webpack_exports__DPTPreTrainedModel as DPTPreTrainedModel, __webpack_exports__DacDecoderModel as DacDecoderModel, __webpack_exports__DacDecoderOutput as DacDecoderOutput, __webpack_exports__DacEncoderModel as DacEncoderModel, __webpack_exports__DacEncoderOutput as DacEncoderOutput, __webpack_exports__DacFeatureExtractor as DacFeatureExtractor, __webpack_exports__DacModel as DacModel, __webpack_exports__DacPreTrainedModel as DacPreTrainedModel, __webpack_exports__DataTypeMap as DataTypeMap, __webpack_exports__DebertaForMaskedLM as DebertaForMaskedLM, __webpack_exports__DebertaForQuestionAnswering as DebertaForQuestionAnswering, __webpack_exports__DebertaForSequenceClassification as DebertaForSequenceClassification, __webpack_exports__DebertaForTokenClassification as DebertaForTokenClassification, __webpack_exports__DebertaModel as DebertaModel, __webpack_exports__DebertaPreTrainedModel as DebertaPreTrainedModel, __webpack_exports__DebertaTokenizer as DebertaTokenizer, __webpack_exports__DebertaV2ForMaskedLM as DebertaV2ForMaskedLM, __webpack_exports__DebertaV2ForQuestionAnswering as DebertaV2ForQuestionAnswering, __webpack_exports__DebertaV2ForSequenceClassification as DebertaV2ForSequenceClassification, __webpack_exports__DebertaV2ForTokenClassification as DebertaV2ForTokenClassification, __webpack_exports__DebertaV2Model as DebertaV2Model, __webpack_exports__DebertaV2PreTrainedModel as DebertaV2PreTrainedModel, __webpack_exports__DebertaV2Tokenizer as DebertaV2Tokenizer, __webpack_exports__DecisionTransformerModel as DecisionTransformerModel, __webpack_exports__DecisionTransformerPreTrainedModel as DecisionTransformerPreTrainedModel, __webpack_exports__DeiTFeatureExtractor as DeiTFeatureExtractor, __webpack_exports__DeiTForImageClassification as DeiTForImageClassification, __webpack_exports__DeiTImageProcessor as DeiTImageProcessor, __webpack_exports__DeiTModel as DeiTModel, __webpack_exports__DeiTPreTrainedModel as DeiTPreTrainedModel, __webpack_exports__DepthAnythingForDepthEstimation as DepthAnythingForDepthEstimation, __webpack_exports__DepthAnythingPreTrainedModel as DepthAnythingPreTrainedModel, __webpack_exports__DepthEstimationPipeline as DepthEstimationPipeline, __webpack_exports__DepthProForDepthEstimation as DepthProForDepthEstimation, __webpack_exports__DepthProPreTrainedModel as DepthProPreTrainedModel, __webpack_exports__DetrFeatureExtractor as DetrFeatureExtractor, __webpack_exports__DetrForObjectDetection as DetrForObjectDetection, __webpack_exports__DetrForSegmentation as DetrForSegmentation, __webpack_exports__DetrImageProcessor as DetrImageProcessor, __webpack_exports__DetrModel as DetrModel, __webpack_exports__DetrObjectDetectionOutput as DetrObjectDetectionOutput, __webpack_exports__DetrPreTrainedModel as DetrPreTrainedModel, __webpack_exports__DetrSegmentationOutput as DetrSegmentationOutput, __webpack_exports__Dinov2ForImageClassification as Dinov2ForImageClassification, __webpack_exports__Dinov2Model as Dinov2Model, __webpack_exports__Dinov2PreTrainedModel as Dinov2PreTrainedModel, __webpack_exports__Dinov2WithRegistersForImageClassification as Dinov2WithRegistersForImageClassification, __webpack_exports__Dinov2WithRegistersModel as Dinov2WithRegistersModel, __webpack_exports__Dinov2WithRegistersPreTrainedModel as Dinov2WithRegistersPreTrainedModel, __webpack_exports__DistilBertForMaskedLM as DistilBertForMaskedLM, __webpack_exports__DistilBertForQuestionAnswering as DistilBertForQuestionAnswering, __webpack_exports__DistilBertForSequenceClassification as DistilBertForSequenceClassification, __webpack_exports__DistilBertForTokenClassification as DistilBertForTokenClassification, __webpack_exports__DistilBertModel as DistilBertModel, __webpack_exports__DistilBertPreTrainedModel as DistilBertPreTrainedModel, __webpack_exports__DistilBertTokenizer as DistilBertTokenizer, __webpack_exports__DocumentQuestionAnsweringPipeline as DocumentQuestionAnsweringPipeline, __webpack_exports__DonutFeatureExtractor as DonutFeatureExtractor, __webpack_exports__DonutImageProcessor as DonutImageProcessor, __webpack_exports__DonutSwinModel as DonutSwinModel, __webpack_exports__DonutSwinPreTrainedModel as DonutSwinPreTrainedModel, __webpack_exports__EfficientNetForImageClassification as EfficientNetForImageClassification, __webpack_exports__EfficientNetImageProcessor as EfficientNetImageProcessor, __webpack_exports__EfficientNetModel as EfficientNetModel, __webpack_exports__EfficientNetPreTrainedModel as EfficientNetPreTrainedModel, __webpack_exports__ElectraForMaskedLM as ElectraForMaskedLM, __webpack_exports__ElectraForQuestionAnswering as ElectraForQuestionAnswering, __webpack_exports__ElectraForSequenceClassification as ElectraForSequenceClassification, __webpack_exports__ElectraForTokenClassification as ElectraForTokenClassification, __webpack_exports__ElectraModel as ElectraModel, __webpack_exports__ElectraPreTrainedModel as ElectraPreTrainedModel, __webpack_exports__ElectraTokenizer as ElectraTokenizer, __webpack_exports__EncodecFeatureExtractor as EncodecFeatureExtractor, __webpack_exports__EosTokenCriteria as EosTokenCriteria, __webpack_exports__Ernie4_5_ForCausalLM as Ernie4_5_ForCausalLM, __webpack_exports__Ernie4_5_Model as Ernie4_5_Model, __webpack_exports__Ernie4_5_PretrainedModel as Ernie4_5_PretrainedModel, __webpack_exports__Ernie4_5_Tokenizer as Ernie4_5_Tokenizer, __webpack_exports__EsmForMaskedLM as EsmForMaskedLM, __webpack_exports__EsmForSequenceClassification as EsmForSequenceClassification, __webpack_exports__EsmForTokenClassification as EsmForTokenClassification, __webpack_exports__EsmModel as EsmModel, __webpack_exports__EsmPreTrainedModel as EsmPreTrainedModel, __webpack_exports__EsmTokenizer as EsmTokenizer, __webpack_exports__ExaoneForCausalLM as ExaoneForCausalLM, __webpack_exports__ExaoneModel as ExaoneModel, __webpack_exports__ExaonePreTrainedModel as ExaonePreTrainedModel, __webpack_exports__FFT as FFT, __webpack_exports__FalconForCausalLM as FalconForCausalLM, __webpack_exports__FalconModel as FalconModel, __webpack_exports__FalconPreTrainedModel as FalconPreTrainedModel, __webpack_exports__FalconTokenizer as FalconTokenizer, __webpack_exports__FastViTForImageClassification as FastViTForImageClassification, __webpack_exports__FastViTModel as FastViTModel, __webpack_exports__FastViTPreTrainedModel as FastViTPreTrainedModel, __webpack_exports__FeatureExtractionPipeline as FeatureExtractionPipeline, __webpack_exports__FeatureExtractor as FeatureExtractor, __webpack_exports__FillMaskPipeline as FillMaskPipeline, __webpack_exports__Florence2ForConditionalGeneration as Florence2ForConditionalGeneration, __webpack_exports__Florence2PreTrainedModel as Florence2PreTrainedModel, __webpack_exports__Florence2Processor as Florence2Processor, __webpack_exports__ForcedBOSTokenLogitsProcessor as ForcedBOSTokenLogitsProcessor, __webpack_exports__ForcedEOSTokenLogitsProcessor as ForcedEOSTokenLogitsProcessor, __webpack_exports__GLPNFeatureExtractor as GLPNFeatureExtractor, __webpack_exports__GLPNForDepthEstimation as GLPNForDepthEstimation, __webpack_exports__GLPNModel as GLPNModel, __webpack_exports__GLPNPreTrainedModel as GLPNPreTrainedModel, __webpack_exports__GPT2LMHeadModel as GPT2LMHeadModel, __webpack_exports__GPT2Model as GPT2Model, __webpack_exports__GPT2PreTrainedModel as GPT2PreTrainedModel, __webpack_exports__GPT2Tokenizer as GPT2Tokenizer, __webpack_exports__GPTBigCodeForCausalLM as GPTBigCodeForCausalLM, __webpack_exports__GPTBigCodeModel as GPTBigCodeModel, __webpack_exports__GPTBigCodePreTrainedModel as GPTBigCodePreTrainedModel, __webpack_exports__GPTJForCausalLM as GPTJForCausalLM, __webpack_exports__GPTJModel as GPTJModel, __webpack_exports__GPTJPreTrainedModel as GPTJPreTrainedModel, __webpack_exports__GPTNeoForCausalLM as GPTNeoForCausalLM, __webpack_exports__GPTNeoModel as GPTNeoModel, __webpack_exports__GPTNeoPreTrainedModel as GPTNeoPreTrainedModel, __webpack_exports__GPTNeoXForCausalLM as GPTNeoXForCausalLM, __webpack_exports__GPTNeoXModel as GPTNeoXModel, __webpack_exports__GPTNeoXPreTrainedModel as GPTNeoXPreTrainedModel, __webpack_exports__GPTNeoXTokenizer as GPTNeoXTokenizer, __webpack_exports__Gemma2ForCausalLM as Gemma2ForCausalLM, __webpack_exports__Gemma2Model as Gemma2Model, __webpack_exports__Gemma2PreTrainedModel as Gemma2PreTrainedModel, __webpack_exports__Gemma3ForCausalLM as Gemma3ForCausalLM, __webpack_exports__Gemma3Model as Gemma3Model, __webpack_exports__Gemma3PreTrainedModel as Gemma3PreTrainedModel, __webpack_exports__Gemma3nAudioFeatureExtractor as Gemma3nAudioFeatureExtractor, __webpack_exports__Gemma3nForConditionalGeneration as Gemma3nForConditionalGeneration, __webpack_exports__Gemma3nPreTrainedModel as Gemma3nPreTrainedModel, __webpack_exports__Gemma3nProcessor as Gemma3nProcessor, __webpack_exports__GemmaForCausalLM as GemmaForCausalLM, __webpack_exports__GemmaModel as GemmaModel, __webpack_exports__GemmaPreTrainedModel as GemmaPreTrainedModel, __webpack_exports__GemmaTokenizer as GemmaTokenizer, __webpack_exports__GlmForCausalLM as GlmForCausalLM, __webpack_exports__GlmModel as GlmModel, __webpack_exports__GlmPreTrainedModel as GlmPreTrainedModel, __webpack_exports__GraniteForCausalLM as GraniteForCausalLM, __webpack_exports__GraniteModel as GraniteModel, __webpack_exports__GranitePreTrainedModel as GranitePreTrainedModel, __webpack_exports__Grok1Tokenizer as Grok1Tokenizer, __webpack_exports__GroundingDinoForObjectDetection as GroundingDinoForObjectDetection, __webpack_exports__GroundingDinoImageProcessor as GroundingDinoImageProcessor, __webpack_exports__GroundingDinoPreTrainedModel as GroundingDinoPreTrainedModel, __webpack_exports__GroundingDinoProcessor as GroundingDinoProcessor, __webpack_exports__GroupViTModel as GroupViTModel, __webpack_exports__GroupViTPreTrainedModel as GroupViTPreTrainedModel, __webpack_exports__HeliumForCausalLM as HeliumForCausalLM, __webpack_exports__HeliumModel as HeliumModel, __webpack_exports__HeliumPreTrainedModel as HeliumPreTrainedModel, __webpack_exports__HerbertTokenizer as HerbertTokenizer, __webpack_exports__HieraForImageClassification as HieraForImageClassification, __webpack_exports__HieraModel as HieraModel, __webpack_exports__HieraPreTrainedModel as HieraPreTrainedModel, __webpack_exports__HubertForCTC as HubertForCTC, __webpack_exports__HubertForSequenceClassification as HubertForSequenceClassification, __webpack_exports__HubertModel as HubertModel, __webpack_exports__HubertPreTrainedModel as HubertPreTrainedModel, __webpack_exports__IJepaForImageClassification as IJepaForImageClassification, __webpack_exports__IJepaModel as IJepaModel, __webpack_exports__IJepaPreTrainedModel as IJepaPreTrainedModel, __webpack_exports__Idefics3ForConditionalGeneration as Idefics3ForConditionalGeneration, __webpack_exports__Idefics3ImageProcessor as Idefics3ImageProcessor, __webpack_exports__Idefics3PreTrainedModel as Idefics3PreTrainedModel, __webpack_exports__Idefics3Processor as Idefics3Processor, __webpack_exports__ImageClassificationPipeline as ImageClassificationPipeline, __webpack_exports__ImageFeatureExtractionPipeline as ImageFeatureExtractionPipeline, __webpack_exports__ImageFeatureExtractor as ImageFeatureExtractor, __webpack_exports__ImageMattingOutput as ImageMattingOutput, __webpack_exports__ImageProcessor as ImageProcessor, __webpack_exports__ImageSegmentationPipeline as ImageSegmentationPipeline, __webpack_exports__ImageToImagePipeline as ImageToImagePipeline, __webpack_exports__ImageToTextPipeline as ImageToTextPipeline, __webpack_exports__InterruptableStoppingCriteria as InterruptableStoppingCriteria, __webpack_exports__JAISLMHeadModel as JAISLMHeadModel, __webpack_exports__JAISModel as JAISModel, __webpack_exports__JAISPreTrainedModel as JAISPreTrainedModel, __webpack_exports__JinaCLIPImageProcessor as JinaCLIPImageProcessor, __webpack_exports__JinaCLIPModel as JinaCLIPModel, __webpack_exports__JinaCLIPPreTrainedModel as JinaCLIPPreTrainedModel, __webpack_exports__JinaCLIPProcessor as JinaCLIPProcessor, __webpack_exports__JinaCLIPTextModel as JinaCLIPTextModel, __webpack_exports__JinaCLIPVisionModel as JinaCLIPVisionModel, __webpack_exports__Lfm2ForCausalLM as Lfm2ForCausalLM, __webpack_exports__Lfm2Model as Lfm2Model, __webpack_exports__Lfm2PreTrainedModel as Lfm2PreTrainedModel, __webpack_exports__LiteWhisperForConditionalGeneration as LiteWhisperForConditionalGeneration, __webpack_exports__LlamaForCausalLM as LlamaForCausalLM, __webpack_exports__LlamaModel as LlamaModel, __webpack_exports__LlamaPreTrainedModel as LlamaPreTrainedModel, __webpack_exports__LlamaTokenizer as LlamaTokenizer, __webpack_exports__LlavaForConditionalGeneration as LlavaForConditionalGeneration, __webpack_exports__LlavaOnevisionForConditionalGeneration as LlavaOnevisionForConditionalGeneration, __webpack_exports__LlavaOnevisionImageProcessor as LlavaOnevisionImageProcessor, __webpack_exports__LlavaPreTrainedModel as LlavaPreTrainedModel, __webpack_exports__LlavaProcessor as LlavaProcessor, __webpack_exports__LlavaQwen2ForCausalLM as LlavaQwen2ForCausalLM, __webpack_exports__LogitsProcessor as LogitsProcessor, __webpack_exports__LogitsProcessorList as LogitsProcessorList, __webpack_exports__LogitsWarper as LogitsWarper, __webpack_exports__LongT5ForConditionalGeneration as LongT5ForConditionalGeneration, __webpack_exports__LongT5Model as LongT5Model, __webpack_exports__LongT5PreTrainedModel as LongT5PreTrainedModel, __webpack_exports__M2M100ForConditionalGeneration as M2M100ForConditionalGeneration, __webpack_exports__M2M100Model as M2M100Model, __webpack_exports__M2M100PreTrainedModel as M2M100PreTrainedModel, __webpack_exports__M2M100Tokenizer as M2M100Tokenizer, __webpack_exports__MBart50Tokenizer as MBart50Tokenizer, __webpack_exports__MBartForCausalLM as MBartForCausalLM, __webpack_exports__MBartForConditionalGeneration as MBartForConditionalGeneration, __webpack_exports__MBartForSequenceClassification as MBartForSequenceClassification, __webpack_exports__MBartModel as MBartModel, __webpack_exports__MBartPreTrainedModel as MBartPreTrainedModel, __webpack_exports__MBartTokenizer as MBartTokenizer, __webpack_exports__MPNetForMaskedLM as MPNetForMaskedLM, __webpack_exports__MPNetForQuestionAnswering as MPNetForQuestionAnswering, __webpack_exports__MPNetForSequenceClassification as MPNetForSequenceClassification, __webpack_exports__MPNetForTokenClassification as MPNetForTokenClassification, __webpack_exports__MPNetModel as MPNetModel, __webpack_exports__MPNetPreTrainedModel as MPNetPreTrainedModel, __webpack_exports__MPNetTokenizer as MPNetTokenizer, __webpack_exports__MT5ForConditionalGeneration as MT5ForConditionalGeneration, __webpack_exports__MT5Model as MT5Model, __webpack_exports__MT5PreTrainedModel as MT5PreTrainedModel, __webpack_exports__MarianMTModel as MarianMTModel, __webpack_exports__MarianModel as MarianModel, __webpack_exports__MarianPreTrainedModel as MarianPreTrainedModel, __webpack_exports__MarianTokenizer as MarianTokenizer, __webpack_exports__Mask2FormerImageProcessor as Mask2FormerImageProcessor, __webpack_exports__MaskFormerFeatureExtractor as MaskFormerFeatureExtractor, __webpack_exports__MaskFormerForInstanceSegmentation as MaskFormerForInstanceSegmentation, __webpack_exports__MaskFormerImageProcessor as MaskFormerImageProcessor, __webpack_exports__MaskFormerModel as MaskFormerModel, __webpack_exports__MaskFormerPreTrainedModel as MaskFormerPreTrainedModel, __webpack_exports__MaskedLMOutput as MaskedLMOutput, __webpack_exports__MaxLengthCriteria as MaxLengthCriteria, __webpack_exports__Metric3DForDepthEstimation as Metric3DForDepthEstimation, __webpack_exports__Metric3DPreTrainedModel as Metric3DPreTrainedModel, __webpack_exports__Metric3Dv2ForDepthEstimation as Metric3Dv2ForDepthEstimation, __webpack_exports__Metric3Dv2PreTrainedModel as Metric3Dv2PreTrainedModel, __webpack_exports__MgpstrForSceneTextRecognition as MgpstrForSceneTextRecognition, __webpack_exports__MgpstrModelOutput as MgpstrModelOutput, __webpack_exports__MgpstrPreTrainedModel as MgpstrPreTrainedModel, __webpack_exports__MgpstrProcessor as MgpstrProcessor, __webpack_exports__MgpstrTokenizer as MgpstrTokenizer, __webpack_exports__MimiDecoderModel as MimiDecoderModel, __webpack_exports__MimiDecoderOutput as MimiDecoderOutput, __webpack_exports__MimiEncoderModel as MimiEncoderModel, __webpack_exports__MimiEncoderOutput as MimiEncoderOutput, __webpack_exports__MimiModel as MimiModel, __webpack_exports__MimiPreTrainedModel as MimiPreTrainedModel, __webpack_exports__MinLengthLogitsProcessor as MinLengthLogitsProcessor, __webpack_exports__MinNewTokensLengthLogitsProcessor as MinNewTokensLengthLogitsProcessor, __webpack_exports__MistralForCausalLM as MistralForCausalLM, __webpack_exports__MistralModel as MistralModel, __webpack_exports__MistralPreTrainedModel as MistralPreTrainedModel, __webpack_exports__MobileBertForMaskedLM as MobileBertForMaskedLM, __webpack_exports__MobileBertForQuestionAnswering as MobileBertForQuestionAnswering, __webpack_exports__MobileBertForSequenceClassification as MobileBertForSequenceClassification, __webpack_exports__MobileBertModel as MobileBertModel, __webpack_exports__MobileBertPreTrainedModel as MobileBertPreTrainedModel, __webpack_exports__MobileBertTokenizer as MobileBertTokenizer, __webpack_exports__MobileLLMForCausalLM as MobileLLMForCausalLM, __webpack_exports__MobileLLMModel as MobileLLMModel, __webpack_exports__MobileLLMPreTrainedModel as MobileLLMPreTrainedModel, __webpack_exports__MobileNetV1FeatureExtractor as MobileNetV1FeatureExtractor, __webpack_exports__MobileNetV1ForImageClassification as MobileNetV1ForImageClassification, __webpack_exports__MobileNetV1ForSemanticSegmentation as MobileNetV1ForSemanticSegmentation, __webpack_exports__MobileNetV1ImageProcessor as MobileNetV1ImageProcessor, __webpack_exports__MobileNetV1Model as MobileNetV1Model, __webpack_exports__MobileNetV1PreTrainedModel as MobileNetV1PreTrainedModel, __webpack_exports__MobileNetV2FeatureExtractor as MobileNetV2FeatureExtractor, __webpack_exports__MobileNetV2ForImageClassification as MobileNetV2ForImageClassification, __webpack_exports__MobileNetV2ForSemanticSegmentation as MobileNetV2ForSemanticSegmentation, __webpack_exports__MobileNetV2ImageProcessor as MobileNetV2ImageProcessor, __webpack_exports__MobileNetV2Model as MobileNetV2Model, __webpack_exports__MobileNetV2PreTrainedModel as MobileNetV2PreTrainedModel, __webpack_exports__MobileNetV3FeatureExtractor as MobileNetV3FeatureExtractor, __webpack_exports__MobileNetV3ForImageClassification as MobileNetV3ForImageClassification, __webpack_exports__MobileNetV3ForSemanticSegmentation as MobileNetV3ForSemanticSegmentation, __webpack_exports__MobileNetV3ImageProcessor as MobileNetV3ImageProcessor, __webpack_exports__MobileNetV3Model as MobileNetV3Model, __webpack_exports__MobileNetV3PreTrainedModel as MobileNetV3PreTrainedModel, __webpack_exports__MobileNetV4FeatureExtractor as MobileNetV4FeatureExtractor, __webpack_exports__MobileNetV4ForImageClassification as MobileNetV4ForImageClassification, __webpack_exports__MobileNetV4ForSemanticSegmentation as MobileNetV4ForSemanticSegmentation, __webpack_exports__MobileNetV4ImageProcessor as MobileNetV4ImageProcessor, __webpack_exports__MobileNetV4Model as MobileNetV4Model, __webpack_exports__MobileNetV4PreTrainedModel as MobileNetV4PreTrainedModel, __webpack_exports__MobileViTFeatureExtractor as MobileViTFeatureExtractor, __webpack_exports__MobileViTForImageClassification as MobileViTForImageClassification, __webpack_exports__MobileViTImageProcessor as MobileViTImageProcessor, __webpack_exports__MobileViTModel as MobileViTModel, __webpack_exports__MobileViTPreTrainedModel as MobileViTPreTrainedModel, __webpack_exports__MobileViTV2ForImageClassification as MobileViTV2ForImageClassification, __webpack_exports__MobileViTV2Model as MobileViTV2Model, __webpack_exports__MobileViTV2PreTrainedModel as MobileViTV2PreTrainedModel, __webpack_exports__ModelOutput as ModelOutput, __webpack_exports__ModernBertDecoderForCausalLM as ModernBertDecoderForCausalLM, __webpack_exports__ModernBertDecoderModel as ModernBertDecoderModel, __webpack_exports__ModernBertDecoderPreTrainedModel as ModernBertDecoderPreTrainedModel, __webpack_exports__ModernBertForMaskedLM as ModernBertForMaskedLM, __webpack_exports__ModernBertForSequenceClassification as ModernBertForSequenceClassification, __webpack_exports__ModernBertForTokenClassification as ModernBertForTokenClassification, __webpack_exports__ModernBertModel as ModernBertModel, __webpack_exports__ModernBertPreTrainedModel as ModernBertPreTrainedModel, __webpack_exports__Moondream1ForConditionalGeneration as Moondream1ForConditionalGeneration, __webpack_exports__MoonshineFeatureExtractor as MoonshineFeatureExtractor, __webpack_exports__MoonshineForConditionalGeneration as MoonshineForConditionalGeneration, __webpack_exports__MoonshineModel as MoonshineModel, __webpack_exports__MoonshinePreTrainedModel as MoonshinePreTrainedModel, __webpack_exports__MoonshineProcessor as MoonshineProcessor, __webpack_exports__MptForCausalLM as MptForCausalLM, __webpack_exports__MptModel as MptModel, __webpack_exports__MptPreTrainedModel as MptPreTrainedModel, __webpack_exports__MultiModalityCausalLM as MultiModalityCausalLM, __webpack_exports__MultiModalityPreTrainedModel as MultiModalityPreTrainedModel, __webpack_exports__MusicgenForCausalLM as MusicgenForCausalLM, __webpack_exports__MusicgenForConditionalGeneration as MusicgenForConditionalGeneration, __webpack_exports__MusicgenModel as MusicgenModel, __webpack_exports__MusicgenPreTrainedModel as MusicgenPreTrainedModel, __webpack_exports__NeoBertForMaskedLM as NeoBertForMaskedLM, __webpack_exports__NeoBertForQuestionAnswering as NeoBertForQuestionAnswering, __webpack_exports__NeoBertForSequenceClassification as NeoBertForSequenceClassification, __webpack_exports__NeoBertForTokenClassification as NeoBertForTokenClassification, __webpack_exports__NeoBertModel as NeoBertModel, __webpack_exports__NeoBertPreTrainedModel as NeoBertPreTrainedModel, __webpack_exports__NllbTokenizer as NllbTokenizer, __webpack_exports__NoBadWordsLogitsProcessor as NoBadWordsLogitsProcessor, __webpack_exports__NoRepeatNGramLogitsProcessor as NoRepeatNGramLogitsProcessor, __webpack_exports__NomicBertModel as NomicBertModel, __webpack_exports__NomicBertPreTrainedModel as NomicBertPreTrainedModel, __webpack_exports__NougatImageProcessor as NougatImageProcessor, __webpack_exports__NougatTokenizer as NougatTokenizer, __webpack_exports__OPTForCausalLM as OPTForCausalLM, __webpack_exports__OPTModel as OPTModel, __webpack_exports__OPTPreTrainedModel as OPTPreTrainedModel, __webpack_exports__ObjectDetectionPipeline as ObjectDetectionPipeline, __webpack_exports__Olmo2ForCausalLM as Olmo2ForCausalLM, __webpack_exports__Olmo2Model as Olmo2Model, __webpack_exports__Olmo2PreTrainedModel as Olmo2PreTrainedModel, __webpack_exports__OlmoForCausalLM as OlmoForCausalLM, __webpack_exports__OlmoModel as OlmoModel, __webpack_exports__OlmoPreTrainedModel as OlmoPreTrainedModel, __webpack_exports__OpenELMForCausalLM as OpenELMForCausalLM, __webpack_exports__OpenELMModel as OpenELMModel, __webpack_exports__OpenELMPreTrainedModel as OpenELMPreTrainedModel, __webpack_exports__OwlViTFeatureExtractor as OwlViTFeatureExtractor, __webpack_exports__OwlViTForObjectDetection as OwlViTForObjectDetection, __webpack_exports__OwlViTImageProcessor as OwlViTImageProcessor, __webpack_exports__OwlViTModel as OwlViTModel, __webpack_exports__OwlViTPreTrainedModel as OwlViTPreTrainedModel, __webpack_exports__OwlViTProcessor as OwlViTProcessor, __webpack_exports__Owlv2ForObjectDetection as Owlv2ForObjectDetection, __webpack_exports__Owlv2ImageProcessor as Owlv2ImageProcessor, __webpack_exports__Owlv2Model as Owlv2Model, __webpack_exports__Owlv2PreTrainedModel as Owlv2PreTrainedModel, __webpack_exports__PaliGemmaForConditionalGeneration as PaliGemmaForConditionalGeneration, __webpack_exports__PaliGemmaPreTrainedModel as PaliGemmaPreTrainedModel, __webpack_exports__PaliGemmaProcessor as PaliGemmaProcessor, __webpack_exports__PatchTSMixerForPrediction as PatchTSMixerForPrediction, __webpack_exports__PatchTSMixerModel as PatchTSMixerModel, __webpack_exports__PatchTSMixerPreTrainedModel as PatchTSMixerPreTrainedModel, __webpack_exports__PatchTSTForPrediction as PatchTSTForPrediction, __webpack_exports__PatchTSTModel as PatchTSTModel, __webpack_exports__PatchTSTPreTrainedModel as PatchTSTPreTrainedModel, __webpack_exports__Phi3ForCausalLM as Phi3ForCausalLM, __webpack_exports__Phi3Model as Phi3Model, __webpack_exports__Phi3PreTrainedModel as Phi3PreTrainedModel, __webpack_exports__Phi3VForCausalLM as Phi3VForCausalLM, __webpack_exports__Phi3VImageProcessor as Phi3VImageProcessor, __webpack_exports__Phi3VPreTrainedModel as Phi3VPreTrainedModel, __webpack_exports__Phi3VProcessor as Phi3VProcessor, __webpack_exports__PhiForCausalLM as PhiForCausalLM, __webpack_exports__PhiModel as PhiModel, __webpack_exports__PhiPreTrainedModel as PhiPreTrainedModel, __webpack_exports__Pipeline as Pipeline, __webpack_exports__PreTrainedModel as PreTrainedModel, __webpack_exports__PreTrainedTokenizer as PreTrainedTokenizer, __webpack_exports__PretrainedConfig as PretrainedConfig, __webpack_exports__PretrainedMixin as PretrainedMixin, __webpack_exports__Processor as Processor, __webpack_exports__PvtForImageClassification as PvtForImageClassification, __webpack_exports__PvtImageProcessor as PvtImageProcessor, __webpack_exports__PvtModel as PvtModel, __webpack_exports__PvtPreTrainedModel as PvtPreTrainedModel, __webpack_exports__PyAnnoteFeatureExtractor as PyAnnoteFeatureExtractor, __webpack_exports__PyAnnoteForAudioFrameClassification as PyAnnoteForAudioFrameClassification, __webpack_exports__PyAnnoteModel as PyAnnoteModel, __webpack_exports__PyAnnotePreTrainedModel as PyAnnotePreTrainedModel, __webpack_exports__PyAnnoteProcessor as PyAnnoteProcessor, __webpack_exports__QuestionAnsweringModelOutput as QuestionAnsweringModelOutput, __webpack_exports__QuestionAnsweringPipeline as QuestionAnsweringPipeline, __webpack_exports__Qwen2ForCausalLM as Qwen2ForCausalLM, __webpack_exports__Qwen2Model as Qwen2Model, __webpack_exports__Qwen2PreTrainedModel as Qwen2PreTrainedModel, __webpack_exports__Qwen2Tokenizer as Qwen2Tokenizer, __webpack_exports__Qwen2VLForConditionalGeneration as Qwen2VLForConditionalGeneration, __webpack_exports__Qwen2VLImageProcessor as Qwen2VLImageProcessor, __webpack_exports__Qwen2VLPreTrainedModel as Qwen2VLPreTrainedModel, __webpack_exports__Qwen2VLProcessor as Qwen2VLProcessor, __webpack_exports__Qwen3ForCausalLM as Qwen3ForCausalLM, __webpack_exports__Qwen3Model as Qwen3Model, __webpack_exports__Qwen3PreTrainedModel as Qwen3PreTrainedModel, __webpack_exports__RFDetrForObjectDetection as RFDetrForObjectDetection, __webpack_exports__RFDetrModel as RFDetrModel, __webpack_exports__RFDetrObjectDetectionOutput as RFDetrObjectDetectionOutput, __webpack_exports__RFDetrPreTrainedModel as RFDetrPreTrainedModel, __webpack_exports__RTDetrForObjectDetection as RTDetrForObjectDetection, __webpack_exports__RTDetrImageProcessor as RTDetrImageProcessor, __webpack_exports__RTDetrModel as RTDetrModel, __webpack_exports__RTDetrObjectDetectionOutput as RTDetrObjectDetectionOutput, __webpack_exports__RTDetrPreTrainedModel as RTDetrPreTrainedModel, __webpack_exports__RTDetrV2ForObjectDetection as RTDetrV2ForObjectDetection, __webpack_exports__RTDetrV2Model as RTDetrV2Model, __webpack_exports__RTDetrV2ObjectDetectionOutput as RTDetrV2ObjectDetectionOutput, __webpack_exports__RTDetrV2PreTrainedModel as RTDetrV2PreTrainedModel, __webpack_exports__RawAudio as RawAudio, __webpack_exports__RawImage as RawImage, __webpack_exports__RawVideo as RawVideo, __webpack_exports__RawVideoFrame as RawVideoFrame, __webpack_exports__RepetitionPenaltyLogitsProcessor as RepetitionPenaltyLogitsProcessor, __webpack_exports__ResNetForImageClassification as ResNetForImageClassification, __webpack_exports__ResNetModel as ResNetModel, __webpack_exports__ResNetPreTrainedModel as ResNetPreTrainedModel, __webpack_exports__RoFormerForMaskedLM as RoFormerForMaskedLM, __webpack_exports__RoFormerForQuestionAnswering as RoFormerForQuestionAnswering, __webpack_exports__RoFormerForSequenceClassification as RoFormerForSequenceClassification, __webpack_exports__RoFormerForTokenClassification as RoFormerForTokenClassification, __webpack_exports__RoFormerModel as RoFormerModel, __webpack_exports__RoFormerPreTrainedModel as RoFormerPreTrainedModel, __webpack_exports__RoFormerTokenizer as RoFormerTokenizer, __webpack_exports__RobertaForMaskedLM as RobertaForMaskedLM, __webpack_exports__RobertaForQuestionAnswering as RobertaForQuestionAnswering, __webpack_exports__RobertaForSequenceClassification as RobertaForSequenceClassification, __webpack_exports__RobertaForTokenClassification as RobertaForTokenClassification, __webpack_exports__RobertaModel as RobertaModel, __webpack_exports__RobertaPreTrainedModel as RobertaPreTrainedModel, __webpack_exports__RobertaTokenizer as RobertaTokenizer, __webpack_exports__SamImageProcessor as SamImageProcessor, __webpack_exports__SamImageSegmentationOutput as SamImageSegmentationOutput, __webpack_exports__SamModel as SamModel, __webpack_exports__SamPreTrainedModel as SamPreTrainedModel, __webpack_exports__SamProcessor as SamProcessor, __webpack_exports__SapiensForDepthEstimation as SapiensForDepthEstimation, __webpack_exports__SapiensForNormalEstimation as SapiensForNormalEstimation, __webpack_exports__SapiensForSemanticSegmentation as SapiensForSemanticSegmentation, __webpack_exports__SapiensPreTrainedModel as SapiensPreTrainedModel, __webpack_exports__SeamlessM4TFeatureExtractor as SeamlessM4TFeatureExtractor, __webpack_exports__SegformerFeatureExtractor as SegformerFeatureExtractor, __webpack_exports__SegformerForImageClassification as SegformerForImageClassification, __webpack_exports__SegformerForSemanticSegmentation as SegformerForSemanticSegmentation, __webpack_exports__SegformerImageProcessor as SegformerImageProcessor, __webpack_exports__SegformerModel as SegformerModel, __webpack_exports__SegformerPreTrainedModel as SegformerPreTrainedModel, __webpack_exports__Seq2SeqLMOutput as Seq2SeqLMOutput, __webpack_exports__SequenceClassifierOutput as SequenceClassifierOutput, __webpack_exports__SiglipImageProcessor as SiglipImageProcessor, __webpack_exports__SiglipModel as SiglipModel, __webpack_exports__SiglipPreTrainedModel as SiglipPreTrainedModel, __webpack_exports__SiglipTextModel as SiglipTextModel, __webpack_exports__SiglipTokenizer as SiglipTokenizer, __webpack_exports__SiglipVisionModel as SiglipVisionModel, __webpack_exports__SmolLM3ForCausalLM as SmolLM3ForCausalLM, __webpack_exports__SmolLM3Model as SmolLM3Model, __webpack_exports__SmolLM3PreTrainedModel as SmolLM3PreTrainedModel, __webpack_exports__SmolVLMForConditionalGeneration as SmolVLMForConditionalGeneration, __webpack_exports__SmolVLMImageProcessor as SmolVLMImageProcessor, __webpack_exports__SmolVLMProcessor as SmolVLMProcessor, __webpack_exports__SnacDecoderModel as SnacDecoderModel, __webpack_exports__SnacEncoderModel as SnacEncoderModel, __webpack_exports__SnacFeatureExtractor as SnacFeatureExtractor, __webpack_exports__SnacModel as SnacModel, __webpack_exports__SnacPreTrainedModel as SnacPreTrainedModel, __webpack_exports__SpeechT5FeatureExtractor as SpeechT5FeatureExtractor, __webpack_exports__SpeechT5ForSpeechToText as SpeechT5ForSpeechToText, __webpack_exports__SpeechT5ForTextToSpeech as SpeechT5ForTextToSpeech, __webpack_exports__SpeechT5HifiGan as SpeechT5HifiGan, __webpack_exports__SpeechT5Model as SpeechT5Model, __webpack_exports__SpeechT5PreTrainedModel as SpeechT5PreTrainedModel, __webpack_exports__SpeechT5Processor as SpeechT5Processor, __webpack_exports__SpeechT5Tokenizer as SpeechT5Tokenizer, __webpack_exports__SqueezeBertForMaskedLM as SqueezeBertForMaskedLM, __webpack_exports__SqueezeBertForQuestionAnswering as SqueezeBertForQuestionAnswering, __webpack_exports__SqueezeBertForSequenceClassification as SqueezeBertForSequenceClassification, __webpack_exports__SqueezeBertModel as SqueezeBertModel, __webpack_exports__SqueezeBertPreTrainedModel as SqueezeBertPreTrainedModel, __webpack_exports__SqueezeBertTokenizer as SqueezeBertTokenizer, __webpack_exports__StableLmForCausalLM as StableLmForCausalLM, __webpack_exports__StableLmModel as StableLmModel, __webpack_exports__StableLmPreTrainedModel as StableLmPreTrainedModel, __webpack_exports__Starcoder2ForCausalLM as Starcoder2ForCausalLM, __webpack_exports__Starcoder2Model as Starcoder2Model, __webpack_exports__Starcoder2PreTrainedModel as Starcoder2PreTrainedModel, __webpack_exports__StoppingCriteria as StoppingCriteria, __webpack_exports__StoppingCriteriaList as StoppingCriteriaList, __webpack_exports__StyleTextToSpeech2Model as StyleTextToSpeech2Model, __webpack_exports__StyleTextToSpeech2PreTrainedModel as StyleTextToSpeech2PreTrainedModel, __webpack_exports__SummarizationPipeline as SummarizationPipeline, __webpack_exports__SuppressTokensAtBeginLogitsProcessor as SuppressTokensAtBeginLogitsProcessor, __webpack_exports__Swin2SRForImageSuperResolution as Swin2SRForImageSuperResolution, __webpack_exports__Swin2SRImageProcessor as Swin2SRImageProcessor, __webpack_exports__Swin2SRModel as Swin2SRModel, __webpack_exports__Swin2SRPreTrainedModel as Swin2SRPreTrainedModel, __webpack_exports__SwinForImageClassification as SwinForImageClassification, __webpack_exports__SwinForSemanticSegmentation as SwinForSemanticSegmentation, __webpack_exports__SwinModel as SwinModel, __webpack_exports__SwinPreTrainedModel as SwinPreTrainedModel, __webpack_exports__T5ForConditionalGeneration as T5ForConditionalGeneration, __webpack_exports__T5Model as T5Model, __webpack_exports__T5PreTrainedModel as T5PreTrainedModel, __webpack_exports__T5Tokenizer as T5Tokenizer, __webpack_exports__TableTransformerForObjectDetection as TableTransformerForObjectDetection, __webpack_exports__TableTransformerModel as TableTransformerModel, __webpack_exports__TableTransformerObjectDetectionOutput as TableTransformerObjectDetectionOutput, __webpack_exports__TableTransformerPreTrainedModel as TableTransformerPreTrainedModel, __webpack_exports__TemperatureLogitsWarper as TemperatureLogitsWarper, __webpack_exports__Tensor as Tensor, __webpack_exports__Text2TextGenerationPipeline as Text2TextGenerationPipeline, __webpack_exports__TextClassificationPipeline as TextClassificationPipeline, __webpack_exports__TextGenerationPipeline as TextGenerationPipeline, __webpack_exports__TextStreamer as TextStreamer, __webpack_exports__TextToAudioPipeline as TextToAudioPipeline, __webpack_exports__TokenClassificationPipeline as TokenClassificationPipeline, __webpack_exports__TokenClassifierOutput as TokenClassifierOutput, __webpack_exports__TokenizerModel as TokenizerModel, __webpack_exports__TopKLogitsWarper as TopKLogitsWarper, __webpack_exports__TopPLogitsWarper as TopPLogitsWarper, __webpack_exports__TrOCRForCausalLM as TrOCRForCausalLM, __webpack_exports__TrOCRPreTrainedModel as TrOCRPreTrainedModel, __webpack_exports__TranslationPipeline as TranslationPipeline, __webpack_exports__UltravoxModel as UltravoxModel, __webpack_exports__UltravoxPreTrainedModel as UltravoxPreTrainedModel, __webpack_exports__UltravoxProcessor as UltravoxProcessor, __webpack_exports__UniSpeechForCTC as UniSpeechForCTC, __webpack_exports__UniSpeechForSequenceClassification as UniSpeechForSequenceClassification, __webpack_exports__UniSpeechModel as UniSpeechModel, __webpack_exports__UniSpeechPreTrainedModel as UniSpeechPreTrainedModel, __webpack_exports__UniSpeechSatForAudioFrameClassification as UniSpeechSatForAudioFrameClassification, __webpack_exports__UniSpeechSatForCTC as UniSpeechSatForCTC, __webpack_exports__UniSpeechSatForSequenceClassification as UniSpeechSatForSequenceClassification, __webpack_exports__UniSpeechSatModel as UniSpeechSatModel, __webpack_exports__UniSpeechSatPreTrainedModel as UniSpeechSatPreTrainedModel, __webpack_exports__VLChatProcessor as VLChatProcessor, __webpack_exports__VLMImageProcessor as VLMImageProcessor, __webpack_exports__ViTFeatureExtractor as ViTFeatureExtractor, __webpack_exports__ViTForImageClassification as ViTForImageClassification, __webpack_exports__ViTImageProcessor as ViTImageProcessor, __webpack_exports__ViTMAEModel as ViTMAEModel, __webpack_exports__ViTMAEPreTrainedModel as ViTMAEPreTrainedModel, __webpack_exports__ViTMSNForImageClassification as ViTMSNForImageClassification, __webpack_exports__ViTMSNModel as ViTMSNModel, __webpack_exports__ViTMSNPreTrainedModel as ViTMSNPreTrainedModel, __webpack_exports__ViTModel as ViTModel, __webpack_exports__ViTPreTrainedModel as ViTPreTrainedModel, __webpack_exports__VisionEncoderDecoderModel as VisionEncoderDecoderModel, __webpack_exports__VitMatteForImageMatting as VitMatteForImageMatting, __webpack_exports__VitMatteImageProcessor as VitMatteImageProcessor, __webpack_exports__VitMattePreTrainedModel as VitMattePreTrainedModel, __webpack_exports__VitPoseForPoseEstimation as VitPoseForPoseEstimation, __webpack_exports__VitPoseImageProcessor as VitPoseImageProcessor, __webpack_exports__VitPosePreTrainedModel as VitPosePreTrainedModel, __webpack_exports__VitsModel as VitsModel, __webpack_exports__VitsModelOutput as VitsModelOutput, __webpack_exports__VitsPreTrainedModel as VitsPreTrainedModel, __webpack_exports__VitsTokenizer as VitsTokenizer, __webpack_exports__VoxtralForConditionalGeneration as VoxtralForConditionalGeneration, __webpack_exports__VoxtralProcessor as VoxtralProcessor, __webpack_exports__Wav2Vec2BertForCTC as Wav2Vec2BertForCTC, __webpack_exports__Wav2Vec2BertForSequenceClassification as Wav2Vec2BertForSequenceClassification, __webpack_exports__Wav2Vec2BertModel as Wav2Vec2BertModel, __webpack_exports__Wav2Vec2BertPreTrainedModel as Wav2Vec2BertPreTrainedModel, __webpack_exports__Wav2Vec2CTCTokenizer as Wav2Vec2CTCTokenizer, __webpack_exports__Wav2Vec2FeatureExtractor as Wav2Vec2FeatureExtractor, __webpack_exports__Wav2Vec2ForAudioFrameClassification as Wav2Vec2ForAudioFrameClassification, __webpack_exports__Wav2Vec2ForCTC as Wav2Vec2ForCTC, __webpack_exports__Wav2Vec2ForSequenceClassification as Wav2Vec2ForSequenceClassification, __webpack_exports__Wav2Vec2Model as Wav2Vec2Model, __webpack_exports__Wav2Vec2PreTrainedModel as Wav2Vec2PreTrainedModel, __webpack_exports__Wav2Vec2Processor as Wav2Vec2Processor, __webpack_exports__Wav2Vec2ProcessorWithLM as Wav2Vec2ProcessorWithLM, __webpack_exports__WavLMForAudioFrameClassification as WavLMForAudioFrameClassification, __webpack_exports__WavLMForCTC as WavLMForCTC, __webpack_exports__WavLMForSequenceClassification as WavLMForSequenceClassification, __webpack_exports__WavLMForXVector as WavLMForXVector, __webpack_exports__WavLMModel as WavLMModel, __webpack_exports__WavLMPreTrainedModel as WavLMPreTrainedModel, __webpack_exports__WeSpeakerFeatureExtractor as WeSpeakerFeatureExtractor, __webpack_exports__WeSpeakerResNetModel as WeSpeakerResNetModel, __webpack_exports__WeSpeakerResNetPreTrainedModel as WeSpeakerResNetPreTrainedModel, __webpack_exports__WhisperFeatureExtractor as WhisperFeatureExtractor, __webpack_exports__WhisperForConditionalGeneration as WhisperForConditionalGeneration, __webpack_exports__WhisperModel as WhisperModel, __webpack_exports__WhisperPreTrainedModel as WhisperPreTrainedModel, __webpack_exports__WhisperProcessor as WhisperProcessor, __webpack_exports__WhisperTextStreamer as WhisperTextStreamer, __webpack_exports__WhisperTimeStampLogitsProcessor as WhisperTimeStampLogitsProcessor, __webpack_exports__WhisperTokenizer as WhisperTokenizer, __webpack_exports__XLMForQuestionAnswering as XLMForQuestionAnswering, __webpack_exports__XLMForSequenceClassification as XLMForSequenceClassification, __webpack_exports__XLMForTokenClassification as XLMForTokenClassification, __webpack_exports__XLMModel as XLMModel, __webpack_exports__XLMPreTrainedModel as XLMPreTrainedModel, __webpack_exports__XLMRobertaForMaskedLM as XLMRobertaForMaskedLM, __webpack_exports__XLMRobertaForQuestionAnswering as XLMRobertaForQuestionAnswering, __webpack_exports__XLMRobertaForSequenceClassification as XLMRobertaForSequenceClassification, __webpack_exports__XLMRobertaForTokenClassification as XLMRobertaForTokenClassification, __webpack_exports__XLMRobertaModel as XLMRobertaModel, __webpack_exports__XLMRobertaPreTrainedModel as XLMRobertaPreTrainedModel, __webpack_exports__XLMRobertaTokenizer as XLMRobertaTokenizer, __webpack_exports__XLMTokenizer as XLMTokenizer, __webpack_exports__XLMWithLMHeadModel as XLMWithLMHeadModel, __webpack_exports__XVectorOutput as XVectorOutput, __webpack_exports__YolosFeatureExtractor as YolosFeatureExtractor, __webpack_exports__YolosForObjectDetection as YolosForObjectDetection, __webpack_exports__YolosImageProcessor as YolosImageProcessor, __webpack_exports__YolosModel as YolosModel, __webpack_exports__YolosObjectDetectionOutput as YolosObjectDetectionOutput, __webpack_exports__YolosPreTrainedModel as YolosPreTrainedModel, __webpack_exports__ZeroShotAudioClassificationPipeline as ZeroShotAudioClassificationPipeline, __webpack_exports__ZeroShotClassificationPipeline as ZeroShotClassificationPipeline, __webpack_exports__ZeroShotImageClassificationPipeline as ZeroShotImageClassificationPipeline, __webpack_exports__ZeroShotObjectDetectionPipeline as ZeroShotObjectDetectionPipeline, __webpack_exports__bankers_round as bankers_round, __webpack_exports__cat as cat, __webpack_exports__cos_sim as cos_sim, __webpack_exports__dot as dot, __webpack_exports__dynamic_time_warping as dynamic_time_warping, __webpack_exports__env as env, __webpack_exports__full as full, __webpack_exports__full_like as full_like, __webpack_exports__getCacheShapes as getCacheShapes, __webpack_exports__hamming as hamming, __webpack_exports__hanning as hanning, __webpack_exports__interpolate as interpolate, __webpack_exports__interpolate_4d as interpolate_4d, __webpack_exports__interpolate_data as interpolate_data, __webpack_exports__is_chinese_char as is_chinese_char, __webpack_exports__layer_norm as layer_norm, __webpack_exports__load_image as load_image, __webpack_exports__load_video as load_video, __webpack_exports__log_softmax as log_softmax, __webpack_exports__magnitude as magnitude, __webpack_exports__matmul as matmul, __webpack_exports__max as max, __webpack_exports__mean as mean, __webpack_exports__mean_pooling as mean_pooling, __webpack_exports__medianFilter as medianFilter, __webpack_exports__mel_filter_bank as mel_filter_bank, __webpack_exports__min as min, __webpack_exports__ones as ones, __webpack_exports__ones_like as ones_like, __webpack_exports__permute as permute, __webpack_exports__permute_data as permute_data, __webpack_exports__pipeline as pipeline, __webpack_exports__quantize_embeddings as quantize_embeddings, __webpack_exports__rand as rand, __webpack_exports__read_audio as read_audio, __webpack_exports__rfft as rfft, __webpack_exports__round as round, __webpack_exports__slice as slice, __webpack_exports__softmax as softmax, __webpack_exports__spectrogram as spectrogram, __webpack_exports__stack as stack, __webpack_exports__std_mean as std_mean, __webpack_exports__topk as topk, __webpack_exports__window_function as window_function, __webpack_exports__zeros as zeros, __webpack_exports__zeros_like as zeros_like }; - -//# sourceMappingURL=transformers.js.map \ No newline at end of file +// src/utils/model_registry/ModelRegistry.js +var ModelRegistry = class { + /** + * Get all files (model, tokenizer, processor) needed for a model. + * + * @param {string} modelId - The model id (e.g., "onnx-community/bert-base-uncased-ONNX") + * @param {Object} [options] - Optional parameters + * @param {import('../../configs.js').PretrainedConfig} [options.config=null] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @param {string} [options.model_file_name=null] - Override the model file name (excluding .onnx suffix) + * @param {boolean} [options.include_tokenizer=true] - Whether to check for tokenizer files + * @param {boolean} [options.include_processor=true] - Whether to check for processor files + * @returns {Promise} Array of file paths + * + * **Example:** + * ```javascript + * const files = await ModelRegistry.get_files('onnx-community/gpt2-ONNX'); + * console.log(files); // ['config.json', 'tokenizer.json', 'onnx/model_q4.onnx', ...] + * ``` + */ + static async get_files(modelId, options = {}) { + return get_files(modelId, options); + } + /** + * Get all files needed for a specific pipeline task. + * Automatically determines which components are needed based on the task. + * + * @param {string} task - The pipeline task (e.g., "text-generation", "background-removal") + * @param {string} modelId - The model id (e.g., "onnx-community/bert-base-uncased-ONNX") + * @param {Object} [options] - Optional parameters + * @param {import('../../configs.js').PretrainedConfig} [options.config=null] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @param {string} [options.model_file_name=null] - Override the model file name (excluding .onnx suffix) + * @returns {Promise} Array of file paths + * + * **Example:** + * ```javascript + * const files = await ModelRegistry.get_pipeline_files('text-generation', 'onnx-community/gpt2-ONNX'); + * console.log(files); // ['config.json', 'tokenizer.json', 'onnx/model_q4.onnx', ...] + * ``` + */ + static async get_pipeline_files(task, modelId, options = {}) { + return get_pipeline_files(task, modelId, options); + } + /** + * Get model files needed for a specific model. + * + * @param {string} modelId - The model id + * @param {Object} [options] - Optional parameters + * @param {import('../../configs.js').PretrainedConfig} [options.config=null] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @param {string} [options.model_file_name=null] - Override the model file name (excluding .onnx suffix) + * @returns {Promise} Array of model file paths + * + * **Example:** + * ```javascript + * const files = await ModelRegistry.get_model_files('onnx-community/bert-base-uncased-ONNX'); + * console.log(files); // ['config.json', 'onnx/model_q4.onnx', 'generation_config.json'] + * ``` + */ + static async get_model_files(modelId, options = {}) { + return get_model_files(modelId, options); + } + /** + * Get tokenizer files needed for a specific model. + * + * @param {string} modelId - The model id + * @returns {Promise} Array of tokenizer file paths + * + * **Example:** + * ```javascript + * const files = await ModelRegistry.get_tokenizer_files('onnx-community/gpt2-ONNX'); + * console.log(files); // ['tokenizer.json', 'tokenizer_config.json'] + * ``` + */ + static async get_tokenizer_files(modelId) { + return get_tokenizer_files(modelId); + } + /** + * Get processor files needed for a specific model. + * + * @param {string} modelId - The model id + * @returns {Promise} Array of processor file paths + * + * **Example:** + * ```javascript + * const files = await ModelRegistry.get_processor_files('onnx-community/vit-base-patch16-224-ONNX'); + * console.log(files); // ['preprocessor_config.json'] + * ``` + */ + static async get_processor_files(modelId) { + return get_processor_files(modelId); + } + /** + * Detects which quantization levels (dtypes) are available for a model + * by checking which ONNX files exist on the hub or locally. + * + * A dtype is considered available if all required model session files + * exist for that dtype. + * + * An empty array means the model is accessible but has no complete set of ONNX files for any dtype. + * + * @param {string} modelId - The model id (e.g., "onnx-community/all-MiniLM-L6-v2-ONNX") + * @param {Object} [options] - Optional parameters + * @param {import('../../configs.js').PretrainedConfig} [options.config=null] - Pre-loaded config + * @param {string} [options.model_file_name=null] - Override the model file name (excluding .onnx suffix) + * @param {string} [options.revision='main'] - Model revision + * @param {string} [options.cache_dir=null] - Custom cache directory + * @param {boolean} [options.local_files_only=false] - Only check local files + * @returns {Promise} Array of available dtype strings (e.g., ['fp32', 'fp16', 'q4', 'q8']). Empty if the model has no ONNX files. + * @throws {import('../hub/utils.js').ModelFileNotFoundError} If the model is missing or inaccessible. The Hub returns 401 for nonexistent repositories. + * @throws {Error} On network or server failures. + * + * **Example:** + * ```javascript + * const dtypes = await ModelRegistry.get_available_dtypes('onnx-community/all-MiniLM-L6-v2-ONNX'); + * console.log(dtypes); // ['fp32', 'fp16', 'int8', 'uint8', 'q8', 'q4'] + * ``` + */ + static async get_available_dtypes(modelId, options = {}) { + return get_available_dtypes(modelId, options); + } + /** + * Quickly checks if a model is fully cached by verifying `config.json` is present, + * then confirming all required files are cached. + * Returns a plain boolean — use `is_cached_files` if you need per-file detail. + * + * @param {string} modelId - The model id + * @param {Object} [options] - Optional parameters + * @param {string} [options.cache_dir] - Custom cache directory + * @param {string} [options.revision] - Model revision (default: 'main') + * @param {import('../../configs.js').PretrainedConfig} [options.config] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @returns {Promise} Whether all required files are cached + * + * **Example:** + * ```javascript + * const cached = await ModelRegistry.is_cached('onnx-community/bert-base-uncased-ONNX'); + * console.log(cached); // true or false + * ``` + */ + static async is_cached(modelId, options = {}) { + return is_cached(modelId, options); + } + /** + * Checks if all files for a given model are already cached, with per-file detail. + * Automatically determines which files are needed using get_files(). + * + * @param {string} modelId - The model id + * @param {Object} [options] - Optional parameters + * @param {string} [options.cache_dir] - Custom cache directory + * @param {string} [options.revision] - Model revision (default: 'main') + * @param {import('../../configs.js').PretrainedConfig} [options.config] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @returns {Promise} Object with allCached boolean and files array with cache status + * + * **Example:** + * ```javascript + * const status = await ModelRegistry.is_cached_files('onnx-community/bert-base-uncased-ONNX'); + * console.log(status.allCached); // true or false + * console.log(status.files); // [{ file: 'config.json', cached: true }, ...] + * ``` + */ + static async is_cached_files(modelId, options = {}) { + return is_cached_files(modelId, options); + } + /** + * Quickly checks if all files for a specific pipeline task are cached by verifying + * `config.json` is present, then confirming all required files are cached. + * Returns a plain boolean — use `is_pipeline_cached_files` if you need per-file detail. + * + * @param {string} task - The pipeline task (e.g., "text-generation", "background-removal") + * @param {string} modelId - The model id + * @param {Object} [options] - Optional parameters + * @param {string} [options.cache_dir] - Custom cache directory + * @param {string} [options.revision] - Model revision (default: 'main') + * @param {import('../../configs.js').PretrainedConfig} [options.config] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @returns {Promise} Whether all required files are cached + * + * **Example:** + * ```javascript + * const cached = await ModelRegistry.is_pipeline_cached('text-generation', 'onnx-community/gpt2-ONNX'); + * console.log(cached); // true or false + * ``` + */ + static async is_pipeline_cached(task, modelId, options = {}) { + return is_pipeline_cached(task, modelId, options); + } + /** + * Checks if all files for a specific pipeline task are already cached, with per-file detail. + * Automatically determines which components are needed based on the task. + * + * @param {string} task - The pipeline task (e.g., "text-generation", "background-removal") + * @param {string} modelId - The model id + * @param {Object} [options] - Optional parameters + * @param {string} [options.cache_dir] - Custom cache directory + * @param {string} [options.revision] - Model revision (default: 'main') + * @param {import('../../configs.js').PretrainedConfig} [options.config] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype=null] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device=null] - Override device + * @returns {Promise} Object with allCached boolean and files array with cache status + * + * **Example:** + * ```javascript + * const status = await ModelRegistry.is_pipeline_cached_files('text-generation', 'onnx-community/gpt2-ONNX'); + * console.log(status.allCached); // true or false + * console.log(status.files); // [{ file: 'config.json', cached: true }, ...] + * ``` + */ + static async is_pipeline_cached_files(task, modelId, options = {}) { + return is_pipeline_cached_files(task, modelId, options); + } + /** + * Get metadata for a specific file without downloading it. + * + * @param {string} path_or_repo_id - Model id or path + * @param {string} filename - The file name + * @param {import('../hub.js').PretrainedOptions} [options] - Optional parameters + * @returns {Promise<{exists: boolean, size?: number, contentType?: string, fromCache?: boolean}>} File metadata. `exists: false` means the file was not found. + * @throws {import('../hub/utils.js').ModelFileNotFoundError} If the file is missing or inaccessible. The Hub returns 401 for nonexistent repositories. + * @throws {Error} On network or server failures. + * + * **Example:** + * ```javascript + * const metadata = await ModelRegistry.get_file_metadata('onnx-community/gpt2-ONNX', 'config.json'); + * console.log(metadata.exists, metadata.size); // true, 665 + * ``` + */ + static async get_file_metadata(path_or_repo_id, filename, options = {}) { + return get_file_metadata(path_or_repo_id, filename, options); + } + /** + * Clears all cached files for a given model. + * Automatically determines which files are needed and removes them from the cache. + * + * @param {string} modelId - The model id (e.g., "onnx-community/gpt2-ONNX") + * @param {Object} [options] - Optional parameters + * @param {string} [options.cache_dir] - Custom cache directory + * @param {string} [options.revision] - Model revision (default: 'main') + * @param {import('../../configs.js').PretrainedConfig} [options.config] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device] - Override device + * @param {boolean} [options.include_tokenizer=true] - Whether to clear tokenizer files + * @param {boolean} [options.include_processor=true] - Whether to clear processor files + * @returns {Promise} Object with deletion statistics and file status + * + * **Example:** + * ```javascript + * const result = await ModelRegistry.clear_cache('onnx-community/bert-base-uncased-ONNX'); + * console.log(`Deleted ${result.filesDeleted} of ${result.filesCached} cached files`); + * ``` + */ + static async clear_cache(modelId, options = {}) { + return clear_cache(modelId, options); + } + /** + * Clears all cached files for a specific pipeline task. + * Automatically determines which components are needed based on the task. + * + * @param {string} task - The pipeline task (e.g., "text-generation", "image-classification") + * @param {string} modelId - The model id (e.g., "onnx-community/gpt2-ONNX") + * @param {Object} [options] - Optional parameters + * @param {string} [options.cache_dir] - Custom cache directory + * @param {string} [options.revision] - Model revision (default: 'main') + * @param {import('../../configs.js').PretrainedConfig} [options.config] - Pre-loaded config + * @param {import('../dtypes.js').DataType|Record} [options.dtype] - Override dtype + * @param {import('../devices.js').DeviceType|Record} [options.device] - Override device + * @returns {Promise} Object with deletion statistics and file status + * + * **Example:** + * ```javascript + * const result = await ModelRegistry.clear_pipeline_cache('text-generation', 'onnx-community/gpt2-ONNX'); + * console.log(`Deleted ${result.filesDeleted} of ${result.filesCached} cached files`); + * ``` + */ + static async clear_pipeline_cache(task, modelId, options = {}) { + return clear_pipeline_cache(task, modelId, options); + } +}; +export { + ASTFeatureExtractor, + ASTForAudioClassification, + ASTModel, + ASTPreTrainedModel, + AfmoeForCausalLM, + AfmoeModel, + AfmoePreTrainedModel, + AlbertForMaskedLM, + AlbertForQuestionAnswering, + AlbertForSequenceClassification, + AlbertModel, + AlbertPreTrainedModel, + AlbertTokenizer, + ApertusForCausalLM, + ApertusModel, + ApertusPreTrainedModel, + ArceeForCausalLM, + ArceeModel, + ArceePreTrainedModel, + AudioClassificationPipeline, + AutoConfig, + AutoFeatureExtractor, + AutoImageProcessor, + AutoModel, + AutoModelForAudioClassification, + AutoModelForAudioFrameClassification, + AutoModelForAudioTextToText, + AutoModelForCTC, + AutoModelForCausalLM, + AutoModelForDepthEstimation, + AutoModelForDocumentQuestionAnswering, + AutoModelForImageClassification, + AutoModelForImageFeatureExtraction, + AutoModelForImageMatting, + AutoModelForImageSegmentation, + AutoModelForImageTextToText, + AutoModelForImageToImage, + AutoModelForMaskGeneration, + AutoModelForMaskedLM, + AutoModelForNormalEstimation, + AutoModelForObjectDetection, + AutoModelForPoseEstimation, + AutoModelForQuestionAnswering, + AutoModelForSemanticSegmentation, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoModelForSpeechSeq2Seq, + AutoModelForTextToSpectrogram, + AutoModelForTextToWaveform, + AutoModelForTokenClassification, + AutoModelForUniversalSegmentation, + AutoModelForVision2Seq, + AutoModelForXVector, + AutoModelForZeroShotObjectDetection, + AutoProcessor, + AutoTokenizer, + AutomaticSpeechRecognitionPipeline, + BackgroundRemovalPipeline, + BartForConditionalGeneration, + BartForSequenceClassification, + BartModel, + BartPretrainedModel, + BartTokenizer, + BaseModelOutput, + BaseStreamer, + BeitFeatureExtractor, + BeitForImageClassification, + BeitModel, + BeitPreTrainedModel, + BertForMaskedLM, + BertForQuestionAnswering, + BertForSequenceClassification, + BertForTokenClassification, + BertModel, + BertPreTrainedModel, + BertTokenizer, + BitImageProcessor, + BlenderbotForConditionalGeneration, + BlenderbotModel, + BlenderbotPreTrainedModel, + BlenderbotSmallForConditionalGeneration, + BlenderbotSmallModel, + BlenderbotSmallPreTrainedModel, + BlenderbotSmallTokenizer, + BlenderbotTokenizer, + BloomForCausalLM, + BloomModel, + BloomPreTrainedModel, + BloomTokenizer, + CHMv2ForDepthEstimation, + CHMv2ImageProcessor, + CHMv2PreTrainedModel, + CLIPFeatureExtractor, + CLIPImageProcessor, + CLIPModel, + CLIPPreTrainedModel, + CLIPSegForImageSegmentation, + CLIPSegModel, + CLIPSegPreTrainedModel, + CLIPTextModel, + CLIPTextModelWithProjection, + CLIPTokenizer, + CLIPVisionModel, + CLIPVisionModelWithProjection, + CamembertForMaskedLM, + CamembertForQuestionAnswering, + CamembertForSequenceClassification, + CamembertForTokenClassification, + CamembertModel, + CamembertPreTrainedModel, + CamembertTokenizer, + CausalLMOutput, + CausalLMOutputWithPast, + ChatterboxFeatureExtractor, + ChatterboxModel, + ChatterboxPreTrainedModel, + ChatterboxProcessor, + ChineseCLIPFeatureExtractor, + ChineseCLIPModel, + ChineseCLIPPreTrainedModel, + ClapAudioModelWithProjection, + ClapFeatureExtractor, + ClapModel, + ClapPreTrainedModel, + ClapTextModelWithProjection, + ClassifierFreeGuidanceLogitsProcessor, + CodeGenForCausalLM, + CodeGenModel, + CodeGenPreTrainedModel, + CodeGenTokenizer, + CodeLlamaTokenizer, + Cohere2ForCausalLM, + Cohere2Model, + Cohere2PreTrainedModel, + CohereAsrFeatureExtractor, + CohereAsrForConditionalGeneration, + CohereAsrModel, + CohereAsrPreTrainedModel, + CohereAsrProcessor, + CohereAsrTokenizer, + CohereForCausalLM, + CohereModel, + CoherePreTrainedModel, + CohereTokenizer, + ConvBertForMaskedLM, + ConvBertForQuestionAnswering, + ConvBertForSequenceClassification, + ConvBertForTokenClassification, + ConvBertModel, + ConvBertPreTrainedModel, + ConvBertTokenizer, + ConvNextFeatureExtractor, + ConvNextForImageClassification, + ConvNextImageProcessor, + ConvNextModel, + ConvNextPreTrainedModel, + ConvNextV2ForImageClassification, + ConvNextV2Model, + ConvNextV2PreTrainedModel, + DFineForObjectDetection, + DFineModel, + DFinePreTrainedModel, + DINOv3ConvNextModel, + DINOv3ConvNextPreTrainedModel, + DINOv3ViTImageProcessor, + DINOv3ViTModel, + DINOv3ViTPreTrainedModel, + DPTFeatureExtractor, + DPTForDepthEstimation, + DPTImageProcessor, + DPTModel, + DPTPreTrainedModel, + DacDecoderModel, + DacDecoderOutput, + DacEncoderModel, + DacEncoderOutput, + DacFeatureExtractor, + DacModel, + DacPreTrainedModel, + DebertaForMaskedLM, + DebertaForQuestionAnswering, + DebertaForSequenceClassification, + DebertaForTokenClassification, + DebertaModel, + DebertaPreTrainedModel, + DebertaTokenizer, + DebertaV2ForMaskedLM, + DebertaV2ForQuestionAnswering, + DebertaV2ForSequenceClassification, + DebertaV2ForTokenClassification, + DebertaV2Model, + DebertaV2PreTrainedModel, + DebertaV2Tokenizer, + DecisionTransformerModel, + DecisionTransformerPreTrainedModel, + DeepseekV3ForCausalLM, + DeepseekV3Model, + DeepseekV3PreTrainedModel, + DeepseekV4ForCausalLM, + DeepseekV4Model, + DeepseekV4PreTrainedModel, + DeiTFeatureExtractor, + DeiTForImageClassification, + DeiTImageProcessor, + DeiTModel, + DeiTPreTrainedModel, + DepthAnythingForDepthEstimation, + DepthAnythingPreTrainedModel, + DepthEstimationPipeline, + DepthProForDepthEstimation, + DepthProPreTrainedModel, + DetrFeatureExtractor, + DetrForObjectDetection, + DetrForSegmentation, + DetrImageProcessor, + DetrModel, + DetrObjectDetectionOutput, + DetrPreTrainedModel, + DetrSegmentationOutput, + Dinov2ForImageClassification, + Dinov2Model, + Dinov2PreTrainedModel, + Dinov2WithRegistersForImageClassification, + Dinov2WithRegistersModel, + Dinov2WithRegistersPreTrainedModel, + DistilBertForMaskedLM, + DistilBertForQuestionAnswering, + DistilBertForSequenceClassification, + DistilBertForTokenClassification, + DistilBertModel, + DistilBertPreTrainedModel, + DistilBertTokenizer, + DocumentQuestionAnsweringPipeline, + DonutFeatureExtractor, + DonutImageProcessor, + DonutSwinModel, + DonutSwinPreTrainedModel, + DynamicCache, + EdgeTamModel, + EfficientNetForImageClassification, + EfficientNetImageProcessor, + EfficientNetModel, + EfficientNetPreTrainedModel, + ElectraForMaskedLM, + ElectraForQuestionAnswering, + ElectraForSequenceClassification, + ElectraForTokenClassification, + ElectraModel, + ElectraPreTrainedModel, + ElectraTokenizer, + EmbeddingGemma2Model, + EmbeddingGemma2PreTrainedModel, + EmbeddingGemma2Processor, + EmbeddingGemma2VideoProcessor, + EncodecFeatureExtractor, + EosTokenCriteria, + Ernie4_5ForCausalLM, + Ernie4_5Model, + Ernie4_5PretrainedModel, + EsmForMaskedLM, + EsmForSequenceClassification, + EsmForTokenClassification, + EsmModel, + EsmPreTrainedModel, + EsmTokenizer, + EuroBertForMaskedLM, + EuroBertForSequenceClassification, + EuroBertForTokenClassification, + EuroBertModel, + EuroBertPreTrainedModel, + ExaoneForCausalLM, + ExaoneModel, + ExaonePreTrainedModel, + FalconForCausalLM, + FalconH1ForCausalLM, + FalconH1Model, + FalconH1PreTrainedModel, + FalconModel, + FalconPreTrainedModel, + FalconTokenizer, + FastViTForImageClassification, + FastViTModel, + FastViTPreTrainedModel, + FeatureExtractionPipeline, + FeatureExtractor, + FillMaskPipeline, + Florence2ForConditionalGeneration, + Florence2PreTrainedModel, + Florence2Processor, + ForcedBOSTokenLogitsProcessor, + ForcedEOSTokenLogitsProcessor, + GLPNFeatureExtractor, + GLPNForDepthEstimation, + GLPNModel, + GLPNPreTrainedModel, + GPT2LMHeadModel, + GPT2Model, + GPT2PreTrainedModel, + GPT2Tokenizer, + GPTBigCodeForCausalLM, + GPTBigCodeModel, + GPTBigCodePreTrainedModel, + GPTJForCausalLM, + GPTJModel, + GPTJPreTrainedModel, + GPTNeoForCausalLM, + GPTNeoModel, + GPTNeoPreTrainedModel, + GPTNeoXForCausalLM, + GPTNeoXModel, + GPTNeoXPreTrainedModel, + GPTNeoXTokenizer, + Gemma2ForCausalLM, + Gemma2Model, + Gemma2PreTrainedModel, + Gemma3ForCausalLM, + Gemma3ForConditionalGeneration, + Gemma3ImageProcessor, + Gemma3Model, + Gemma3PreTrainedModel, + Gemma3Processor, + Gemma3nAudioFeatureExtractor, + Gemma3nForCausalLM, + Gemma3nForConditionalGeneration, + Gemma3nPreTrainedModel, + Gemma3nProcessor, + Gemma4AudioFeatureExtractor, + Gemma4ForCausalLM, + Gemma4ForConditionalGeneration, + Gemma4ImageProcessor, + Gemma4Processor, + GemmaForCausalLM, + GemmaModel, + GemmaPreTrainedModel, + GemmaTokenizer, + GenerationConfig, + Glm46VImageProcessor, + Glm46VProcessor, + GlmForCausalLM, + GlmModel, + GlmMoeDsaForCausalLM, + GlmMoeDsaModel, + GlmMoeDsaPreTrainedModel, + GlmOcrForConditionalGeneration, + GlmPreTrainedModel, + GptOssForCausalLM, + GptOssModel, + GptOssPreTrainedModel, + GraniteForCausalLM, + GraniteModel, + GraniteMoeHybridForCausalLM, + GraniteMoeHybridModel, + GraniteMoeHybridPreTrainedModel, + GranitePreTrainedModel, + GraniteSpeechFeatureExtractor, + GraniteSpeechForConditionalGeneration, + GraniteSpeechProcessor, + GroundingDinoForObjectDetection, + GroundingDinoImageProcessor, + GroundingDinoPreTrainedModel, + GroundingDinoProcessor, + GroupViTModel, + GroupViTPreTrainedModel, + HeliumForCausalLM, + HeliumModel, + HeliumPreTrainedModel, + HerbertTokenizer, + HieraForImageClassification, + HieraModel, + HieraPreTrainedModel, + HrmTextForCausalLM, + HrmTextModel, + HrmTextPreTrainedModel, + HubertForCTC, + HubertForSequenceClassification, + HubertModel, + HubertPreTrainedModel, + HunYuanDenseV1ForCausalLM, + HunYuanDenseV1Model, + HunYuanDenseV1PreTrainedModel, + IJepaForImageClassification, + IJepaModel, + IJepaPreTrainedModel, + Idefics3ForConditionalGeneration, + Idefics3ImageProcessor, + Idefics3Processor, + ImageClassificationPipeline, + ImageFeatureExtractionPipeline, + ImageProcessor as ImageFeatureExtractor, + ImageMattingOutput, + ImageProcessor, + ImageSegmentationPipeline, + ImageToImagePipeline, + ImageToTextPipeline, + InterruptableStoppingCriteria, + JAISLMHeadModel, + JAISModel, + JAISPreTrainedModel, + JinaCLIPImageProcessor, + JinaCLIPModel, + JinaCLIPPreTrainedModel, + JinaCLIPProcessor, + JinaCLIPTextModel, + JinaCLIPVisionModel, + Lfm2ForCausalLM, + Lfm2Model, + Lfm2MoeForCausalLM, + Lfm2MoeModel, + Lfm2MoePreTrainedModel, + Lfm2PreTrainedModel, + Lfm2VlForConditionalGeneration, + Lfm2VlImageProcessor, + Lfm2VlProcessor, + Lfm3ForCausalLM, + Lfm3Model, + Lfm3PreTrainedModel, + Lfm3VlForConditionalGeneration, + Lfm3VlImageProcessor, + Lfm3VlProcessor, + LightOnOcrForConditionalGeneration, + LiteWhisperForConditionalGeneration, + Llama4ForCausalLM, + Llama4PreTrainedModel, + LlamaForCausalLM, + LlamaModel, + LlamaPreTrainedModel, + LlamaTokenizer, + LlavaForConditionalGeneration, + LlavaForConditionalGeneration as LlavaOnevisionForConditionalGeneration, + LlavaOnevisionImageProcessor, + LlavaPreTrainedModel, + LlavaProcessor, + LlavaQwen2ForCausalLM, + LogLevel, + LogitsProcessor, + LogitsProcessorList, + LogitsWarper, + LongT5ForConditionalGeneration, + LongT5Model, + LongT5PreTrainedModel, + M2M100ForConditionalGeneration, + M2M100Model, + M2M100PreTrainedModel, + M2M100Tokenizer, + MBart50Tokenizer, + MBartForCausalLM, + MBartForConditionalGeneration, + MBartForSequenceClassification, + MBartModel, + MBartPreTrainedModel, + MBartTokenizer, + MPNetForMaskedLM, + MPNetForQuestionAnswering, + MPNetForSequenceClassification, + MPNetForTokenClassification, + MPNetModel, + MPNetPreTrainedModel, + MPNetTokenizer, + MT5ForConditionalGeneration, + MT5Model, + MT5PreTrainedModel, + MarianMTModel, + MarianModel, + MarianPreTrainedModel, + MarianTokenizer, + Mask2FormerImageProcessor, + MaskFormerFeatureExtractor, + MaskFormerForInstanceSegmentation, + MaskFormerImageProcessor, + MaskFormerModel, + MaskFormerPreTrainedModel, + MaskedLMOutput, + MaxLengthCriteria, + Metric3DForDepthEstimation, + Metric3DPreTrainedModel, + Metric3Dv2ForDepthEstimation, + Metric3Dv2PreTrainedModel, + MgpstrForSceneTextRecognition, + MgpstrModelOutput, + MgpstrPreTrainedModel, + MgpstrProcessor, + MgpstrTokenizer, + MimiDecoderModel, + MimiDecoderOutput, + MimiEncoderModel, + MimiEncoderOutput, + MimiModel, + MimiPreTrainedModel, + MinLengthLogitsProcessor, + MinNewTokensLengthLogitsProcessor, + Ministral3ForCausalLM, + Ministral3Model, + Ministral3PreTrainedModel, + MinistralForCausalLM, + MinistralModel, + MinistralPreTrainedModel, + Mistral3ForConditionalGeneration, + Mistral4ForCausalLM, + Mistral4Model, + Mistral4PreTrainedModel, + MistralForCausalLM, + MistralModel, + MistralPreTrainedModel, + MobileBertForMaskedLM, + MobileBertForQuestionAnswering, + MobileBertForSequenceClassification, + MobileBertModel, + MobileBertPreTrainedModel, + MobileBertTokenizer, + MobileLLMForCausalLM, + MobileLLMModel, + MobileLLMPreTrainedModel, + MobileNetV1FeatureExtractor, + MobileNetV1ForImageClassification, + MobileNetV1ForSemanticSegmentation, + MobileNetV1ImageProcessor, + MobileNetV1Model, + MobileNetV1PreTrainedModel, + MobileNetV2FeatureExtractor, + MobileNetV2ForImageClassification, + MobileNetV2ForSemanticSegmentation, + MobileNetV2ImageProcessor, + MobileNetV2Model, + MobileNetV2PreTrainedModel, + MobileNetV3FeatureExtractor, + MobileNetV3ForImageClassification, + MobileNetV3ForSemanticSegmentation, + MobileNetV3ImageProcessor, + MobileNetV3Model, + MobileNetV3PreTrainedModel, + MobileNetV4FeatureExtractor, + MobileNetV4ForImageClassification, + MobileNetV4ForSemanticSegmentation, + MobileNetV4ImageProcessor, + MobileNetV4Model, + MobileNetV4PreTrainedModel, + MobileViTFeatureExtractor, + MobileViTForImageClassification, + MobileViTImageProcessor, + MobileViTModel, + MobileViTPreTrainedModel, + MobileViTV2ForImageClassification, + MobileViTV2Model, + MobileViTV2PreTrainedModel, + ModelFileNotFoundError, + ModelOutput, + ModelRegistry, + ModernBertDecoderForCausalLM, + ModernBertDecoderModel, + ModernBertDecoderPreTrainedModel, + ModernBertForMaskedLM, + ModernBertForSequenceClassification, + ModernBertForTokenClassification, + ModernBertModel, + ModernBertPreTrainedModel, + Moondream1ForConditionalGeneration, + MoonshineFeatureExtractor, + MoonshineForConditionalGeneration, + MoonshineModel, + MoonshinePreTrainedModel, + MoonshineProcessor, + MptForCausalLM, + MptModel, + MptPreTrainedModel, + MultiModalityCausalLM, + MultiModalityPreTrainedModel, + MusicgenForCausalLM, + MusicgenForConditionalGeneration, + MusicgenModel, + MusicgenPreTrainedModel, + NanoChatForCausalLM, + NanoChatModel, + NanoChatPreTrainedModel, + NemotronHForCausalLM, + NemotronHModel, + NemotronHPreTrainedModel, + NeoBertForMaskedLM, + NeoBertForQuestionAnswering, + NeoBertForSequenceClassification, + NeoBertForTokenClassification, + NeoBertModel, + NeoBertPreTrainedModel, + NllbTokenizer, + NoBadWordsLogitsProcessor, + NoRepeatNGramLogitsProcessor, + NomicBertModel, + NomicBertPreTrainedModel, + NougatImageProcessor, + NougatTokenizer, + OPTForCausalLM, + OPTModel, + OPTPreTrainedModel, + ObjectDetectionPipeline, + Olmo2ForCausalLM, + Olmo2Model, + Olmo2PreTrainedModel, + Olmo3ForCausalLM, + Olmo3Model, + Olmo3PreTrainedModel, + OlmoForCausalLM, + OlmoHybridForCausalLM, + OlmoHybridModel, + OlmoHybridPreTrainedModel, + OlmoModel, + OlmoPreTrainedModel, + OpenAIPrivacyFilterForTokenClassification, + OpenAIPrivacyFilterModel, + OpenAIPrivacyFilterPreTrainedModel, + OpenELMForCausalLM, + OpenELMModel, + OpenELMPreTrainedModel, + OwlViTFeatureExtractor, + OwlViTForObjectDetection, + OwlViTImageProcessor, + OwlViTModel, + OwlViTPreTrainedModel, + OwlViTProcessor, + Owlv2ForObjectDetection, + Owlv2ImageProcessor, + Owlv2Model, + Owlv2PreTrainedModel, + PaliGemmaForConditionalGeneration, + PaliGemmaProcessor, + ParakeetFeatureExtractor, + ParakeetForCTC, + ParakeetPreTrainedModel, + PatchTSMixerForPrediction, + PatchTSMixerModel, + PatchTSMixerPreTrainedModel, + PatchTSTForPrediction, + PatchTSTModel, + PatchTSTPreTrainedModel, + Phi3ForCausalLM, + Phi3Model, + Phi3PreTrainedModel, + Phi3VForCausalLM, + Phi3VImageProcessor, + Phi3VPreTrainedModel, + Phi3VProcessor, + PhiForCausalLM, + PhiModel, + PhiPreTrainedModel, + PixtralImageProcessor, + PixtralProcessor, + PreTrainedModel, + PreTrainedTokenizer, + PretrainedConfig, + Processor, + PvtForImageClassification, + PvtImageProcessor, + PvtModel, + PvtPreTrainedModel, + PyAnnoteFeatureExtractor, + PyAnnoteForAudioFrameClassification, + PyAnnoteModel, + PyAnnotePreTrainedModel, + PyAnnoteProcessor, + QuestionAnsweringModelOutput, + QuestionAnsweringPipeline, + Qwen2ForCausalLM, + Qwen2Model, + Qwen2MoeForCausalLM, + Qwen2MoeModel, + Qwen2MoePreTrainedModel, + Qwen2PreTrainedModel, + Qwen2Tokenizer, + Qwen2VLForCausalLM, + Qwen2VLForConditionalGeneration, + Qwen2VLImageProcessor, + Qwen2VLPreTrainedModel, + Qwen2VLProcessor, + Qwen2_5_VLForCausalLM, + Qwen2_5_VLForConditionalGeneration, + Qwen2_5_VLProcessor, + Qwen3ForCausalLM, + Qwen3Model, + Qwen3MoeForCausalLM, + Qwen3MoeModel, + Qwen3MoePreTrainedModel, + Qwen3NextForCausalLM, + Qwen3NextModel, + Qwen3NextPreTrainedModel, + Qwen3PreTrainedModel, + Qwen3VLForCausalLM, + Qwen3VLForConditionalGeneration, + Qwen3VLMoeForCausalLM, + Qwen3VLMoeForConditionalGeneration, + Qwen3VLProcessor, + Qwen3_5ForCausalLM, + Qwen3_5ForConditionalGeneration, + Qwen3_5MoeForCausalLM, + Qwen3_5MoeForConditionalGeneration, + RFDetrForObjectDetection, + RFDetrModel, + RFDetrObjectDetectionOutput, + RFDetrPreTrainedModel, + RTDetrForObjectDetection, + RTDetrImageProcessor, + RTDetrModel, + RTDetrObjectDetectionOutput, + RTDetrPreTrainedModel, + RTDetrV2ForObjectDetection, + RTDetrV2Model, + RTDetrV2ObjectDetectionOutput, + RTDetrV2PreTrainedModel, + RawAudio, + RawImage, + RawVideo, + RawVideoFrame, + RepetitionPenaltyLogitsProcessor, + ResNetForImageClassification, + ResNetModel, + ResNetPreTrainedModel, + RoFormerForMaskedLM, + RoFormerForQuestionAnswering, + RoFormerForSequenceClassification, + RoFormerForTokenClassification, + RoFormerModel, + RoFormerPreTrainedModel, + RoFormerTokenizer, + RobertaForMaskedLM, + RobertaForQuestionAnswering, + RobertaForSequenceClassification, + RobertaForTokenClassification, + RobertaModel, + RobertaPreTrainedModel, + RobertaTokenizer, + SamImageProcessor as Sam2ImageProcessor, + Sam2ImageSegmentationOutput, + Sam2Model, + Sam2PreTrainedModel, + Sam2Processor, + Sam2VideoProcessor, + SamImageProcessor as Sam3ImageProcessor, + Sam3TrackerModel, + SamImageProcessor, + SamImageSegmentationOutput, + SamModel, + SamPreTrainedModel, + SamProcessor, + SapiensFeatureExtractor, + SapiensForDepthEstimation, + SapiensForNormalEstimation, + SapiensForSemanticSegmentation, + SapiensImageProcessor, + SapiensPreTrainedModel, + SeamlessM4TFeatureExtractor, + SegformerFeatureExtractor, + SegformerForImageClassification, + SegformerForSemanticSegmentation, + SegformerImageProcessor, + SegformerModel, + SegformerPreTrainedModel, + Seq2SeqLMOutput, + SequenceClassifierOutput, + SiglipImageProcessor, + SiglipModel, + SiglipPreTrainedModel, + SiglipTextModel, + SiglipTokenizer, + SiglipVisionModel, + SmolLM3ForCausalLM, + SmolLM3Model, + SmolLM3PreTrainedModel, + SmolVLMForConditionalGeneration, + Idefics3ImageProcessor as SmolVLMImageProcessor, + Idefics3Processor as SmolVLMProcessor, + SnacDecoderModel, + SnacEncoderModel, + SnacFeatureExtractor, + SnacModel, + SnacPreTrainedModel, + SolarOpenForCausalLM, + SolarOpenModel, + SolarOpenPreTrainedModel, + SpeechT5FeatureExtractor, + SpeechT5ForSpeechToText, + SpeechT5ForTextToSpeech, + SpeechT5HifiGan, + SpeechT5Model, + SpeechT5PreTrainedModel, + SpeechT5Processor, + SpeechT5Tokenizer, + SqueezeBertForMaskedLM, + SqueezeBertForQuestionAnswering, + SqueezeBertForSequenceClassification, + SqueezeBertModel, + SqueezeBertPreTrainedModel, + SqueezeBertTokenizer, + StableLmForCausalLM, + StableLmModel, + StableLmPreTrainedModel, + Starcoder2ForCausalLM, + Starcoder2Model, + Starcoder2PreTrainedModel, + StoppingCriteria, + StoppingCriteriaList, + StyleTextToSpeech2Model, + StyleTextToSpeech2PreTrainedModel, + SummarizationPipeline, + SupertonicForConditionalGeneration, + SupertonicPreTrainedModel, + SuppressTokensAtBeginLogitsProcessor, + SuppressTokensLogitsProcessor, + Swin2SRForImageSuperResolution, + Swin2SRImageProcessor, + Swin2SRModel, + Swin2SRPreTrainedModel, + SwinForImageClassification, + SwinForSemanticSegmentation, + SwinModel, + SwinPreTrainedModel, + T5ForConditionalGeneration, + T5Model, + T5PreTrainedModel, + T5Tokenizer, + TableTransformerForObjectDetection, + TableTransformerModel, + TableTransformerObjectDetectionOutput, + TableTransformerPreTrainedModel, + TemperatureLogitsWarper, + Tensor3 as Tensor, + Text2TextGenerationPipeline, + TextClassificationPipeline, + TextGenerationPipeline, + TextStreamer, + TextToAudioPipeline, + TokenClassificationPipeline, + TokenClassifierOutput, + PreTrainedTokenizer as TokenizersBackend, + TopKLogitsWarper, + TopPLogitsWarper, + TrOCRForCausalLM, + TrOCRPreTrainedModel, + TranslationPipeline, + UltravoxModel, + UltravoxPreTrainedModel, + UltravoxProcessor, + UniSpeechForCTC, + UniSpeechForSequenceClassification, + UniSpeechModel, + UniSpeechPreTrainedModel, + UniSpeechSatForAudioFrameClassification, + UniSpeechSatForCTC, + UniSpeechSatForSequenceClassification, + UniSpeechSatModel, + UniSpeechSatPreTrainedModel, + VLChatProcessor, + VLMImageProcessor, + VaultGemmaForCausalLM, + VaultGemmaModel, + VaultGemmaPreTrainedModel, + ViTFeatureExtractor, + ViTForImageClassification, + ViTImageProcessor, + ViTMAEModel, + ViTMAEPreTrainedModel, + ViTMSNForImageClassification, + ViTMSNModel, + ViTMSNPreTrainedModel, + ViTModel, + ViTPreTrainedModel, + VisionEncoderDecoderModel, + VitMatteForImageMatting, + VitMatteImageProcessor, + VitMattePreTrainedModel, + VitPoseForPoseEstimation, + VitPoseImageProcessor, + VitPosePreTrainedModel, + VitsModel, + VitsModelOutput, + VitsPreTrainedModel, + VitsTokenizer, + VoxtralForConditionalGeneration, + VoxtralProcessor, + VoxtralRealtimeFeatureExtractor, + VoxtralRealtimeForConditionalGeneration, + VoxtralRealtimePreTrainedModel, + VoxtralRealtimeProcessor, + Wav2Vec2BertForCTC, + Wav2Vec2BertForSequenceClassification, + Wav2Vec2BertModel, + Wav2Vec2BertPreTrainedModel, + Wav2Vec2CTCTokenizer, + Wav2Vec2FeatureExtractor, + Wav2Vec2ForAudioFrameClassification, + Wav2Vec2ForCTC, + Wav2Vec2ForSequenceClassification, + Wav2Vec2Model, + Wav2Vec2PreTrainedModel, + Wav2Vec2Processor, + Wav2Vec2ProcessorWithLM, + WavLMForAudioFrameClassification, + WavLMForCTC, + WavLMForSequenceClassification, + WavLMForXVector, + WavLMModel, + WavLMPreTrainedModel, + WeSpeakerFeatureExtractor, + WeSpeakerResNetModel, + WeSpeakerResNetPreTrainedModel, + WhisperFeatureExtractor, + WhisperForConditionalGeneration, + WhisperModel, + WhisperPreTrainedModel, + WhisperProcessor, + WhisperTextStreamer, + WhisperTimeStampLogitsProcessor, + WhisperTokenizer, + XLMForQuestionAnswering, + XLMForSequenceClassification, + XLMForTokenClassification, + XLMModel, + XLMPreTrainedModel, + XLMRobertaForMaskedLM, + XLMRobertaForQuestionAnswering, + XLMRobertaForSequenceClassification, + XLMRobertaForTokenClassification, + XLMRobertaModel, + XLMRobertaPreTrainedModel, + XLMRobertaTokenizer, + XLMTokenizer, + XLMWithLMHeadModel, + XVectorOutput, + YolosFeatureExtractor, + YolosForObjectDetection, + YolosImageProcessor, + YolosModel, + YolosObjectDetectionOutput, + YolosPreTrainedModel, + YoutuForCausalLM, + YoutuModel, + YoutuPreTrainedModel, + ZayaForCausalLM, + ZayaModel, + ZayaPreTrainedModel, + ZeroShotAudioClassificationPipeline, + ZeroShotClassificationPipeline, + ZeroShotImageClassificationPipeline, + ZeroShotObjectDetectionPipeline, + cat, + cos_sim, + dot, + env, + full, + full_like, + interpolate, + interpolate_4d, + layer_norm, + load_audio, + load_image, + load_video, + log_softmax, + matmul, + mean, + mean_pooling, + ones, + ones_like, + permute, + pipeline2 as pipeline, + quantize_embeddings, + rand, + randn, + random, + read_audio, + rfft, + slice2 as slice, + softmax, + stack, + std_mean, + topk, + zeros, + zeros_like +}; +/*! Bundled license information: + +onnxruntime-web/dist/ort.webgpu.bundle.min.mjs: + (*! + * ONNX Runtime Web v1.31.0-dev.20260914-8d85527a0 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + *) +*/ diff --git a/workloads/transformersjs/transformers.js.patch b/workloads/transformersjs/transformers.js.patch deleted file mode 100644 index d489f39a..00000000 --- a/workloads/transformersjs/transformers.js.patch +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/workloads/transformersjs/build/transformers.js b/workloads/transformersjs/build/transformers.js -index b8e1342..0c702e8 100644 ---- a/workloads/transformersjs/build/transformers.js -+++ b/workloads/transformersjs/build/transformers.js -@@ -37868,11 +37868,10 @@ function quantize_embeddings(tensor, precision) { - /******/ - /******/ /* webpack/runtime/publicPath */ - /******/ (() => { --/******/ var scriptUrl; -+/******/ var scriptUrl = ''; - /******/ if (typeof import.meta.url === "string") scriptUrl = import.meta.url - /******/ // When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration - /******/ // or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic. --/******/ if (!scriptUrl) throw new Error("Automatic publicPath is not supported in this browser"); - /******/ scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\?.*$/, "").replace(/\/[^\/]+$/, "/"); - /******/ __webpack_require__.p = scriptUrl; - /******/ })(); diff --git a/workloads/transformersjs/util/package.json b/workloads/transformersjs/util/package.json index 5ba21290..2efbec99 100644 --- a/workloads/transformersjs/util/package.json +++ b/workloads/transformersjs/util/package.json @@ -4,7 +4,7 @@ "author": "Daniel Lehmann ", "license": "MIT", "dependencies": { - "@huggingface/transformers": "^3.7.2", + "@huggingface/transformers": "4.3.2", "wavefile": "^11.0.0" } }