diff --git a/.github/workflows/sync-whisper-transcriber.yml b/.github/workflows/sync-whisper-transcriber.yml new file mode 100644 index 0000000..5b64d3a --- /dev/null +++ b/.github/workflows/sync-whisper-transcriber.yml @@ -0,0 +1,165 @@ +name: Sync Whisper Transcriber + +# Republishes static/utility-apps/whisper-transcriber/ from a release of +# YurMil/ws-speech-text and opens a pull request with the result. +# +# Triggered by that repository's Release workflow (repository_dispatch), or +# manually from the Actions tab when a release needs to be re-pulled. +# +# The artifact is only accepted if its SHA-256 matches the digest published +# with the release, and the sync script re-audits every file before publishing. +# This workflow never builds the transcriber and never downloads model weights. + +on: + repository_dispatch: + types: [whisper-transcriber-release] + workflow_dispatch: + inputs: + tag: + description: Release tag in YurMil/ws-speech-text (e.g. v0.1.0) + required: true + sha256: + description: Expected SHA-256 of the archive (blank = take it from the release) + required: false + +concurrency: + group: sync-whisper-transcriber + cancel-in-progress: false + +permissions: + contents: write + pull-requests: write + +jobs: + sync: + runs-on: ubuntu-latest + env: + SOURCE_REPOSITORY: YurMil/ws-speech-text + TAG: ${{ github.event.client_payload.tag || inputs.tag }} + EXPECTED_SHA256: ${{ github.event.client_payload.sha256 || inputs.sha256 }} + ARCHIVE: ${{ github.event.client_payload.archive }} + steps: + - uses: actions/checkout@v7 + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v6 + with: + node-version-file: .nvmrc + cache: pnpm + + - name: Download release archive + env: + # Reading a public release needs no extra scope; a PAT is only + # required if the source repository is private. + GH_TOKEN: ${{ secrets.SOURCE_RELEASE_TOKEN || github.token }} + run: | + set -euo pipefail + mkdir -p .artifact + archive="${ARCHIVE:-whisper-transcriber-${TAG}.zip}" + gh release download "$TAG" --repo "$SOURCE_REPOSITORY" \ + --pattern "$archive" --pattern "$archive.sha256" --dir .artifact + echo "ARCHIVE=$archive" >> "$GITHUB_ENV" + + - name: Resolve expected checksum + run: | + set -euo pipefail + if [ -z "${EXPECTED_SHA256}" ]; then + # Fall back to the digest published alongside the archive. The + # dispatch payload is preferred: it is produced by the build itself. + EXPECTED_SHA256="$(cut -d' ' -f1 < ".artifact/${ARCHIVE}.sha256")" + echo "Using checksum from the release: ${EXPECTED_SHA256}" + fi + echo "EXPECTED_SHA256=${EXPECTED_SHA256}" >> "$GITHUB_ENV" + + - name: Publish artifact + run: | + node scripts/sync-whisper-transcriber.mjs \ + --archive ".artifact/${ARCHIVE}" \ + --sha256 "${EXPECTED_SHA256}" + + - name: Detect changes + id: diff + run: | + set -euo pipefail + rm -rf .artifact + # --porcelain rather than `git diff`, so a release that only adds a + # newly hashed asset still counts as a change. + if [ -z "$(git status --porcelain -- static/utility-apps/whisper-transcriber)" ]; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "Published artifact is identical to the committed one; nothing to do." + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Install dependencies + if: steps.diff.outputs.changed == 'true' + run: pnpm install --frozen-lockfile + + - name: Typecheck + if: steps.diff.outputs.changed == 'true' + run: pnpm typecheck + + - name: Lint + if: steps.diff.outputs.changed == 'true' + run: pnpm lint + + - name: Build + if: steps.diff.outputs.changed == 'true' + run: pnpm build + env: + DOCUSAURUS_ONBROKENLINKS: throw + SUPABASE_URL: ${{ secrets.SUPABASE_URL }} + SUPABASE_ANON_KEY: ${{ secrets.SUPABASE_ANON_KEY }} + AUTH_REDIRECT_URL: ${{ secrets.AUTH_REDIRECT_URL }} + + - name: Open pull request + if: steps.diff.outputs.changed == 'true' + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + branch="chore/whisper-transcriber-${TAG}" + build_id="$(node -p "require('./static/utility-apps/whisper-transcriber/manifest.json').buildId")" + version="$(node -p "require('./static/utility-apps/whisper-transcriber/manifest.json').version")" + + { + printf 'Publish Whisper Transcriber %s\n\n' "$TAG" + printf 'Artifact from the %s release %s.\n\n' "$SOURCE_REPOSITORY" "$TAG" + printf -- '- version: %s\n' "$version" + printf -- '- build id: %s\n' "$build_id" + printf -- '- archive sha256: %s\n\n' "$EXPECTED_SHA256" + printf 'Verified against the published checksum and re-audited by\n' + printf 'scripts/sync-whisper-transcriber.mjs before publishing.\n' + } > commit-msg.md + + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git checkout -b "$branch" + git add static/utility-apps/whisper-transcriber + git commit -F commit-msg.md + rm -f commit-msg.md + git push --force-with-lease origin "$branch" + + { + printf 'Republishes the embedded Whisper Transcriber from [%s@%s](https://github.com/%s/releases/tag/%s).\n\n' \ + "$SOURCE_REPOSITORY" "$TAG" "$SOURCE_REPOSITORY" "$TAG" + printf '| | |\n|---|---|\n' + printf '| Version | `%s` |\n' "$version" + printf '| Build id | `%s` |\n' "$build_id" + printf '| Archive SHA-256 | `%s` |\n\n' "$EXPECTED_SHA256" + printf 'The archive checksum was verified before extraction, and every file was\n' + printf 're-audited (no symlinks, traversal, source maps or dev references; the entry\n' + printf 'document may only reference packaged relative assets). Typecheck, lint and a\n' + printf 'six-locale production build passed on this branch.\n' + } > pr-body.md + + existing="$(gh pr list --head "$branch" --state open --json number --jq '.[0].number // empty')" + if [ -n "$existing" ]; then + gh pr edit "$existing" --body-file pr-body.md + echo "Updated existing pull request #${existing}" + else + gh pr create --base main --head "$branch" \ + --title "Publish Whisper Transcriber ${TAG}" --body-file pr-body.md + fi + rm -f pr-body.md diff --git a/README.md b/README.md index dcbfa4e..464cabb 100644 --- a/README.md +++ b/README.md @@ -332,6 +332,29 @@ AUTH_REDIRECT_URL=http://localhost:3000/auth/callback 5. Add the catalog name/description to all six `src/i18n/locales/*.ts` dictionaries 6. Place standalone build assets in `static/utility-apps//` if needed +### Embedded apps built in their own repository + +Utilities too heavy to live in the Docusaurus bundle are built elsewhere and +published here as static artifacts. The Whisper Transcriber is the reference +implementation of that pipeline: + +1. Tagging a release in [`YurMil/ws-speech-text`](https://github.com/YurMil/ws-speech-text) + builds the bundle, audits it, and attaches a checksummed archive to a GitHub + release. +2. That workflow sends a `whisper-transcriber-release` `repository_dispatch` here + (secret `SITE_DISPATCH_TOKEN`, set in the source repository). +3. `.github/workflows/sync-whisper-transcriber.yml` downloads the archive, + refuses it unless the SHA-256 matches, republishes + `static/utility-apps/whisper-transcriber/` via + `scripts/sync-whisper-transcriber.mjs`, runs typecheck/lint/build, and opens + a pull request. + +Nothing is deployed without review, and this repository never builds the app or +downloads model weights. The same script publishes from a local checkout during +development (`npm run sync:whisper-transcriber`). + +### Device capabilities + Device capabilities (camera, microphone) are delegated **per utility** through the `iframeAllow` field of `UtilityPageConfig`, paired with a path-scoped `Permissions-Policy` rule in `vercel.json`. Never widen the global policy: the diff --git a/scripts/sync-whisper-transcriber.mjs b/scripts/sync-whisper-transcriber.mjs index dd8a818..5f7d347 100644 --- a/scripts/sync-whisper-transcriber.mjs +++ b/scripts/sync-whisper-transcriber.mjs @@ -3,17 +3,24 @@ // // The transcriber lives in its own repository (YurMil/ws-speech-text) because // it carries Transformers.js and ONNX Runtime Web, which must never enter the -// Docusaurus bundle. This script builds that source tree, audits the produced -// bundle, and republishes it atomically. +// Docusaurus bundle. This script takes a bundle produced there, audits it, and +// republishes it atomically. // // Usage: // npm run sync:whisper-transcriber +// build the sibling checkout and publish it // WHISPER_TRANSCRIBER_DIR=/path/to/ws-speech-text npm run sync:whisper-transcriber -// npm run sync:whisper-transcriber -- --skip-build (reuse an existing dist/) +// build a checkout somewhere else +// npm run sync:whisper-transcriber -- --skip-build +// reuse an existing dist/ +// npm run sync:whisper-transcriber -- --archive dist.zip --sha256 +// publish a release archive, refusing it unless the checksum matches. +// This is the path CI uses; see .github/workflows/sync-whisper-transcriber.yml. import {createHash} from 'node:crypto'; import {spawnSync} from 'node:child_process'; import fs from 'node:fs'; +import os from 'node:os'; import path from 'node:path'; import {fileURLToPath} from 'node:url'; @@ -25,7 +32,6 @@ const DEFAULT_SOURCE_DIR = path.resolve( 'ws-speech-text', ); const SOURCE_DIR = path.resolve(process.env.WHISPER_TRANSCRIBER_DIR || DEFAULT_SOURCE_DIR); -const SOURCE_DIST_DIR = path.join(SOURCE_DIR, 'dist'); const TARGET_DIR = path.join(SITE_ROOT, 'static', 'utility-apps', 'whisper-transcriber'); const STAGING_DIR = `${TARGET_DIR}.staging`; @@ -38,7 +44,16 @@ const FORBIDDEN_PATTERNS = [ /sourceMappingURL/i, ]; +function readFlag(name) { + const index = process.argv.indexOf(name); + return index === -1 ? undefined : process.argv[index + 1]; +} + const skipBuild = process.argv.includes('--skip-build'); +const archivePath = readFlag('--archive'); +const expectedSha256 = readFlag('--sha256'); + +let scratchDir = null; function fail(message) { throw new Error(message); @@ -134,8 +149,8 @@ function readBuildInfo(distDir) { const infoPath = path.join(distDir, 'build-info.json'); assertExists(infoPath, 'ws-speech-text dist/build-info.json'); const info = JSON.parse(fs.readFileSync(infoPath, 'utf8')); - if (!info.buildId || !info.version) { - fail('build-info.json is missing version or buildId.'); + if (!info.buildId || !info.version || !info.buildTime) { + fail('build-info.json is missing version, buildId or buildTime.'); } if (info.buildId === 'unversioned') { fail('Refusing to publish an artifact built outside a git checkout.'); @@ -143,7 +158,38 @@ function readBuildInfo(distDir) { return info; } -function main() { +/** + * Unpacks a release archive after verifying its checksum. The digest is checked + * before anything is extracted, so a tampered or truncated download never + * reaches the filesystem walk. + */ +function extractArchive(archive) { + assertExists(archive, 'release archive'); + + const actual = sha256(archive); + if (!expectedSha256) { + fail('--archive requires --sha256 ; refusing to publish an unverified archive.'); + } + if (actual !== expectedSha256.trim().toLowerCase()) { + fail(`Archive checksum mismatch.\n expected ${expectedSha256}\n actual ${actual}`); + } + console.log(`[whisper-transcriber] Archive checksum verified: ${actual}`); + + scratchDir = fs.mkdtempSync(path.join(os.tmpdir(), 'whisper-transcriber-')); + // bsdtar reads zip archives and is present on Windows, macOS and the runners. + run('tar', ['-xf', path.resolve(archive), '-C', scratchDir]); + + // Accept both a flat archive and one that wraps the files in dist/. + const nested = path.join(scratchDir, 'dist'); + return fs.existsSync(path.join(nested, 'index.html')) ? nested : scratchDir; +} + +/** Produces the directory whose contents should be published. */ +function resolveDistDir() { + if (archivePath) { + return extractArchive(archivePath); + } + assertExists(SOURCE_DIR, 'ws-speech-text source directory'); assertExists(path.join(SOURCE_DIR, 'package.json'), 'ws-speech-text package.json'); @@ -155,15 +201,20 @@ function main() { run('pnpm', ['build'], SOURCE_DIR); } - assertExists(SOURCE_DIST_DIR, 'ws-speech-text dist directory'); - assertExists(path.join(SOURCE_DIST_DIR, 'index.html'), 'ws-speech-text dist/index.html'); + return path.join(SOURCE_DIR, 'dist'); +} + +function main() { + const distDir = resolveDistDir(); + assertExists(distDir, 'transcriber dist directory'); + assertExists(path.join(distDir, 'index.html'), 'transcriber dist/index.html'); - const files = collectFiles(SOURCE_DIST_DIR); + const files = collectFiles(distDir); const assets = files.filter((file) => file !== 'index.html'); - const entryHtml = fs.readFileSync(path.join(SOURCE_DIST_DIR, 'index.html'), 'utf8'); + const entryHtml = fs.readFileSync(path.join(distDir, 'index.html'), 'utf8'); auditEntryHtml(entryHtml, assets); - const {version, buildId} = readBuildInfo(SOURCE_DIST_DIR); + const {version, buildId, buildTime} = readBuildInfo(distDir); // Stage first, then swap, so a failed sync never leaves a half-published app. fs.rmSync(STAGING_DIR, {recursive: true, force: true}); @@ -172,7 +223,7 @@ function main() { const checksums = {}; let totalBytes = 0; for (const relative of assets) { - const source = path.join(SOURCE_DIST_DIR, relative); + const source = path.join(distDir, relative); const destination = path.join(STAGING_DIR, relative); fs.mkdirSync(path.dirname(destination), {recursive: true}); fs.copyFileSync(source, destination); @@ -194,7 +245,9 @@ function main() { name: 'whisper-transcriber', version, buildId, - buildTime: new Date().toISOString(), + // Taken from the source build, not from now(), so republishing the same + // artifact is a no-op and CI can tell whether anything actually changed. + buildTime, entry: 'app.html', assets, checksums, @@ -218,5 +271,9 @@ try { } catch (error) { fs.rmSync(STAGING_DIR, {recursive: true, force: true}); console.error(`[whisper-transcriber] ${error.message}`); - process.exit(1); + process.exitCode = 1; +} finally { + if (scratchDir) { + fs.rmSync(scratchDir, {recursive: true, force: true}); + } } diff --git a/static/utility-apps/whisper-transcriber/app.html b/static/utility-apps/whisper-transcriber/app.html index 65ba537..8b21e22 100644 --- a/static/utility-apps/whisper-transcriber/app.html +++ b/static/utility-apps/whisper-transcriber/app.html @@ -8,7 +8,7 @@ content="Private browser speech-to-text. Audio stays on your device." /> Whisper Transcriber - + diff --git a/static/utility-apps/whisper-transcriber/assets/index-B5C8PNiW.js b/static/utility-apps/whisper-transcriber/assets/index-DA9_-avd.js similarity index 99% rename from static/utility-apps/whisper-transcriber/assets/index-B5C8PNiW.js rename to static/utility-apps/whisper-transcriber/assets/index-DA9_-avd.js index cc5f445..7cf390f 100644 --- a/static/utility-apps/whisper-transcriber/assets/index-B5C8PNiW.js +++ b/static/utility-apps/whisper-transcriber/assets/index-DA9_-avd.js @@ -17,4 +17,4 @@ ${n.text.trim()} ${l.map(i=>`${zg(i.startSeconds)} --> ${zg(i.endSeconds)} ${i.text.trim()} `).join(` -`)}`}function af(l,n,i){const r=new Blob([n],{type:i}),o=URL.createObjectURL(r),u=document.createElement("a");u.href=o,u.download=l,u.click(),URL.revokeObjectURL(o)}function rf(){return`transcript-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}`}const Of=[{id:"whisper-tiny-multilingual-wasm",label:"Whisper Tiny (multilingual)",modelId:"onnx-community/whisper-tiny",revision:"ff4177021cc41f7db950912b73ea4fdf7d01d8e7",multilingual:!0,approximateDownloadBytes:77e6,devices:["wasm","webgpu"],dtypeByDevice:{wasm:"q8",webgpu:"fp32"},chunkLengthSeconds:30,strideLengthSeconds:5,maxDurationSeconds:10800}],yT=Of[0].id;function kT(l){return Of.find(n=>n.id===l)}function $l(l){return l<1e6?`${Math.round(l/1e3)} KB`:`${(l/1e6).toFixed(0)} MB`}class bT{worker=null;generation=0;pending=new Map;requestSeq=0;ensureWorker(){if(this.worker)return this.worker;const n=this.generation,i=new Worker(new URL(""+new URL("whisper.worker-CA5aZLsj.js",import.meta.url).href,import.meta.url),{type:"module"});return i.onmessage=r=>{n===this.generation&&this.handleMessage(r.data)},i.onerror=()=>{n===this.generation&&(this.failAll(new Error("Inference Worker crashed.")),this.hardReset())},this.worker=i,i}nextRequestId(){return this.requestSeq+=1,`req-${this.requestSeq}-${Date.now()}`}handleMessage(n){if(n.protocol!==1)return;const i=this.pending.get(n.requestId);if(i)switch(n.type){case"PROGRESS":i.onProgress?.(n.progress);break;case"READY":case"RESULT":case"DIAGNOSTICS":this.pending.delete(n.requestId),i.resolve(n);break;case"CANCELLED":this.pending.delete(n.requestId),i.reject(Object.assign(new Error("Cancelled"),{code:"CANCELLED"}));break;case"ERROR":this.pending.delete(n.requestId),i.reject(ST(n.error));break}}post(n,i=[],r){const o=this.ensureWorker();return new Promise((u,c)=>{this.pending.set(n.requestId,{resolve:u,reject:c,onProgress:r,kind:n.type}),o.postMessage(n,i)})}prepare(n,i,r){const o=this.nextRequestId();return this.post({protocol:1,type:"PREPARE",requestId:o,profileId:n,runtimePreference:i},[],r).then(u=>({diagnostics:u.diagnostics}))}transcribe(n){const i=this.nextRequestId(),r=n.audio;return this.post({protocol:1,type:"TRANSCRIBE",requestId:i,profileId:n.profileId,runtimePreference:n.runtimePreference,audio:r,options:{language:n.language,task:"transcribe",timestamps:n.timestamps}},[r.buffer],n.onProgress).then(o=>o.result)}async cancel(n){if(this.worker){if(n){const i=this.nextRequestId();try{await this.post({protocol:1,type:"CANCEL",requestId:i,targetRequestId:n})}catch{}}this.hardReset()}}hardReset(){this.generation+=1,this.failAll(Object.assign(new Error("Cancelled"),{code:"CANCELLED"})),this.worker?.terminate(),this.worker=null}dispose(){this.hardReset()}failAll(n){for(const[,i]of this.pending)i.reject(n);this.pending.clear()}}function ST(l){return Object.assign(new Error(l.code),{code:l.code,phase:l.phase,recoverable:l.recoverable,diagnostic:l.diagnostic})}const Qi=new bT;function TT(l,n){if(n)return n.message;if(!l)return"Working…";switch(l.phase){case"download":return l.ratio!=null?`Downloading model… ${Math.round(l.ratio*100)}%`:"Downloading model…";case"runtime-init":return"Initializing runtime…";case"model-init":return"Preparing model…";case"warmup":return"Warming up…";case"inference":return l.approximate?"Transcribing… (approximate)":"Transcribing…";case"finalize":return"Finalizing…";default:return"Working…"}}function ms(l){const n=Math.max(0,Math.floor(l)),i=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return i>0?`${i}:${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`:`${r}:${String(o).padStart(2,"0")}`}function vT(){const[l,n]=tt.useState("idle"),[i,r]=tt.useState("auto"),[o,u]=tt.useState("segment"),[c,d]=tt.useState("auto"),[m,p]=tt.useState(yT),[y,g]=tt.useState(null),[b,T]=tt.useState(null),[w,S]=tt.useState(null),[E,x]=tt.useState("Select an audio/video file or record from the microphone."),[P,_]=tt.useState("neutral"),[D,B]=tt.useState(""),[z,L]=tt.useState(null),[H,R]=tt.useState(null),[X,W]=tt.useState(0),[Z,ie]=tt.useState(!1),ce=tt.useRef(null),re=tt.useRef(null),N=tt.useRef(null),J=tt.useMemo(()=>kT(m),[m]),ae=l==="normalizing"||l==="preparing-model"||l==="transcribing"||l==="cancelling"||l==="recording";tt.useEffect(()=>()=>{ce.current?.abort(),re.current?.cancel(),Qi.dispose()},[]);async function Te(de){ce.current?.abort();const ye=new AbortController;ce.current=ye,n("normalizing"),x("Inspecting media (duration, audio track)…"),_("neutral"),L(null),B(""),T(null),S(null);const je=$0(de);try{const We=await oT(de,{signal:ye.signal});if(ye.signal.aborted)return;if(!We.canDecodeAudio)throw new Ve("AUDIO_DECODE_UNSUPPORTED","decode","This browser cannot decode the audio track via WebCodecs.");const Et=lT(We,We.kind),Jt=[];if(Et&&Jt.push(`Conveyor mode: ${Xe.windowSeconds}s windows, ${Xe.overlapSeconds}s overlap — model stays loaded.`),Et){g({mode:"conveyor",blob:de,mediaKind:We.kind,durationSeconds:We.durationSeconds,warnings:Jt,sourceLabel:We.kind==="video"?"Video file":"Media file",byteLength:We.byteLength,formatName:We.formatName}),n("ready"),x(`Ready · ${We.kind} · ${ms(We.durationSeconds)} · ${$l(We.byteLength)} · windowed pipeline`),_("ok");return}x("Normalizing short clip to mono 16 kHz…");const yn=await nf(de,{signal:ye.signal,maxDurationSeconds:Xe.inlineDecodeMaxSeconds});if(ye.signal.aborted)return;g({mode:"inline",samples:yn.samples,durationSeconds:yn.durationSeconds,warnings:yn.warnings,sourceLabel:je==="video"?"Video file":"Uploaded file"}),n("ready"),x(yn.warnings[0]??`Ready · ${yn.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(yn.warnings.length?"neutral":"ok")}catch(We){if(ye.signal.aborted)return;if(je!=="video"&&de.size<=Xe.inlineDecodeMaxBytes)try{const Jt=await nf(de,{signal:ye.signal,maxDurationSeconds:Xe.inlineDecodeMaxSeconds});if(ye.signal.aborted)return;g({mode:"inline",samples:Jt.samples,durationSeconds:Jt.durationSeconds,warnings:Jt.warnings,sourceLabel:"Uploaded file"}),n("ready"),x(Jt.warnings[0]??`Ready · ${Jt.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(Jt.warnings.length?"neutral":"ok");return}catch{}const Et=We instanceof Ve?We.message:"Could not prepare the selected media.";g(null),n("error"),x(Et),_("error")}}async function Be(de){ce.current?.abort();const ye=new AbortController;ce.current=ye,n("normalizing"),x("Normalizing recording to mono 16 kHz…"),_("neutral"),L(null),B(""),T(null),S(null);try{const je=await nf(de,{signal:ye.signal});if(ye.signal.aborted)return;g({mode:"inline",samples:je.samples,durationSeconds:je.durationSeconds,warnings:je.warnings,sourceLabel:"Microphone recording"}),n("ready"),x(je.warnings[0]??`Ready · ${je.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(je.warnings.length?"neutral":"ok")}catch(je){if(ye.signal.aborted)return;const We=je instanceof Ve?je.message:"Could not prepare the recording.";g(null),n("error"),x(We),_("error")}}async function O(de){de&&await Te(de)}async function Q(de){de.preventDefault(),ie(!1);const ye=de.dataTransfer.files?.[0];ye&&await O(ye)}async function ne(){if(!ae){Pe(!1),n("recording"),W(0),x("Recording… click Stop when finished."),_("neutral");try{const de=await hT(ye=>{W(ye)});re.current=de}catch{n("error"),x("Microphone permission denied or unavailable. File upload still works."),_("error")}}}async function le(){const de=re.current;if(de){re.current=null;try{const ye=await de.stop();await Be(ye)}catch{n("error"),x("Recording failed."),_("error")}}}async function pe(){if(!y||!J)return;const de=new AbortController;ce.current=de,n("preparing-model"),x("Preparing model… first run downloads ~"+$l(J.approximateDownloadBytes)),_("neutral"),T(null),S(null);try{const ye=await Qi.prepare(m,c,T);R(ye.diagnostics),ye.diagnostics.fallbackReasonCode&&x(`WebGPU unavailable — using WASM (${ye.diagnostics.fallbackReasonCode}).`),n("transcribing"),x(y.mode==="conveyor"?"Conveyor transcription started…":"Transcribing…");let je;if(y.mode==="conveyor")je=await dT({blob:y.blob,profileId:m,runtimePreference:c,language:i,timestamps:o,client:Qi,signal:de.signal,onModelProgress:T,onChunkProgress:Et=>{S(Et),T({phase:"inference",status:"running",ratio:Et.ratio,approximate:!0})},onPartialResult:Et=>{L(Et),B(Et.text)}});else{const Et=y.samples.slice();je=await Qi.transcribe({profileId:m,runtimePreference:c,audio:Et,language:i,timestamps:o,onProgress:T})}L(je),B(je.text),n("complete"),T(null),S(null);const We=je.warnings[0];x(We??(y.mode==="conveyor"?"Transcription complete via windowed pipeline. Media stayed on-device.":"Transcription complete. Audio and text stayed in this browser session.")),_(We?"neutral":"ok")}catch(ye){const je=ye&&typeof ye=="object"&&"code"in ye?String(ye.code):"";if(je==="CANCELLED"||ye instanceof Ve&&ye.code==="CANCELLED"){n(y?"ready":"idle"),x("Cancelled."),_("neutral"),T(null),S(null);return}n("error"),x(ye instanceof Ve?ye.message:je?`Transcription failed (${je}).`:"Transcription failed."),_("error"),T(null),S(null)}}async function we(){n("cancelling"),x("Cancelling…"),ce.current?.abort(),ce.current=new AbortController,re.current?.cancel(),re.current=null,await Qi.cancel(),n(y?"ready":"idle"),T(null),S(null),x("Cancelled. Session media still available until Clear."),_("neutral")}function Pe(de=!0){ce.current?.abort(),ce.current=new AbortController,re.current?.cancel(),re.current=null,Qi.hardReset(),g(null),L(null),B(""),T(null),S(null),R(null),W(0),n("idle"),de&&(x("Session cleared. Nothing was saved."),_("neutral")),N.current&&(N.current.value="")}function ht(){const de=mT({text:D,segments:z?.segments??[],durationSeconds:z?.durationSeconds??y?.durationSeconds??0,warnings:z?.warnings??[]});af(`${rf()}.txt`,de,"text/plain;charset=utf-8")}function Ze(){z?.segments.length&&af(`${rf()}.srt`,pT(z.segments),"application/x-subrip")}function Ia(){z?.segments.length&&af(`${rf()}.vtt`,gT(z.segments),"text/vtt")}async function li(){await navigator.clipboard.writeText(D),x("Copied to clipboard."),_("ok")}const oi=w?.ratio??b?.ratio;return te.jsxs("main",{className:"shell",children:[te.jsxs("header",{className:"brand",children:[te.jsx("h1",{children:"Whisper Transcriber"}),te.jsx("p",{children:"Private speech-to-text in your browser. Audio and video are processed in a windowed conveyor (mono 16 kHz chunks) so large files do not load full PCM into memory. The model stays resident across windows."})]}),te.jsxs("section",{className:"panel","aria-labelledby":"input-heading",children:[te.jsx("h2",{id:"input-heading",children:"Input"}),te.jsxs("div",{className:`dropzone${Z?" active":""}`,onDragEnter:de=>{de.preventDefault(),ie(!0)},onDragOver:de=>de.preventDefault(),onDragLeave:()=>ie(!1),onDrop:Q,children:["Drop an audio or video file here, or choose one below.",te.jsxs("div",{className:"field",style:{marginTop:"0.85rem"},children:[te.jsx("label",{htmlFor:"audio-file",children:"Audio / video file"}),te.jsx("input",{id:"audio-file",ref:N,type:"file",accept:"audio/*,video/*,.wav,.mp3,.m4a,.ogg,.webm,.flac,.mp4,.m4v,.mov,.mkv,.avi,.mpeg,.mpg,.ogv",disabled:ae,onChange:de=>{O(de.target.files?.[0]??null)}})]})]}),te.jsxs("div",{className:"actions",children:[l==="recording"?te.jsxs("button",{type:"button",className:"btn danger",onClick:()=>{le()},children:["Stop (",ms(X),")"]}):te.jsx("button",{type:"button",className:"btn secondary",disabled:ae,onClick:()=>{ne()},children:"Record microphone"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:l==="idle"&&!y&&!z,onClick:()=>Pe(),children:"Clear session"})]})]}),te.jsxs("section",{className:"panel","aria-labelledby":"settings-heading",children:[te.jsx("h2",{id:"settings-heading",children:"Settings"}),te.jsxs("div",{className:"row",children:[te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"profile",children:"Model"}),te.jsx("select",{id:"profile",value:m,disabled:ae,onChange:de=>p(de.target.value),children:Of.map(de=>te.jsxs("option",{value:de.id,children:[de.label," (~",$l(de.approximateDownloadBytes),")"]},de.id))})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"language",children:"Language"}),te.jsxs("select",{id:"language",value:i,disabled:ae,onChange:de=>r(de.target.value),children:[te.jsx("option",{value:"auto",children:"Automatic"}),te.jsx("option",{value:"en",children:"English"}),te.jsx("option",{value:"ru",children:"Russian"})]})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"timestamps",children:"Timestamps"}),te.jsxs("select",{id:"timestamps",value:o,disabled:ae,onChange:de=>u(de.target.value),children:[te.jsx("option",{value:"segment",children:"Segment"}),te.jsx("option",{value:"none",children:"Off"})]})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"runtime",children:"Runtime"}),te.jsxs("select",{id:"runtime",value:c,disabled:ae,onChange:de=>d(de.target.value),children:[te.jsx("option",{value:"auto",children:"Auto (WebGPU → WASM)"}),te.jsx("option",{value:"wasm",children:"WASM only"}),te.jsx("option",{value:"webgpu",children:"WebGPU preferred"})]})]})]}),te.jsxs("div",{className:"actions",children:[te.jsx("button",{type:"button",className:"btn",disabled:!y||ae,onClick:()=>{pe()},children:"Transcribe"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!ae||l==="recording",onClick:()=>{we()},children:"Cancel"})]}),te.jsx("div",{className:"status","data-tone":P,role:"status","aria-live":"polite",children:ae&&l!=="recording"?TT(b,w):E}),oi!=null&&te.jsx("div",{className:"progress","aria-hidden":"true",children:te.jsx("span",{style:{width:`${Math.round(Math.min(1,Math.max(0,oi))*100)}%`}})})]}),te.jsxs("section",{className:"panel","aria-labelledby":"result-heading",children:[te.jsx("h2",{id:"result-heading",children:"Transcript"}),te.jsxs("label",{className:"field",htmlFor:"transcript",children:["Editable result",te.jsx("textarea",{id:"transcript",className:"transcript",value:D,onChange:de=>B(de.target.value),placeholder:"Transcript appears here after inference. Large media updates window by window."})]}),te.jsxs("div",{className:"actions",children:[te.jsx("button",{type:"button",className:"btn secondary",disabled:!D,onClick:()=>{li()},children:"Copy"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!D,onClick:ht,children:"Export TXT"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!z?.segments.length,onClick:Ze,children:"Export SRT"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!z?.segments.length,onClick:Ia,children:"Export WebVTT"})]}),!!z?.segments.length&&te.jsx("ul",{className:"segments","aria-label":"Timestamped segments",children:z.segments.map((de,ye)=>te.jsxs("li",{children:[te.jsxs("time",{children:[ms(de.startSeconds),"–",ms(de.endSeconds)]}),te.jsx("span",{children:de.text})]},`${de.startSeconds}-${ye}`))})]}),te.jsxs("section",{className:"panel","aria-labelledby":"diagnostics-heading",children:[te.jsx("h2",{id:"diagnostics-heading",children:"Diagnostics"}),te.jsxs("div",{className:"meta",children:[te.jsxs("span",{children:["phase: ",l]}),te.jsxs("span",{children:["mode: ",y?.mode??"—"]}),te.jsxs("span",{children:["profile: ",J?.id??"—"]}),te.jsxs("span",{children:["source: ",y?.sourceLabel??"—"]}),y?.mode==="conveyor"&&te.jsxs(te.Fragment,{children:[te.jsxs("span",{children:["media: ",y.mediaKind]}),te.jsxs("span",{children:["bytes: ",$l(y.byteLength)]}),te.jsxs("span",{children:["format: ",y.formatName??"—"]})]}),te.jsxs("span",{children:["duration: ",y?ms(y.durationSeconds):"—"]}),te.jsxs("span",{children:["window: ",Xe.windowSeconds,"s / overlap ",Xe.overlapSeconds,"s"]}),te.jsxs("span",{children:["chunk:"," ",w?`${w.chunkIndex+1}/${w.chunkTotal}`:"—"]}),te.jsxs("span",{children:["runtime: ",H?.effectiveRuntime??"—"]}),te.jsxs("span",{children:["requested: ",H?.requestedRuntime??c]}),te.jsxs("span",{children:["prep: ",H?.preparationMs!=null?`${H.preparationMs} ms`:"—"]}),te.jsxs("span",{children:["build: ","0.1.0-prototype"," · ","0d8c0a8b93e2"]})]})]})]})}class wT extends tt.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){}render(){return this.state.hasError?te.jsxs("main",{className:"shell",children:[te.jsx("h1",{children:"Whisper Transcriber"}),te.jsx("p",{role:"alert",children:"Something went wrong. Reload the page to start a new session."}),te.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload"})]}):this.props.children}}Ib.createRoot(document.getElementById("root")).render(te.jsx(tt.StrictMode,{children:te.jsx(wT,{children:te.jsx(vT,{})})})); +`)}`}function af(l,n,i){const r=new Blob([n],{type:i}),o=URL.createObjectURL(r),u=document.createElement("a");u.href=o,u.download=l,u.click(),URL.revokeObjectURL(o)}function rf(){return`transcript-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}`}const Of=[{id:"whisper-tiny-multilingual-wasm",label:"Whisper Tiny (multilingual)",modelId:"onnx-community/whisper-tiny",revision:"ff4177021cc41f7db950912b73ea4fdf7d01d8e7",multilingual:!0,approximateDownloadBytes:77e6,devices:["wasm","webgpu"],dtypeByDevice:{wasm:"q8",webgpu:"fp32"},chunkLengthSeconds:30,strideLengthSeconds:5,maxDurationSeconds:10800}],yT=Of[0].id;function kT(l){return Of.find(n=>n.id===l)}function $l(l){return l<1e6?`${Math.round(l/1e3)} KB`:`${(l/1e6).toFixed(0)} MB`}class bT{worker=null;generation=0;pending=new Map;requestSeq=0;ensureWorker(){if(this.worker)return this.worker;const n=this.generation,i=new Worker(new URL(""+new URL("whisper.worker-ewvZ1MXN.js",import.meta.url).href,import.meta.url),{type:"module"});return i.onmessage=r=>{n===this.generation&&this.handleMessage(r.data)},i.onerror=()=>{n===this.generation&&(this.failAll(new Error("Inference Worker crashed.")),this.hardReset())},this.worker=i,i}nextRequestId(){return this.requestSeq+=1,`req-${this.requestSeq}-${Date.now()}`}handleMessage(n){if(n.protocol!==1)return;const i=this.pending.get(n.requestId);if(i)switch(n.type){case"PROGRESS":i.onProgress?.(n.progress);break;case"READY":case"RESULT":case"DIAGNOSTICS":this.pending.delete(n.requestId),i.resolve(n);break;case"CANCELLED":this.pending.delete(n.requestId),i.reject(Object.assign(new Error("Cancelled"),{code:"CANCELLED"}));break;case"ERROR":this.pending.delete(n.requestId),i.reject(ST(n.error));break}}post(n,i=[],r){const o=this.ensureWorker();return new Promise((u,c)=>{this.pending.set(n.requestId,{resolve:u,reject:c,onProgress:r,kind:n.type}),o.postMessage(n,i)})}prepare(n,i,r){const o=this.nextRequestId();return this.post({protocol:1,type:"PREPARE",requestId:o,profileId:n,runtimePreference:i},[],r).then(u=>({diagnostics:u.diagnostics}))}transcribe(n){const i=this.nextRequestId(),r=n.audio;return this.post({protocol:1,type:"TRANSCRIBE",requestId:i,profileId:n.profileId,runtimePreference:n.runtimePreference,audio:r,options:{language:n.language,task:"transcribe",timestamps:n.timestamps}},[r.buffer],n.onProgress).then(o=>o.result)}async cancel(n){if(this.worker){if(n){const i=this.nextRequestId();try{await this.post({protocol:1,type:"CANCEL",requestId:i,targetRequestId:n})}catch{}}this.hardReset()}}hardReset(){this.generation+=1,this.failAll(Object.assign(new Error("Cancelled"),{code:"CANCELLED"})),this.worker?.terminate(),this.worker=null}dispose(){this.hardReset()}failAll(n){for(const[,i]of this.pending)i.reject(n);this.pending.clear()}}function ST(l){return Object.assign(new Error(l.code),{code:l.code,phase:l.phase,recoverable:l.recoverable,diagnostic:l.diagnostic})}const Qi=new bT;function TT(l,n){if(n)return n.message;if(!l)return"Working…";switch(l.phase){case"download":return l.ratio!=null?`Downloading model… ${Math.round(l.ratio*100)}%`:"Downloading model…";case"runtime-init":return"Initializing runtime…";case"model-init":return"Preparing model…";case"warmup":return"Warming up…";case"inference":return l.approximate?"Transcribing… (approximate)":"Transcribing…";case"finalize":return"Finalizing…";default:return"Working…"}}function ms(l){const n=Math.max(0,Math.floor(l)),i=Math.floor(n/3600),r=Math.floor(n%3600/60),o=n%60;return i>0?`${i}:${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}`:`${r}:${String(o).padStart(2,"0")}`}function vT(){const[l,n]=tt.useState("idle"),[i,r]=tt.useState("auto"),[o,u]=tt.useState("segment"),[c,d]=tt.useState("auto"),[m,p]=tt.useState(yT),[y,g]=tt.useState(null),[b,T]=tt.useState(null),[w,S]=tt.useState(null),[E,x]=tt.useState("Select an audio/video file or record from the microphone."),[P,_]=tt.useState("neutral"),[D,B]=tt.useState(""),[z,L]=tt.useState(null),[H,R]=tt.useState(null),[X,W]=tt.useState(0),[Z,ie]=tt.useState(!1),ce=tt.useRef(null),re=tt.useRef(null),N=tt.useRef(null),J=tt.useMemo(()=>kT(m),[m]),ae=l==="normalizing"||l==="preparing-model"||l==="transcribing"||l==="cancelling"||l==="recording";tt.useEffect(()=>()=>{ce.current?.abort(),re.current?.cancel(),Qi.dispose()},[]);async function Te(de){ce.current?.abort();const ye=new AbortController;ce.current=ye,n("normalizing"),x("Inspecting media (duration, audio track)…"),_("neutral"),L(null),B(""),T(null),S(null);const je=$0(de);try{const We=await oT(de,{signal:ye.signal});if(ye.signal.aborted)return;if(!We.canDecodeAudio)throw new Ve("AUDIO_DECODE_UNSUPPORTED","decode","This browser cannot decode the audio track via WebCodecs.");const Et=lT(We,We.kind),Jt=[];if(Et&&Jt.push(`Conveyor mode: ${Xe.windowSeconds}s windows, ${Xe.overlapSeconds}s overlap — model stays loaded.`),Et){g({mode:"conveyor",blob:de,mediaKind:We.kind,durationSeconds:We.durationSeconds,warnings:Jt,sourceLabel:We.kind==="video"?"Video file":"Media file",byteLength:We.byteLength,formatName:We.formatName}),n("ready"),x(`Ready · ${We.kind} · ${ms(We.durationSeconds)} · ${$l(We.byteLength)} · windowed pipeline`),_("ok");return}x("Normalizing short clip to mono 16 kHz…");const yn=await nf(de,{signal:ye.signal,maxDurationSeconds:Xe.inlineDecodeMaxSeconds});if(ye.signal.aborted)return;g({mode:"inline",samples:yn.samples,durationSeconds:yn.durationSeconds,warnings:yn.warnings,sourceLabel:je==="video"?"Video file":"Uploaded file"}),n("ready"),x(yn.warnings[0]??`Ready · ${yn.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(yn.warnings.length?"neutral":"ok")}catch(We){if(ye.signal.aborted)return;if(je!=="video"&&de.size<=Xe.inlineDecodeMaxBytes)try{const Jt=await nf(de,{signal:ye.signal,maxDurationSeconds:Xe.inlineDecodeMaxSeconds});if(ye.signal.aborted)return;g({mode:"inline",samples:Jt.samples,durationSeconds:Jt.durationSeconds,warnings:Jt.warnings,sourceLabel:"Uploaded file"}),n("ready"),x(Jt.warnings[0]??`Ready · ${Jt.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(Jt.warnings.length?"neutral":"ok");return}catch{}const Et=We instanceof Ve?We.message:"Could not prepare the selected media.";g(null),n("error"),x(Et),_("error")}}async function Be(de){ce.current?.abort();const ye=new AbortController;ce.current=ye,n("normalizing"),x("Normalizing recording to mono 16 kHz…"),_("neutral"),L(null),B(""),T(null),S(null);try{const je=await nf(de,{signal:ye.signal});if(ye.signal.aborted)return;g({mode:"inline",samples:je.samples,durationSeconds:je.durationSeconds,warnings:je.warnings,sourceLabel:"Microphone recording"}),n("ready"),x(je.warnings[0]??`Ready · ${je.durationSeconds.toFixed(1)}s · mono 16 kHz`),_(je.warnings.length?"neutral":"ok")}catch(je){if(ye.signal.aborted)return;const We=je instanceof Ve?je.message:"Could not prepare the recording.";g(null),n("error"),x(We),_("error")}}async function O(de){de&&await Te(de)}async function Q(de){de.preventDefault(),ie(!1);const ye=de.dataTransfer.files?.[0];ye&&await O(ye)}async function ne(){if(!ae){Pe(!1),n("recording"),W(0),x("Recording… click Stop when finished."),_("neutral");try{const de=await hT(ye=>{W(ye)});re.current=de}catch{n("error"),x("Microphone permission denied or unavailable. File upload still works."),_("error")}}}async function le(){const de=re.current;if(de){re.current=null;try{const ye=await de.stop();await Be(ye)}catch{n("error"),x("Recording failed."),_("error")}}}async function pe(){if(!y||!J)return;const de=new AbortController;ce.current=de,n("preparing-model"),x("Preparing model… first run downloads ~"+$l(J.approximateDownloadBytes)),_("neutral"),T(null),S(null);try{const ye=await Qi.prepare(m,c,T);R(ye.diagnostics),ye.diagnostics.fallbackReasonCode&&x(`WebGPU unavailable — using WASM (${ye.diagnostics.fallbackReasonCode}).`),n("transcribing"),x(y.mode==="conveyor"?"Conveyor transcription started…":"Transcribing…");let je;if(y.mode==="conveyor")je=await dT({blob:y.blob,profileId:m,runtimePreference:c,language:i,timestamps:o,client:Qi,signal:de.signal,onModelProgress:T,onChunkProgress:Et=>{S(Et),T({phase:"inference",status:"running",ratio:Et.ratio,approximate:!0})},onPartialResult:Et=>{L(Et),B(Et.text)}});else{const Et=y.samples.slice();je=await Qi.transcribe({profileId:m,runtimePreference:c,audio:Et,language:i,timestamps:o,onProgress:T})}L(je),B(je.text),n("complete"),T(null),S(null);const We=je.warnings[0];x(We??(y.mode==="conveyor"?"Transcription complete via windowed pipeline. Media stayed on-device.":"Transcription complete. Audio and text stayed in this browser session.")),_(We?"neutral":"ok")}catch(ye){const je=ye&&typeof ye=="object"&&"code"in ye?String(ye.code):"";if(je==="CANCELLED"||ye instanceof Ve&&ye.code==="CANCELLED"){n(y?"ready":"idle"),x("Cancelled."),_("neutral"),T(null),S(null);return}n("error"),x(ye instanceof Ve?ye.message:je?`Transcription failed (${je}).`:"Transcription failed."),_("error"),T(null),S(null)}}async function we(){n("cancelling"),x("Cancelling…"),ce.current?.abort(),ce.current=new AbortController,re.current?.cancel(),re.current=null,await Qi.cancel(),n(y?"ready":"idle"),T(null),S(null),x("Cancelled. Session media still available until Clear."),_("neutral")}function Pe(de=!0){ce.current?.abort(),ce.current=new AbortController,re.current?.cancel(),re.current=null,Qi.hardReset(),g(null),L(null),B(""),T(null),S(null),R(null),W(0),n("idle"),de&&(x("Session cleared. Nothing was saved."),_("neutral")),N.current&&(N.current.value="")}function ht(){const de=mT({text:D,segments:z?.segments??[],durationSeconds:z?.durationSeconds??y?.durationSeconds??0,warnings:z?.warnings??[]});af(`${rf()}.txt`,de,"text/plain;charset=utf-8")}function Ze(){z?.segments.length&&af(`${rf()}.srt`,pT(z.segments),"application/x-subrip")}function Ia(){z?.segments.length&&af(`${rf()}.vtt`,gT(z.segments),"text/vtt")}async function li(){await navigator.clipboard.writeText(D),x("Copied to clipboard."),_("ok")}const oi=w?.ratio??b?.ratio;return te.jsxs("main",{className:"shell",children:[te.jsxs("header",{className:"brand",children:[te.jsx("h1",{children:"Whisper Transcriber"}),te.jsx("p",{children:"Private speech-to-text in your browser. Audio and video are processed in a windowed conveyor (mono 16 kHz chunks) so large files do not load full PCM into memory. The model stays resident across windows."})]}),te.jsxs("section",{className:"panel","aria-labelledby":"input-heading",children:[te.jsx("h2",{id:"input-heading",children:"Input"}),te.jsxs("div",{className:`dropzone${Z?" active":""}`,onDragEnter:de=>{de.preventDefault(),ie(!0)},onDragOver:de=>de.preventDefault(),onDragLeave:()=>ie(!1),onDrop:Q,children:["Drop an audio or video file here, or choose one below.",te.jsxs("div",{className:"field",style:{marginTop:"0.85rem"},children:[te.jsx("label",{htmlFor:"audio-file",children:"Audio / video file"}),te.jsx("input",{id:"audio-file",ref:N,type:"file",accept:"audio/*,video/*,.wav,.mp3,.m4a,.ogg,.webm,.flac,.mp4,.m4v,.mov,.mkv,.avi,.mpeg,.mpg,.ogv",disabled:ae,onChange:de=>{O(de.target.files?.[0]??null)}})]})]}),te.jsxs("div",{className:"actions",children:[l==="recording"?te.jsxs("button",{type:"button",className:"btn danger",onClick:()=>{le()},children:["Stop (",ms(X),")"]}):te.jsx("button",{type:"button",className:"btn secondary",disabled:ae,onClick:()=>{ne()},children:"Record microphone"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:l==="idle"&&!y&&!z,onClick:()=>Pe(),children:"Clear session"})]})]}),te.jsxs("section",{className:"panel","aria-labelledby":"settings-heading",children:[te.jsx("h2",{id:"settings-heading",children:"Settings"}),te.jsxs("div",{className:"row",children:[te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"profile",children:"Model"}),te.jsx("select",{id:"profile",value:m,disabled:ae,onChange:de=>p(de.target.value),children:Of.map(de=>te.jsxs("option",{value:de.id,children:[de.label," (~",$l(de.approximateDownloadBytes),")"]},de.id))})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"language",children:"Language"}),te.jsxs("select",{id:"language",value:i,disabled:ae,onChange:de=>r(de.target.value),children:[te.jsx("option",{value:"auto",children:"Automatic"}),te.jsx("option",{value:"en",children:"English"}),te.jsx("option",{value:"ru",children:"Russian"})]})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"timestamps",children:"Timestamps"}),te.jsxs("select",{id:"timestamps",value:o,disabled:ae,onChange:de=>u(de.target.value),children:[te.jsx("option",{value:"segment",children:"Segment"}),te.jsx("option",{value:"none",children:"Off"})]})]}),te.jsxs("div",{className:"field",children:[te.jsx("label",{htmlFor:"runtime",children:"Runtime"}),te.jsxs("select",{id:"runtime",value:c,disabled:ae,onChange:de=>d(de.target.value),children:[te.jsx("option",{value:"auto",children:"Auto (WebGPU → WASM)"}),te.jsx("option",{value:"wasm",children:"WASM only"}),te.jsx("option",{value:"webgpu",children:"WebGPU preferred"})]})]})]}),te.jsxs("div",{className:"actions",children:[te.jsx("button",{type:"button",className:"btn",disabled:!y||ae,onClick:()=>{pe()},children:"Transcribe"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!ae||l==="recording",onClick:()=>{we()},children:"Cancel"})]}),te.jsx("div",{className:"status","data-tone":P,role:"status","aria-live":"polite",children:ae&&l!=="recording"?TT(b,w):E}),oi!=null&&te.jsx("div",{className:"progress","aria-hidden":"true",children:te.jsx("span",{style:{width:`${Math.round(Math.min(1,Math.max(0,oi))*100)}%`}})})]}),te.jsxs("section",{className:"panel","aria-labelledby":"result-heading",children:[te.jsx("h2",{id:"result-heading",children:"Transcript"}),te.jsxs("label",{className:"field",htmlFor:"transcript",children:["Editable result",te.jsx("textarea",{id:"transcript",className:"transcript",value:D,onChange:de=>B(de.target.value),placeholder:"Transcript appears here after inference. Large media updates window by window."})]}),te.jsxs("div",{className:"actions",children:[te.jsx("button",{type:"button",className:"btn secondary",disabled:!D,onClick:()=>{li()},children:"Copy"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!D,onClick:ht,children:"Export TXT"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!z?.segments.length,onClick:Ze,children:"Export SRT"}),te.jsx("button",{type:"button",className:"btn secondary",disabled:!z?.segments.length,onClick:Ia,children:"Export WebVTT"})]}),!!z?.segments.length&&te.jsx("ul",{className:"segments","aria-label":"Timestamped segments",children:z.segments.map((de,ye)=>te.jsxs("li",{children:[te.jsxs("time",{children:[ms(de.startSeconds),"–",ms(de.endSeconds)]}),te.jsx("span",{children:de.text})]},`${de.startSeconds}-${ye}`))})]}),te.jsxs("section",{className:"panel","aria-labelledby":"diagnostics-heading",children:[te.jsx("h2",{id:"diagnostics-heading",children:"Diagnostics"}),te.jsxs("div",{className:"meta",children:[te.jsxs("span",{children:["phase: ",l]}),te.jsxs("span",{children:["mode: ",y?.mode??"—"]}),te.jsxs("span",{children:["profile: ",J?.id??"—"]}),te.jsxs("span",{children:["source: ",y?.sourceLabel??"—"]}),y?.mode==="conveyor"&&te.jsxs(te.Fragment,{children:[te.jsxs("span",{children:["media: ",y.mediaKind]}),te.jsxs("span",{children:["bytes: ",$l(y.byteLength)]}),te.jsxs("span",{children:["format: ",y.formatName??"—"]})]}),te.jsxs("span",{children:["duration: ",y?ms(y.durationSeconds):"—"]}),te.jsxs("span",{children:["window: ",Xe.windowSeconds,"s / overlap ",Xe.overlapSeconds,"s"]}),te.jsxs("span",{children:["chunk:"," ",w?`${w.chunkIndex+1}/${w.chunkTotal}`:"—"]}),te.jsxs("span",{children:["runtime: ",H?.effectiveRuntime??"—"]}),te.jsxs("span",{children:["requested: ",H?.requestedRuntime??c]}),te.jsxs("span",{children:["prep: ",H?.preparationMs!=null?`${H.preparationMs} ms`:"—"]}),te.jsxs("span",{children:["build: ","0.1.0-prototype"," · ","c53387ee8485"]})]})]})]})}class wT extends tt.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(n,i){}render(){return this.state.hasError?te.jsxs("main",{className:"shell",children:[te.jsx("h1",{children:"Whisper Transcriber"}),te.jsx("p",{role:"alert",children:"Something went wrong. Reload the page to start a new session."}),te.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload"})]}):this.props.children}}Ib.createRoot(document.getElementById("root")).render(te.jsx(tt.StrictMode,{children:te.jsx(wT,{children:te.jsx(vT,{})})})); diff --git a/static/utility-apps/whisper-transcriber/assets/whisper.worker-CA5aZLsj.js b/static/utility-apps/whisper-transcriber/assets/whisper.worker-ewvZ1MXN.js similarity index 90% rename from static/utility-apps/whisper-transcriber/assets/whisper.worker-CA5aZLsj.js rename to static/utility-apps/whisper-transcriber/assets/whisper.worker-ewvZ1MXN.js index 522d811..9a1dcbe 100644 --- a/static/utility-apps/whisper-transcriber/assets/whisper.worker-CA5aZLsj.js +++ b/static/utility-apps/whisper-transcriber/assets/whisper.worker-ewvZ1MXN.js @@ -1,13 +1,13 @@ -const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=ii.get(e);if(s===void 0)ii.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const n=Pn.indexOf(e);n!==-1&&Pn.splice(n,1);for(let o=0;o{const r=ii.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Tx=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Pn:t;let n;const o=[],i=new Set;for(const l of s){const c=await xx(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]},Ex="1.21.0";let Y_="warning";const vs={wasm:{},webgl:{},webgpu:{},versions:{common:Ex},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}`);Y_=e}},get logLevel(){return Y_}};Object.defineProperty(vs,"logLevel",{enumerable:!0});const Px=vs,Cx=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);const i=r?.format!==void 0?r.format:"RGB",a=r?.norm;let l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));const p=o*n;let d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm;let c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const u=4;let f=0,_=1,y=2,k=3,w=0,v=d,I=d*2,T=-1;a==="RGBA"?(w=0,v=d,I=d*2,T=d*3):a==="RGB"?(w=0,v=d,I=d*2):a==="RBG"&&(w=0,I=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,n=r.norm??{mean:255,bias:0};let o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let d=4,u=0,f=1,_=2,y=3,k=0,w=c,v=c*2,I=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?I=c*3:l==="RBG"?(k=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,k=c*2);for(let b=0;b{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const u=l();u.width=d,u.height=p;const f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){const u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,ql(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{const u=l(),f=c(u);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);const y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(ql(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ql(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},$x=(e,r)=>{const{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new ls({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},kx=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new ls({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Ax=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new ls({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Fx=(e,r,t)=>new ls({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),ao=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),li=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Z_=!1;const Ox=()=>{if(!Z_){Z_=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(ao.set("int64",BigInt64Array),li.set(BigInt64Array,"int64")),r&&(ao.set("uint64",BigUint64Array),li.set(BigUint64Array,"uint64")),s?(ao.set("float16",t),li.set(t,"float16")):ao.set("float16",Uint16Array)}},Dx=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new ls(e.type,e.data,r);case"cpu-pinned":return new ls({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new ls({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new ls({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new ls({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let ls=class{constructor(r,t,s){Ox();let n,o;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,n=r.type,o=r.dims,r.location){case"cpu-pinned":{const a=ao.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(n=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const c=ao.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(t,BigInt):a=c.from(t)}else if(t instanceof c)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof r[0];if(c==="string")n="string",a=r;else if(c==="boolean")n="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(r);else{const c=li.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);n=c,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=a,this.dataLocation="cpu"}const i=Dx(o);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=i}static async fromImage(r,t){return Ix(r,t)}static fromTexture(r,t){return $x(r,t)}static fromGpuBuffer(r,t){return kx(r,t)}static fromMLTensor(r,t){return Ax(r,t)}static fromPinnedBuffer(r,t,s){return Fx(r,t,s)}toDataURL(r){return Cx(this,r)}toImageData(r){return Sx(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Lx(this,r)}};const so=ls,Ow=(e,r)=>{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||console.timeStamp(`${e}::ORT::${r}`)},Dw=(e,r)=>{const t=new Error().stack?.split(/\r\n|\r|\n/g)||[];let s=!1;for(let n=0;n{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||Dw("BEGIN",e)},Xc=e=>{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||Dw("END",e)};let zx=class Lw{constructor(r){this.handler=r}async run(r,t,s){Qc();const n={};let o={};if(typeof r!="object"||r===null||r instanceof so||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof so)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const u=t[d];(u===null||u instanceof so)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(const c of this.outputNames)n[c]=null;const a=await this.handler.run(r,n,o),l={};for(const c in a)if(Object.hasOwnProperty.call(a,c)){const p=a[c];p instanceof so?l[c]=p:l[c]=new so(p.type,p.data,p.dims)}return Xc(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Qc();let o,i={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Tx(i),c=await a.createInferenceSessionHandler(o,l);return Xc(),new Lw(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const Bx=zx;var Rx=Object.freeze({__proto__:null,InferenceSession:Bx,TRACE:Ow,TRACE_FUNC_BEGIN:Qc,TRACE_FUNC_END:Xc,Tensor:so,env:Px,registerBackend:vx});var mu=Object.defineProperty,Nx=Object.getOwnPropertyDescriptor,jx=Object.getOwnPropertyNames,Vx=Object.prototype.hasOwnProperty,Ux=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),uo=(e,r)=>{for(var t in r)mu(e,t,{get:r[t],enumerable:!0})},Wx=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of jx(r))!Vx.call(e,n)&&n!==t&&mu(e,n,{get:()=>r[n],enumerable:!(s=Nx(r,n))||s.enumerable});return e},Jo=e=>Wx(mu({},"__esModule",{value:!0}),e),Lo,nn,In,ef,zw,Bw=Ve(()=>{Lo=new Map,nn=[],In=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Lo.get(e);if(s===void 0)Lo.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let n=nn.indexOf(e);n!==-1&&nn.splice(n,1);for(let o=0;o{let r=Lo.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},zw=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?nn:t,n,o=[],i=new Set;for(let l of s){let c=await ef(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]}}),Gx=Ve(()=>{Bw()}),Rw,Kx=Ve(()=>{Rw="1.22.0-dev.20250409-89f8206ba4"}),Ql,is,Nw=Ve(()=>{Kx(),Ql="warning",is={wasm:{},webgl:{},webgpu:{},versions:{common:Rw},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}`);Ql=e}},get logLevel(){return Ql}},Object.defineProperty(is,"logLevel",{enumerable:!0})}),Jt,Hx=Ve(()=>{Nw(),Jt=is}),jw,Vw,qx=Ve(()=>{jw=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);let i=r?.format!==void 0?r.format:"RGB",a=r?.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=o*n,d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,f=0,_=1,y=2,k=3,w=0,v=d,I=d*2,T=-1;a==="RGBA"?(w=0,v=d,I=d*2,T=d*3):a==="RGB"?(w=0,v=d,I=d*2):a==="RBG"&&(w=0,I=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{hu(),Ha=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,n=r.norm??{mean:255,bias:0},o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,u=0,f=1,_=2,y=3,k=0,w=c,v=c*2,I=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?I=c*3:l==="RBG"?(k=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,k=c*2);for(let T=0;T{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let u=l();u.width=d,u.height=p;let f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,Ha(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let u=l(),f=c(u);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);let y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Ha(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ha(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Ww=(e,r)=>{let{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new Zr({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},Gw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Zr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Kw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Zr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Hw=(e,r,t)=>new Zr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),Cn,Ko,Xl,qw,Xx=Ve(()=>{Cn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Xl=!1,qw=()=>{if(!Xl){Xl=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Cn.set("int64",BigInt64Array),Ko.set(BigInt64Array,"int64")),r&&(Cn.set("uint64",BigUint64Array),Ko.set(BigUint64Array,"uint64")),s?(Cn.set("float16",t),Ko.set(t,"float16")):Cn.set("float16",Uint16Array)}}}),Qw,Xw,Jx=Ve(()=>{hu(),Qw=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Zr(e.type,e.data,r);case"cpu-pinned":return new Zr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Zr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Zr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Zr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Zr,hu=Ve(()=>{qx(),Qx(),Xx(),Jx(),Zr=class{constructor(e,r,t){qw();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let i=Cn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=Cn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=Ko.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");n=a,this.cpuData=i,this.dataLocation="cpu"}let o=Qw(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(e,r){return Uw(e,r)}static fromTexture(e,r){return Ww(e,r)}static fromGpuBuffer(e,r){return Gw(e,r)}static fromMLTensor(e,r){return Kw(e,r)}static fromPinnedBuffer(e,r,t){return Hw(e,r,t)}toDataURL(e){return jw(this,e)}toImageData(e){return Vw(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xw(this,e)}}}),ys,Jw=Ve(()=>{hu(),ys=Zr}),Yo,Jl,Ts,us,Yw=Ve(()=>{Nw(),Yo=(e,r)=>{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||console.timeStamp(`${e}::ORT::${r}`)},Jl=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||Jl("BEGIN",e)},us=e=>{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||Jl("END",e)}}),Zw,Yx=Ve(()=>{Bw(),Jw(),Yw(),Zw=class eb{constructor(r){this.handler=r}async run(r,t,s){Ts();let n={},o={};if(typeof r!="object"||r===null||r instanceof ys||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ys)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let u=t[d];(u===null||u instanceof ys)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(let c of this.outputNames)n[c]=null;let a=await this.handler.run(r,n,o),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof ys?l[c]=p:l[c]=new ys(p.type,p.data,p.dims)}return us(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Ts();let o,i={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await zw(i),c=await a.createInferenceSessionHandler(o,l);return us(),new eb(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}}}),_u,Zx=Ve(()=>{Yx(),_u=Zw}),eT=Ve(()=>{}),tT=Ve(()=>{}),rT=Ve(()=>{}),sT=Ve(()=>{}),tb={};uo(tb,{InferenceSession:()=>_u,TRACE:()=>Yo,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>us,Tensor:()=>ys,env:()=>Jt,registerBackend:()=>In});var Es=Ve(()=>{Gx(),Hx(),Zx(),Jw(),eT(),tT(),Yw(),rT(),sT()}),fu=Ve(()=>{}),rb={};uo(rb,{default:()=>sb});var Yl,Zl,sb,nT=Ve(()=>{lv(),Fn(),gu(),Yl="ort-wasm-proxy-worker",Zl=globalThis.self?.name===Yl,Zl&&(self.onmessage=e=>{let{type:r,in:t}=e.data;try{switch(r){case"init-wasm":Mu(t.wasm).then(()=>{Lu(t).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:n}=t;zu(n,s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:s}=t,n=gi(s);postMessage({type:r,out:n});break}case"create":{let{model:s,options:n}=t;Bu(s,n).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":Ru(t),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:i,options:a}=t;Nu(s,n,o,i,new Array(i.length).fill(null),a).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:l},Vu([...o,...l]))},l=>{postMessage({type:r,err:l})});break}case"end-profiling":ju(t),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),sb=Zl?null:e=>new Worker(e??Yr,{type:"module",name:Yl})}),nb={};uo(nb,{default:()=>ob});var ec,tc,ob,tf,oT=Ve(()=>{tc=(ec=import.meta.url,async function(e={}){var r,t,s=e,n=new Promise((h,P)=>{r=h,t=P}),o=typeof window=="object",i=typeof WorkerGlobalScope<"u",a=i&&self.name?.startsWith("em-pthread");s.mountExternalData=(h,P)=>{h.startsWith("./")&&(h=h.substring(2)),(s.Eb||(s.Eb=new Map)).set(h,P)},s.unmountExternalData=()=>{delete s.Eb};var l=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...P)=>{try{if(s.Fb)throw Error("Session already started");let A=s.Fb={dc:P[0],errors:[]},L=await h(...P);if(s.Fb!==A)throw Error("Session mismatch");s.Jb?.flush();let V=A.errors;if(0Pe),0{if(h==="webgpu"){[s.Jb,s.Ub,s.Yb,s.Kb,s.Xb,s.jb,s.Zb,s.ac,s.Vb,s.Wb,s.$b]=P;let A=s.Jb;s.jsepRegisterBuffer=(L,V,ie,Pe)=>A.registerBuffer(L,V,ie,Pe),s.jsepGetBuffer=L=>A.getBuffer(L),s.jsepCreateDownloader=(L,V,ie)=>A.createDownloader(L,V,ie),s.jsepOnCreateSession=L=>{A.onCreateSession(L)},s.jsepOnReleaseSession=L=>{A.onReleaseSession(L)},s.jsepOnRunStart=L=>A.onRunStart(L),s.bc=(L,V)=>{A.upload(L,V)}}else if(h==="webnn"){let A=P[0];[s.nc,s.Nb,s.webnnEnsureTensor,s.Ob,s.webnnDownloadTensor]=P.slice(1),s.webnnReleaseTensorId=s.Nb,s.webnnUploadTensor=s.Ob,s.webnnOnRunStart=L=>A.onRunStart(L),s.webnnOnRunEnd=A.onRunEnd.bind(A),s.webnnRegisterMLContext=(L,V)=>{A.registerMLContext(L,V)},s.webnnOnReleaseSession=L=>{A.onReleaseSession(L)},s.webnnCreateMLTensorDownloader=(L,V)=>A.createMLTensorDownloader(L,V),s.webnnRegisterMLTensor=(L,V,ie,Pe)=>A.registerMLTensor(L,V,ie,Pe),s.webnnCreateMLContext=L=>A.createMLContext(L),s.webnnRegisterMLConstant=(L,V,ie,Pe,Be,Qe)=>A.registerMLConstant(L,V,ie,Pe,Be,s.Eb,Qe),s.webnnRegisterGraphInput=A.registerGraphInput.bind(A),s.webnnIsGraphInput=A.isGraphInput.bind(A),s.webnnCreateTemporaryTensor=A.createTemporaryTensor.bind(A),s.webnnIsInt64Supported=A.isInt64Supported.bind(A)}};let p=()=>{let h=(P,A,L)=>(...V)=>{let ie=Ht,Pe=A?.();V=P(...V);let Be=A?.();return Pe!==Be&&(P=Be,L(Pe),A=L=null),Ht!=ie?new Promise((Qe,at)=>{hr={resolve:Qe,reject:at}}):V};(()=>{for(let P of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])s[P]=h(s[P],()=>s[P],A=>s[P]=A)})(),c!==void 0&&(s._OrtRun=c(s._OrtRun),s._OrtRunWithBinding=c(s._OrtRunWithBinding)),p=void 0};s.asyncInit=()=>{p?.()};var d,u,f=Object.assign({},s),_=(h,P)=>{throw P},y="";(o||i)&&(i?y=self.location.href:typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),ec&&(y=ec),y=y.startsWith("blob:")?"":y.slice(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1),i&&(u=h=>{var P=new XMLHttpRequest;return P.open("GET",h,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),d=async h=>{if(le(h))return new Promise((A,L)=>{var V=new XMLHttpRequest;V.open("GET",h,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?A(V.response):L(V.status)},V.onerror=L,V.send(null)});var P=await fetch(h,{credentials:"same-origin"});if(P.ok)return P.arrayBuffer();throw Error(P.status+" : "+P.url)});var k=console.log.bind(console),w=console.error.bind(console),v=k,I=w;Object.assign(s,f),f=null;var T,b,E,x,S,O,F,H,W,B,Y,X,J,re=s.wasmBinary,ne=!1,le=h=>h.startsWith("file://");function pe(){return T.buffer!=x.buffer&&Te(),x}function oe(){return T.buffer!=x.buffer&&Te(),S}function K(){return T.buffer!=x.buffer&&Te(),O}function N(){return T.buffer!=x.buffer&&Te(),F}function D(){return T.buffer!=x.buffer&&Te(),H}function te(){return T.buffer!=x.buffer&&Te(),W}function he(){return T.buffer!=x.buffer&&Te(),B}function Ae(){return T.buffer!=x.buffer&&Te(),J}if(a){let h=function(P){try{var A=P.data,L=A.Bb;if(L==="load"){let V=[];self.onmessage=ie=>V.push(ie),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ie of V)h(ie);self.onmessage=h};for(let ie of A.Rb)s[ie]&&!s[ie].proxy||(s[ie]=(...Pe)=>{postMessage({Bb:"callHandler",Qb:ie,args:Pe})},ie=="print"&&(v=s[ie]),ie=="printErr"&&(I=s[ie]));T=A.kc,Te(),Ie(A.lc)}else if(L==="run"){qs(A.Ab),fn(A.Ab,0,0,1,0,0),Or(),ee(A.Ab),je||(mn(),je=!0);try{Qs(A.fc,A.Hb)}catch(V){if(V!="unwind")throw V}}else A.target!=="setimmediate"&&(L==="checkMailbox"?je&&se():L&&(I(`worker: received unknown command ${L}`),I(A)))}catch(V){throw Po(),V}};var Ie,je=!1;I=function(...P){P=P.join(" "),console.error(P)},self.alert=function(...P){postMessage({Bb:"alert",text:P.join(" "),ic:hn()})},self.onunhandledrejection=P=>{throw P.reason||P},self.onmessage=h}function Te(){var h=T.buffer;s.HEAP8=x=new Int8Array(h),s.HEAP16=O=new Int16Array(h),s.HEAPU8=S=new Uint8Array(h),s.HEAPU16=F=new Uint16Array(h),s.HEAP32=H=new Int32Array(h),s.HEAPU32=W=new Uint32Array(h),s.HEAPF32=B=new Float32Array(h),s.HEAPF64=J=new Float64Array(h),s.HEAP64=Y=new BigInt64Array(h),s.HEAPU64=X=new BigUint64Array(h)}function Q(){a?startWorker(s):dt.Ca()}a||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Te());var z,de=0,be=null;function ve(){if(--de==0&&be){var h=be;be=null,h()}}function xe(h){throw I(h="Aborted("+h+")"),ne=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),t(h),h}function Ce(){return{a:{L:fe,Aa:De,b:or,$:Qr,A:Ps,pa:Cs,X:Ss,Z:C,qa:q,na:R,ga:G,ma:Z,J:ce,Y:ye,V:et,oa:ut,W:He,va:Tt,E:Is,Q:$s,O:Rs,D:As,u:Fs,r:ss,P:Nr,z:Dn,R:ue,ja:$,T:Me,aa:Xe,M:Je,F:Ye,ia:ee,sa:Ke,t:rr,Ba:br,w:ps,o:os,l:_r,c:ts,n:Ur,j:ra,v:sa,p:na,f:oa,s:Ys,m:aa,e:ia,k:la,i:ca,g:ua,d:Zs,da,ea:pa,fa:fo,ba:go,ca:Mo,N:Ln,xa:ha,ua:bi,h:bo,C:Rn,G:_a,ta:wo,x:fa,ra:ga,U:Ma,q:ma,y:wa,K:ba,S:yo,za:ya,ya:jn,ka:Ls,la:vo,_:Oe,B:va,I:xo,ha:xa,H:Wn,a:T,wa:Ze}}}var ge={829644:(h,P,A,L,V)=>{if(s===void 0||!s.Eb)return 1;if((h=qt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=s.Eb.get(h)))return 2;if(P=Number(P>>>0),A=Number(A>>>0),L=Number(L>>>0),P+A>h.byteLength)return 3;try{let ie=h.subarray(P,P+A);switch(V){case 0:oe().set(ie,L>>>0);break;case 1:s.mc?s.mc(L,ie):s.bc(L,ie);break;default:return 4}return 0}catch{return 4}},830468:(h,P,A)=>{s.Ob(h,oe().subarray(P>>>0,P+A>>>0))},830532:()=>s.nc(),830574:h=>{s.Nb(h)},830611:()=>{s.Vb()},830642:()=>{s.Wb()},830671:()=>{s.$b()},830696:h=>s.Ub(h),830729:h=>s.Yb(h),830761:(h,P,A)=>{s.Kb(Number(h),Number(P),Number(A),!0)},830824:(h,P,A)=>{s.Kb(Number(h),Number(P),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{s.jb("Abs",h,void 0)},830989:h=>{s.jb("Neg",h,void 0)},831040:h=>{s.jb("Floor",h,void 0)},831093:h=>{s.jb("Ceil",h,void 0)},831145:h=>{s.jb("Reciprocal",h,void 0)},831203:h=>{s.jb("Sqrt",h,void 0)},831255:h=>{s.jb("Exp",h,void 0)},831306:h=>{s.jb("Erf",h,void 0)},831357:h=>{s.jb("Sigmoid",h,void 0)},831412:(h,P,A)=>{s.jb("HardSigmoid",h,{alpha:P,beta:A})},831491:h=>{s.jb("Log",h,void 0)},831542:h=>{s.jb("Sin",h,void 0)},831593:h=>{s.jb("Cos",h,void 0)},831644:h=>{s.jb("Tan",h,void 0)},831695:h=>{s.jb("Asin",h,void 0)},831747:h=>{s.jb("Acos",h,void 0)},831799:h=>{s.jb("Atan",h,void 0)},831851:h=>{s.jb("Sinh",h,void 0)},831903:h=>{s.jb("Cosh",h,void 0)},831955:h=>{s.jb("Asinh",h,void 0)},832008:h=>{s.jb("Acosh",h,void 0)},832061:h=>{s.jb("Atanh",h,void 0)},832114:h=>{s.jb("Tanh",h,void 0)},832166:h=>{s.jb("Not",h,void 0)},832217:(h,P,A)=>{s.jb("Clip",h,{min:P,max:A})},832286:h=>{s.jb("Clip",h,void 0)},832338:(h,P)=>{s.jb("Elu",h,{alpha:P})},832396:h=>{s.jb("Gelu",h,void 0)},832448:h=>{s.jb("Relu",h,void 0)},832500:(h,P)=>{s.jb("LeakyRelu",h,{alpha:P})},832564:(h,P)=>{s.jb("ThresholdedRelu",h,{alpha:P})},832634:(h,P)=>{s.jb("Cast",h,{to:P})},832692:h=>{s.jb("Add",h,void 0)},832743:h=>{s.jb("Sub",h,void 0)},832794:h=>{s.jb("Mul",h,void 0)},832845:h=>{s.jb("Div",h,void 0)},832896:h=>{s.jb("Pow",h,void 0)},832947:h=>{s.jb("Equal",h,void 0)},833e3:h=>{s.jb("Greater",h,void 0)},833055:h=>{s.jb("GreaterOrEqual",h,void 0)},833117:h=>{s.jb("Less",h,void 0)},833169:h=>{s.jb("LessOrEqual",h,void 0)},833228:(h,P,A,L,V)=>{s.jb("ReduceMean",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833403:(h,P,A,L,V)=>{s.jb("ReduceMax",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833577:(h,P,A,L,V)=>{s.jb("ReduceMin",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833751:(h,P,A,L,V)=>{s.jb("ReduceProd",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833926:(h,P,A,L,V)=>{s.jb("ReduceSum",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834100:(h,P,A,L,V)=>{s.jb("ReduceL1",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834273:(h,P,A,L,V)=>{s.jb("ReduceL2",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834446:(h,P,A,L,V)=>{s.jb("ReduceLogSum",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834623:(h,P,A,L,V)=>{s.jb("ReduceSumSquare",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834803:(h,P,A,L,V)=>{s.jb("ReduceLogSumExp",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834983:h=>{s.jb("Where",h,void 0)},835036:(h,P,A)=>{s.jb("Transpose",h,{perm:P?Array.from(D().subarray(Number(P)>>>0,Number(A)>>>0)):[]})},835160:(h,P,A,L)=>{s.jb("DepthToSpace",h,{blocksize:P,mode:qt(A),format:L?"NHWC":"NCHW"})},835293:(h,P,A,L)=>{s.jb("DepthToSpace",h,{blocksize:P,mode:qt(A),format:L?"NHWC":"NCHW"})},835426:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:P,dilations:[A],group:L,kernelShape:[V],pads:[ie,Pe],strides:[Be],wIsConst:()=>!!pe()[at>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Ot)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},835859:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:P,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],outputShape:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},836520:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:P,dilations:[A],group:L,kernelShape:[V],pads:[ie,Pe],strides:[Be],wIsConst:()=>!!pe()[at>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Ot)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},836953:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:P,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],outputShape:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},837614:(h,P)=>{s.jb("GlobalAveragePool",h,{format:P?"NHWC":"NCHW"})},837705:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},838184:(h,P)=>{s.jb("GlobalAveragePool",h,{format:P?"NHWC":"NCHW"})},838275:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},838754:(h,P)=>{s.jb("GlobalMaxPool",h,{format:P?"NHWC":"NCHW"})},838841:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},839316:(h,P)=>{s.jb("GlobalMaxPool",h,{format:P?"NHWC":"NCHW"})},839403:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},839878:(h,P,A,L,V)=>{s.jb("Gemm",h,{alpha:P,beta:A,transA:L,transB:V})},839982:h=>{s.jb("MatMul",h,void 0)},840036:(h,P,A,L)=>{s.jb("ArgMax",h,{keepDims:!!P,selectLastIndex:!!A,axis:L})},840144:(h,P,A,L)=>{s.jb("ArgMin",h,{keepDims:!!P,selectLastIndex:!!A,axis:L})},840252:(h,P)=>{s.jb("Softmax",h,{axis:P})},840315:(h,P)=>{s.jb("Concat",h,{axis:P})},840375:(h,P,A,L,V)=>{s.jb("Split",h,{axis:P,numOutputs:A,splitSizes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},840531:h=>{s.jb("Expand",h,void 0)},840585:(h,P)=>{s.jb("Gather",h,{axis:Number(P)})},840656:(h,P)=>{s.jb("GatherElements",h,{axis:Number(P)})},840735:(h,P)=>{s.jb("GatherND",h,{batch_dims:Number(P)})},840814:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt)=>{s.jb("Resize",h,{antialias:P,axes:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],coordinateTransformMode:qt(V),cubicCoeffA:ie,excludeOutside:Pe,extrapolationValue:Be,keepAspectRatioPolicy:qt(Qe),mode:qt(at),nearestMode:qt(vt)})},841176:(h,P,A,L,V,ie,Pe)=>{s.jb("Slice",h,{starts:P?Array.from(D().subarray(Number(P)>>>0,Number(A)>>>0)):[],ends:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[],axes:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[]})},841440:h=>{s.jb("Tile",h,void 0)},841492:(h,P,A)=>{s.jb("InstanceNormalization",h,{epsilon:P,format:A?"NHWC":"NCHW"})},841606:(h,P,A)=>{s.jb("InstanceNormalization",h,{epsilon:P,format:A?"NHWC":"NCHW"})},841720:h=>{s.jb("Range",h,void 0)},841773:(h,P)=>{s.jb("Einsum",h,{equation:qt(P)})},841854:(h,P,A,L,V)=>{s.jb("Pad",h,{mode:P,value:A,pads:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},841997:(h,P,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:P,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842166:(h,P,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:P,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842335:(h,P,A)=>{s.jb("CumSum",h,{exclusive:Number(P),reverse:Number(A)})},842432:(h,P,A)=>{s.jb("DequantizeLinear",h,{axis:P,blockSize:A})},842522:(h,P,A,L,V)=>{s.jb("GridSample",h,{align_corners:P,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842692:(h,P,A,L,V)=>{s.jb("GridSample",h,{align_corners:P,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842862:(h,P)=>{s.jb("ScatterND",h,{reduction:qt(P)})},842947:(h,P,A,L,V,ie,Pe,Be,Qe)=>{s.jb("Attention",h,{numHeads:P,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie,qkvHiddenSizes:Pe?Array.from(D().subarray(Number(Be)>>>0,Number(Be)+Pe>>>0)):[],pastPresentShareBuffer:!!Qe})},843219:h=>{s.jb("BiasAdd",h,void 0)},843274:h=>{s.jb("BiasSplitGelu",h,void 0)},843335:h=>{s.jb("FastGelu",h,void 0)},843391:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us,Pa)=>{s.jb("Conv",h,{format:Ot?"NHWC":"NCHW",auto_pad:P,dilations:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],group:V,kernel_shape:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],pads:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],strides:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],w_is_const:()=>!!pe()[Number(Vt)>>>0],activation:qt(xr),activation_params:Us?Array.from(he().subarray(Number(Us)>>>0,Number(Pa)>>>0)):[]})},843975:h=>{s.jb("Gelu",h,void 0)},844027:(h,P,A,L,V,ie,Pe,Be,Qe)=>{s.jb("GroupQueryAttention",h,{numHeads:P,kvNumHeads:A,scale:L,softcap:V,doRotary:ie,rotaryInterleaved:Pe,smoothSoftmax:Be,localWindowSize:Qe})},844244:(h,P,A,L)=>{s.jb("LayerNormalization",h,{axis:P,epsilon:A,simplified:!!L})},844355:(h,P,A,L)=>{s.jb("LayerNormalization",h,{axis:P,epsilon:A,simplified:!!L})},844466:(h,P,A,L,V,ie)=>{s.jb("MatMulNBits",h,{k:P,n:A,accuracyLevel:L,bits:V,blockSize:ie})},844593:(h,P,A,L,V,ie)=>{s.jb("MultiHeadAttention",h,{numHeads:P,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie})},844752:(h,P)=>{s.jb("QuickGelu",h,{alpha:P})},844816:(h,P,A,L,V)=>{s.jb("RotaryEmbedding",h,{interleaved:!!P,numHeads:A,rotaryEmbeddingDim:L,scale:V})},844955:(h,P,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:P,simplified:!!A})},845057:(h,P,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:P,simplified:!!A})},845159:(h,P,A,L)=>{s.jb("GatherBlockQuantized",h,{gatherAxis:P,quantizeAxis:A,blockSize:L})},845280:h=>{s.Zb(h)},845314:(h,P)=>s.ac(Number(h),Number(P),s.Fb.dc,s.Fb.errors)};function De(h,P,A){return Xr(async()=>{await s.Xb(Number(h),Number(P),Number(A))})}function fe(){return typeof wasmOffsetConverter<"u"}class Ee{name="ExitStatus";constructor(P){this.message=`Program terminated with exit(${P})`,this.status=P}}var We=h=>{h.terminate(),h.onmessage=()=>{}},Fe=[],tt=h=>{ot.length==0&&(Rr(),zt(ot[0]));var P=ot.pop();if(!P)return 6;ht.push(P),It[h.Ab]=P,P.Ab=h.Ab;var A={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return P.postMessage(A,h.Mb),0},Re=0,rt=(h,P,...A)=>{for(var L=2*A.length,V=qn(),ie=Mn(8*L),Pe=ie>>>3,Be=0;Be>>0]=Qe)}return h=Co(h,0,L,ie,P),gn(V),h};function Ze(h){if(a)return rt(0,1,h);if(E=h,!(0{if(E=h,a)throw Ne(h),"unwind";Ze(h)},ot=[],ht=[],Rt=[],It={},gr=h=>{var P=h.Ab;delete It[P],ot.push(h),ht.splice(ht.indexOf(h),1),h.Ab=0,Gn(P)};function Or(){Rt.forEach(h=>h())}var zt=h=>new Promise(P=>{h.onmessage=V=>{var ie=(V=V.data).Bb;if(V.Gb&&V.Gb!=hn()){var Pe=It[V.Gb];Pe?Pe.postMessage(V,V.Mb):I(`Internal error! Worker sent a message "${ie}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ie==="checkMailbox"?se():ie==="spawnThread"?tt(V):ie==="cleanupThread"?gr(It[V.hc]):ie==="loaded"?(h.loaded=!0,P(h)):ie==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?h.postMessage(V):ie==="callHandler"?s[V.Qb](...V.args):ie&&I(`worker sent an unknown command ${ie}`)},h.onerror=V=>{throw I(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var A,L=[];for(A of[])s.propertyIsEnumerable(A)&&L.push(A);h.postMessage({Bb:"load",Rb:L,kc:T,lc:b})});function Rr(){var h=new Worker((()=>{let P=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new P("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ot.push(h)}var qs=h=>{Te();var P=te()[h+52>>>2>>>0];h=te()[h+56>>>2>>>0],Io(P,P-h),gn(P)},Qs=(h,P)=>{Re=0,h=$o(h,P),0>>=0);throw P>>>=0,A>>>=0,te()[L.Ib+16>>>2>>>0]=0,te()[L.Ib+4>>>2>>>0]=P,te()[L.Ib+8>>>2>>>0]=A,h}function Sr(h,P,A,L){return a?rt(2,1,h,P,A,L):Qr(h,P,A,L)}function Qr(h,P,A,L){if(h>>>=0,A>>>=0,L>>>=0,l===void 0)return 6;var V=[];return a&&V.length===0?Sr(h,P>>>=0,A,L):(h={ec:A,Ab:h,Hb:L,Mb:V},a?(h.Bb="spawnThread",postMessage(h,V),0):tt(h))}var Bs=typeof TextDecoder<"u"?new TextDecoder:void 0,ft=(h,P=0,A=NaN)=>{var L=(P>>>=0)+A;for(A=P;h[A]&&!(A>=L);)++A;if(16(V=(240&V)==224?(15&V)<<12|ie<<6|Pe:(7&V)<<18|ie<<12|Pe<<6|63&h[P++])?L+=String.fromCharCode(V):(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else L+=String.fromCharCode(V)}return L},qt=(h,P)=>(h>>>=0)?ft(oe(),h,P):"";function Ps(h,P,A){return a?rt(3,1,h,P,A):0}function Cs(h,P){if(a)return rt(4,1,h,P)}var Kr=h=>{for(var P=0,A=0;A=L?P++:2047>=L?P+=2:55296<=L&&57343>=L?(P+=4,++A):P+=3}return P},yt=(h,P,A)=>{var L=oe();if(P>>>=0,0=Pe&&(Pe=65536+((1023&Pe)<<10)|1023&h.charCodeAt(++ie)),127>=Pe){if(P>=A)break;L[P++>>>0]=Pe}else{if(2047>=Pe){if(P+1>=A)break;L[P++>>>0]=192|Pe>>6}else{if(65535>=Pe){if(P+2>=A)break;L[P++>>>0]=224|Pe>>12}else{if(P+3>=A)break;L[P++>>>0]=240|Pe>>18,L[P++>>>0]=128|Pe>>12&63}L[P++>>>0]=128|Pe>>6&63}L[P++>>>0]=128|63&Pe}}L[P>>>0]=0,h=P-V}else h=0;return h};function Ss(h,P){if(a)return rt(5,1,h,P)}function C(h,P,A){if(a)return rt(6,1,h,P,A)}function q(h,P,A){return a?rt(7,1,h,P,A):0}function R(h,P){if(a)return rt(8,1,h,P)}function G(h,P,A){if(a)return rt(9,1,h,P,A)}function Z(h,P,A,L){if(a)return rt(10,1,h,P,A,L)}function ce(h,P,A,L){if(a)return rt(11,1,h,P,A,L)}function ye(h,P,A,L){if(a)return rt(12,1,h,P,A,L)}function et(h){if(a)return rt(13,1,h)}function ut(h,P){if(a)return rt(14,1,h,P)}function He(h,P,A){if(a)return rt(15,1,h,P,A)}var Mt,qe,Tt=()=>xe(""),kt=h=>{for(var P="";oe()[h>>>0];)P+=Mt[oe()[h++>>>0]];return P},Mr={},dr={};function ar(h,P,A={}){return(function(L,V,ie={}){var Pe=V.name;if(!L)throw new qe(`type "${Pe}" must have a positive integer typeid pointer`);if(dr.hasOwnProperty(L)){if(ie.Sb)return;throw new qe(`Cannot register type '${Pe}' twice`)}dr[L]=V,Mr.hasOwnProperty(L)&&(V=Mr[L],delete Mr[L],V.forEach(Be=>Be()))})(h,P,A)}var Tr=(h,P,A)=>{switch(P){case 1:return A?L=>pe()[L>>>0]:L=>oe()[L>>>0];case 2:return A?L=>K()[L>>>1>>>0]:L=>N()[L>>>1>>>0];case 4:return A?L=>D()[L>>>2>>>0]:L=>te()[L>>>2>>>0];case 8:return A?L=>Y[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${P}): ${h}`)}};function Is(h,P,A){A>>>=0,ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:L=>L,toWireType:function(L,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(L=typeof V)=="object"||L==="array"||L==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:Dr,readValueFromPointer:Tr(P,A,P.indexOf("u")==-1),Db:null})}var Dr=8;function $s(h,P,A,L){ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ie){return ie?A:L},Cb:Dr,readValueFromPointer:function(V){return this.fromWireType(oe()[V>>>0])},Db:null})}var Lr=[],zr=[];function ts(h){9<(h>>>=0)&&--zr[h+1]==0&&(zr[h]=void 0,Lr.push(h))}var wr=h=>{if(!h)throw new qe("Cannot use deleted val. handle = "+h);return zr[h]},ir=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let P=Lr.pop()||zr.length;return zr[P]=h,zr[P+1]=1,P}};function Hr(h){return this.fromWireType(te()[h>>>2>>>0])}var rs={name:"emscripten::val",fromWireType:h=>{var P=wr(h);return ts(h),P},toWireType:(h,P)=>ir(P),Cb:Dr,readValueFromPointer:Hr,Db:null};function Rs(h){return ar(h>>>0,rs)}var ks=(h,P)=>{switch(P){case 4:return function(A){return this.fromWireType(he()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ae()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${P}): ${h}`)}};function As(h,P,A){A>>>=0,ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:L=>L,toWireType:(L,V)=>V,Cb:Dr,readValueFromPointer:ks(P,A),Db:null})}function Fs(h,P,A,L,V){if(h>>>=0,A>>>=0,P=kt(P>>>0),V===-1&&(V=4294967295),V=Be=>Be,L===0){var ie=32-8*A;V=Be=>Be<>>ie}var Pe=P.includes("unsigned")?function(Be,Qe){return Qe>>>0}:function(Be,Qe){return Qe};ar(h,{name:P,fromWireType:V,toWireType:Pe,Cb:Dr,readValueFromPointer:Tr(P,A,L!==0),Db:null})}function ss(h,P,A){function L(ie){var Pe=te()[ie>>>2>>>0];return ie=te()[ie+4>>>2>>>0],new V(pe().buffer,ie,Pe)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][P];ar(h>>>=0,{name:A=kt(A>>>0),fromWireType:L,Cb:Dr,readValueFromPointer:L},{Sb:!0})}function Nr(h,P){ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:function(A){for(var L,V=te()[A>>>2>>>0],ie=A+4,Pe=ie,Be=0;Be<=V;++Be){var Qe=ie+Be;Be!=V&&oe()[Qe>>>0]!=0||(Pe=qt(Pe,Qe-Pe),L===void 0?L=Pe:(L+="\0",L+=Pe),Pe=Qe+1)}return Jr(A),L},toWireType:function(A,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var V=typeof L=="string";if(!(V||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new qe("Cannot pass non-string to std::string");var ie=V?Kr(L):L.length,Pe=_n(4+ie+1),Be=Pe+4;if(te()[Pe>>>2>>>0]=ie,V)yt(L,Be,ie+1);else if(V)for(V=0;V>>0]=Qe}else for(V=0;V>>0]=L[V];return A!==null&&A.push(Jr,Pe),Pe},Cb:Dr,readValueFromPointer:Hr,Db(A){Jr(A)}})}var ze=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ue=(h,P)=>{for(var A=h>>1,L=A+P/2;!(A>=L)&&N()[A>>>0];)++A;if(32<(A<<=1)-h&&ze)return ze.decode(oe().slice(h,A));for(A="",L=0;!(L>=P/2);++L){var V=K()[h+2*L>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},nt=(h,P,A)=>{if(A??=2147483647,2>A)return 0;var L=P;A=(A-=2)<2*h.length?A/2:h.length;for(var V=0;V>>1>>>0]=ie,P+=2}return K()[P>>>1>>>0]=0,P-L},Kt=h=>2*h.length,Ns=(h,P)=>{for(var A=0,L="";!(A>=P/4);){var V=D()[h+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V)):L+=String.fromCharCode(V)}return L},Os=(h,P,A)=>{if(P>>>=0,A??=2147483647,4>A)return 0;var L=P;A=L+A-4;for(var V=0;V=ie&&(ie=65536+((1023&ie)<<10)|1023&h.charCodeAt(++V)),D()[P>>>2>>>0]=ie,(P+=4)+4>A)break}return D()[P>>>2>>>0]=0,P-L},js=h=>{for(var P=0,A=0;A=L&&++A,P+=4}return P};function Dn(h,P,A){if(h>>>=0,P>>>=0,A=kt(A>>>=0),P===2)var L=Ue,V=nt,ie=Kt,Pe=Be=>N()[Be>>>1>>>0];else P===4&&(L=Ns,V=Os,ie=js,Pe=Be=>te()[Be>>>2>>>0]);ar(h,{name:A,fromWireType:Be=>{for(var Qe,at=te()[Be>>>2>>>0],vt=Be+4,Ot=0;Ot<=at;++Ot){var Vt=Be+4+Ot*P;Ot!=at&&Pe(Vt)!=0||(vt=L(vt,Vt-vt),Qe===void 0?Qe=vt:(Qe+="\0",Qe+=vt),vt=Vt+P)}return Jr(Be),Qe},toWireType:(Be,Qe)=>{if(typeof Qe!="string")throw new qe(`Cannot pass non-string to C++ string type ${A}`);var at=ie(Qe),vt=_n(4+at+P);return te()[vt>>>2>>>0]=at/P,V(Qe,vt+4,at+P),Be!==null&&Be.push(Jr,vt),vt},Cb:Dr,readValueFromPointer:Hr,Db(Be){Jr(Be)}})}function ue(h,P){ar(h>>>=0,{Tb:!0,name:P=kt(P>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function $(h){fn(h>>>0,!i,1,!o,131072,!1),Or()}var U=h=>{if(!ne)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(D(),h>>>2,h).value.then(se),h+=128,Atomics.store(D(),h>>>2,1))}var se=()=>{var h=hn();h&&(ee(h),U(Hn))};function Me(h,P){(h>>>=0)==P>>>0?setTimeout(se):a?postMessage({Gb:h,Bb:"checkMailbox"}):(h=It[h])&&h.postMessage({Bb:"checkMailbox"})}var $e=[];function Xe(h,P,A,L,V){for(P>>>=0,L/=2,$e.length=L,A=V>>>0>>>3,V=0;V>>0];return(P?ge[P]:Ea[h])(...$e)}var Je=()=>{Re=0};function Ye(h){h>>>=0,a?postMessage({Bb:"cleanupThread",hc:h}):gr(It[h])}function Ke(h){}var $t=(h,P)=>{var A=dr[h];if(A===void 0)throw h=Eo(h),A=kt(h),Jr(h),new qe(`${P} has unknown type ${A}`);return A},Et=(h,P,A)=>{var L=[];return h=h.toWireType(L,A),L.length&&(te()[P>>>2>>>0]=ir(L)),h};function rr(h,P,A){return P>>>=0,A>>>=0,h=wr(h>>>0),P=$t(P,"emval::as"),Et(P,A,h)}function br(h,P){return P>>>=0,h=wr(h>>>0),(P=$t(P,"emval::as")).toWireType(null,h)}var Xt=h=>{try{h()}catch(P){xe(P)}},sr=0,Ht=null,qr=0,ns=[],Er={},ds={},Yt=0,hr=null,Ir=[];function Xr(h){return(function(P){if(!ne){if(sr===0){var A=!1,L=!1;P((V=0)=>{if(!ne&&(qr=V,A=!0,L)){sr=2,Xt(()=>Ao(Ht)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ie=(function(){var Qe=D()[Ht+8>>>2>>>0];return Qe=dt[ds[Qe]],--Re,Qe()})()}catch(Qe){ie=Qe,V=!0}var Pe=!1;if(!Ht){var Be=hr;Be&&(hr=null,(V?Be.reject:Be.resolve)(ie),Pe=!0)}if(V&&!Pe)throw ie}}),L=!0,A||(sr=1,Ht=(function(){var V=_n(65548),ie=V+12;te()[V>>>2>>>0]=ie,te()[V+4>>>2>>>0]=ie+65536,ie=ns[0];var Pe=Er[ie];return Pe===void 0&&(Pe=Yt++,Er[ie]=Pe,ds[Pe]=ie),ie=Pe,D()[V+8>>>2>>>0]=ie,V})(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Xt(()=>Qn(Ht)))}else sr===2?(sr=0,Xt(Xn),Jr(Ht),Ht=null,Ir.forEach(U)):xe(`invalid state: ${sr}`);return qr}})(P=>{h().then(P)})}function ps(h){return h>>>=0,Xr(async()=>{var P=await wr(h);return ir(P)})}var yr=[];function os(h,P,A,L){return A>>>=0,L>>>=0,(h=yr[h>>>0])(null,P=wr(P>>>0),A,L)}var vr={},Zt=h=>{var P=vr[h];return P===void 0?kt(h):P};function _r(h,P,A,L,V){return A>>>=0,L>>>=0,V>>>=0,(h=yr[h>>>0])(P=wr(P>>>0),P[A=Zt(A)],L,V)}var lr=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ur(h){return(h>>>=0)==0?ir(lr()):(h=Zt(h),ir(lr()[h]))}var Js=h=>{var P=yr.length;return yr.push(h),P},Ds=(h,P)=>{for(var A=Array(h),L=0;L>>2>>>0],"parameter "+L);return A},po=(h,P)=>Object.defineProperty(P,"name",{value:h});function ra(h,P,A){var L=(P=Ds(h,P>>>0)).shift();h--;var V=`return function (obj, func, destructorsRef, args) { +const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=ii.get(e);if(s===void 0)ii.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const n=Pn.indexOf(e);n!==-1&&Pn.splice(n,1);for(let o=0;o{const r=ii.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Tx=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Pn:t;let n;const o=[],i=new Set;for(const l of s){const c=await xx(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]},Ex="1.21.0";let Z_="warning";const vs={wasm:{},webgl:{},webgpu:{},versions:{common:Ex},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}`);Z_=e}},get logLevel(){return Z_}};Object.defineProperty(vs,"logLevel",{enumerable:!0});const Px=vs,Cx=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);const i=r?.format!==void 0?r.format:"RGB",a=r?.norm;let l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));const p=o*n;let d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm;let c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const u=4;let f=0,_=1,y=2,k=3,w=0,v=d,I=d*2,T=-1;a==="RGBA"?(w=0,v=d,I=d*2,T=d*3):a==="RGB"?(w=0,v=d,I=d*2):a==="RBG"&&(w=0,I=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,n=r.norm??{mean:255,bias:0};let o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let d=4,u=0,f=1,_=2,y=3,k=0,w=c,v=c*2,I=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?I=c*3:l==="RBG"?(k=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,k=c*2);for(let b=0;b{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const u=l();u.width=d,u.height=p;const f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){const u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,Ql(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{const u=l(),f=c(u);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);const y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Ql(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ql(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},$x=(e,r)=>{const{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new ls({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},kx=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new ls({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Ax=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new ls({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Fx=(e,r,t)=>new ls({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),ao=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),li=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let ef=!1;const Ox=()=>{if(!ef){ef=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(ao.set("int64",BigInt64Array),li.set(BigInt64Array,"int64")),r&&(ao.set("uint64",BigUint64Array),li.set(BigUint64Array,"uint64")),s?(ao.set("float16",t),li.set(t,"float16")):ao.set("float16",Uint16Array)}},Dx=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new ls(e.type,e.data,r);case"cpu-pinned":return new ls({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new ls({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new ls({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new ls({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let ls=class{constructor(r,t,s){Ox();let n,o;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,n=r.type,o=r.dims,r.location){case"cpu-pinned":{const a=ao.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(n=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const c=ao.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(t,BigInt):a=c.from(t)}else if(t instanceof c)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof r[0];if(c==="string")n="string",a=r;else if(c==="boolean")n="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(r);else{const c=li.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);n=c,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=a,this.dataLocation="cpu"}const i=Dx(o);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=i}static async fromImage(r,t){return Ix(r,t)}static fromTexture(r,t){return $x(r,t)}static fromGpuBuffer(r,t){return kx(r,t)}static fromMLTensor(r,t){return Ax(r,t)}static fromPinnedBuffer(r,t,s){return Fx(r,t,s)}toDataURL(r){return Cx(this,r)}toImageData(r){return Sx(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Lx(this,r)}};const so=ls,Dw=(e,r)=>{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||console.timeStamp(`${e}::ORT::${r}`)},Lw=(e,r)=>{const t=new Error().stack?.split(/\r\n|\r|\n/g)||[];let s=!1;for(let n=0;n{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||Lw("BEGIN",e)},Jc=e=>{(typeof vs.trace>"u"?!vs.wasm.trace:!vs.trace)||Lw("END",e)};let zx=class zw{constructor(r){this.handler=r}async run(r,t,s){Xc();const n={};let o={};if(typeof r!="object"||r===null||r instanceof so||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof so)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const u=t[d];(u===null||u instanceof so)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(const c of this.outputNames)n[c]=null;const a=await this.handler.run(r,n,o),l={};for(const c in a)if(Object.hasOwnProperty.call(a,c)){const p=a[c];p instanceof so?l[c]=p:l[c]=new so(p.type,p.data,p.dims)}return Jc(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Xc();let o,i={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Tx(i),c=await a.createInferenceSessionHandler(o,l);return Jc(),new zw(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const Bx=zx;var Rx=Object.freeze({__proto__:null,InferenceSession:Bx,TRACE:Dw,TRACE_FUNC_BEGIN:Xc,TRACE_FUNC_END:Jc,Tensor:so,env:Px,registerBackend:vx});var hu=Object.defineProperty,Nx=Object.getOwnPropertyDescriptor,jx=Object.getOwnPropertyNames,Vx=Object.prototype.hasOwnProperty,Ux=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),uo=(e,r)=>{for(var t in r)hu(e,t,{get:r[t],enumerable:!0})},Wx=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of jx(r))!Vx.call(e,n)&&n!==t&&hu(e,n,{get:()=>r[n],enumerable:!(s=Nx(r,n))||s.enumerable});return e},Jo=e=>Wx(hu({},"__esModule",{value:!0}),e),Lo,nn,In,tf,Bw,Rw=Ve(()=>{Lo=new Map,nn=[],In=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Lo.get(e);if(s===void 0)Lo.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let n=nn.indexOf(e);n!==-1&&nn.splice(n,1);for(let o=0;o{let r=Lo.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Bw=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?nn:t,n,o=[],i=new Set;for(let l of s){let c=await tf(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]}}),Gx=Ve(()=>{Rw()}),Nw,Kx=Ve(()=>{Nw="1.22.0-dev.20250409-89f8206ba4"}),Xl,is,jw=Ve(()=>{Kx(),Xl="warning",is={wasm:{},webgl:{},webgpu:{},versions:{common:Nw},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}`);Xl=e}},get logLevel(){return Xl}},Object.defineProperty(is,"logLevel",{enumerable:!0})}),Jt,Hx=Ve(()=>{jw(),Jt=is}),Vw,Uw,qx=Ve(()=>{Vw=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);let i=r?.format!==void 0?r.format:"RGB",a=r?.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=o*n,d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,f=0,_=1,y=2,k=3,w=0,v=d,I=d*2,T=-1;a==="RGBA"?(w=0,v=d,I=d*2,T=d*3):a==="RGB"?(w=0,v=d,I=d*2):a==="RBG"&&(w=0,I=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{_u(),Ha=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,n=r.norm??{mean:255,bias:0},o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,u=0,f=1,_=2,y=3,k=0,w=c,v=c*2,I=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?I=c*3:l==="RBG"?(k=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,k=c*2);for(let T=0;T{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let u=l();u.width=d,u.height=p;let f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,Ha(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let u=l(),f=c(u);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);let y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Ha(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Ha(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Gw=(e,r)=>{let{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new Zr({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},Kw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Zr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Hw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Zr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},qw=(e,r,t)=>new Zr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),Cn,Ko,Jl,Qw,Xx=Ve(()=>{Cn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Jl=!1,Qw=()=>{if(!Jl){Jl=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Cn.set("int64",BigInt64Array),Ko.set(BigInt64Array,"int64")),r&&(Cn.set("uint64",BigUint64Array),Ko.set(BigUint64Array,"uint64")),s?(Cn.set("float16",t),Ko.set(t,"float16")):Cn.set("float16",Uint16Array)}}}),Xw,Jw,Jx=Ve(()=>{_u(),Xw=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Zr(e.type,e.data,r);case"cpu-pinned":return new Zr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Zr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Zr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Zr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Zr,_u=Ve(()=>{qx(),Qx(),Xx(),Jx(),Zr=class{constructor(e,r,t){Qw();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let i=Cn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=Cn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=Ko.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");n=a,this.cpuData=i,this.dataLocation="cpu"}let o=Xw(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(e,r){return Ww(e,r)}static fromTexture(e,r){return Gw(e,r)}static fromGpuBuffer(e,r){return Kw(e,r)}static fromMLTensor(e,r){return Hw(e,r)}static fromPinnedBuffer(e,r,t){return qw(e,r,t)}toDataURL(e){return Vw(this,e)}toImageData(e){return Uw(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Jw(this,e)}}}),ys,Yw=Ve(()=>{_u(),ys=Zr}),Yo,Yl,Ts,us,Zw=Ve(()=>{jw(),Yo=(e,r)=>{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||console.timeStamp(`${e}::ORT::${r}`)},Yl=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||Yl("BEGIN",e)},us=e=>{(typeof is.trace>"u"?!is.wasm.trace:!is.trace)||Yl("END",e)}}),eb,Yx=Ve(()=>{Rw(),Yw(),Zw(),eb=class tb{constructor(r){this.handler=r}async run(r,t,s){Ts();let n={},o={};if(typeof r!="object"||r===null||r instanceof ys||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ys)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let u=t[d];(u===null||u instanceof ys)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(let c of this.outputNames)n[c]=null;let a=await this.handler.run(r,n,o),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof ys?l[c]=p:l[c]=new ys(p.type,p.data,p.dims)}return us(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Ts();let o,i={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Bw(i),c=await a.createInferenceSessionHandler(o,l);return us(),new tb(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}}}),fu,Zx=Ve(()=>{Yx(),fu=eb}),eT=Ve(()=>{}),tT=Ve(()=>{}),rT=Ve(()=>{}),sT=Ve(()=>{}),rb={};uo(rb,{InferenceSession:()=>fu,TRACE:()=>Yo,TRACE_FUNC_BEGIN:()=>Ts,TRACE_FUNC_END:()=>us,Tensor:()=>ys,env:()=>Jt,registerBackend:()=>In});var Es=Ve(()=>{Gx(),Hx(),Zx(),Yw(),eT(),tT(),Zw(),rT(),sT()}),gu=Ve(()=>{}),sb={};uo(sb,{default:()=>nb});var Zl,ec,nb,nT=Ve(()=>{cv(),Fn(),Mu(),Zl="ort-wasm-proxy-worker",ec=globalThis.self?.name===Zl,ec&&(self.onmessage=e=>{let{type:r,in:t}=e.data;try{switch(r){case"init-wasm":wu(t.wasm).then(()=>{zu(t).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:n}=t;Bu(n,s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:s}=t,n=gi(s);postMessage({type:r,out:n});break}case"create":{let{model:s,options:n}=t;Ru(s,n).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":Nu(t),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:i,options:a}=t;ju(s,n,o,i,new Array(i.length).fill(null),a).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:l},Uu([...o,...l]))},l=>{postMessage({type:r,err:l})});break}case"end-profiling":Vu(t),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),nb=ec?null:e=>new Worker(e??Yr,{type:"module",name:Zl})}),ob={};uo(ob,{default:()=>ab});var tc,rc,ab,rf,oT=Ve(()=>{rc=(tc=import.meta.url,async function(e={}){var r,t,s=e,n=new Promise((h,P)=>{r=h,t=P}),o=typeof window=="object",i=typeof WorkerGlobalScope<"u",a=i&&self.name?.startsWith("em-pthread");s.mountExternalData=(h,P)=>{h.startsWith("./")&&(h=h.substring(2)),(s.Eb||(s.Eb=new Map)).set(h,P)},s.unmountExternalData=()=>{delete s.Eb};var l=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...P)=>{try{if(s.Fb)throw Error("Session already started");let A=s.Fb={dc:P[0],errors:[]},L=await h(...P);if(s.Fb!==A)throw Error("Session mismatch");s.Jb?.flush();let V=A.errors;if(0Pe),0{if(h==="webgpu"){[s.Jb,s.Ub,s.Yb,s.Kb,s.Xb,s.jb,s.Zb,s.ac,s.Vb,s.Wb,s.$b]=P;let A=s.Jb;s.jsepRegisterBuffer=(L,V,ie,Pe)=>A.registerBuffer(L,V,ie,Pe),s.jsepGetBuffer=L=>A.getBuffer(L),s.jsepCreateDownloader=(L,V,ie)=>A.createDownloader(L,V,ie),s.jsepOnCreateSession=L=>{A.onCreateSession(L)},s.jsepOnReleaseSession=L=>{A.onReleaseSession(L)},s.jsepOnRunStart=L=>A.onRunStart(L),s.bc=(L,V)=>{A.upload(L,V)}}else if(h==="webnn"){let A=P[0];[s.nc,s.Nb,s.webnnEnsureTensor,s.Ob,s.webnnDownloadTensor]=P.slice(1),s.webnnReleaseTensorId=s.Nb,s.webnnUploadTensor=s.Ob,s.webnnOnRunStart=L=>A.onRunStart(L),s.webnnOnRunEnd=A.onRunEnd.bind(A),s.webnnRegisterMLContext=(L,V)=>{A.registerMLContext(L,V)},s.webnnOnReleaseSession=L=>{A.onReleaseSession(L)},s.webnnCreateMLTensorDownloader=(L,V)=>A.createMLTensorDownloader(L,V),s.webnnRegisterMLTensor=(L,V,ie,Pe)=>A.registerMLTensor(L,V,ie,Pe),s.webnnCreateMLContext=L=>A.createMLContext(L),s.webnnRegisterMLConstant=(L,V,ie,Pe,Be,Qe)=>A.registerMLConstant(L,V,ie,Pe,Be,s.Eb,Qe),s.webnnRegisterGraphInput=A.registerGraphInput.bind(A),s.webnnIsGraphInput=A.isGraphInput.bind(A),s.webnnCreateTemporaryTensor=A.createTemporaryTensor.bind(A),s.webnnIsInt64Supported=A.isInt64Supported.bind(A)}};let p=()=>{let h=(P,A,L)=>(...V)=>{let ie=Ht,Pe=A?.();V=P(...V);let Be=A?.();return Pe!==Be&&(P=Be,L(Pe),A=L=null),Ht!=ie?new Promise((Qe,at)=>{hr={resolve:Qe,reject:at}}):V};(()=>{for(let P of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])s[P]=h(s[P],()=>s[P],A=>s[P]=A)})(),c!==void 0&&(s._OrtRun=c(s._OrtRun),s._OrtRunWithBinding=c(s._OrtRunWithBinding)),p=void 0};s.asyncInit=()=>{p?.()};var d,u,f=Object.assign({},s),_=(h,P)=>{throw P},y="";(o||i)&&(i?y=self.location.href:typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),tc&&(y=tc),y=y.startsWith("blob:")?"":y.slice(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1),i&&(u=h=>{var P=new XMLHttpRequest;return P.open("GET",h,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),d=async h=>{if(le(h))return new Promise((A,L)=>{var V=new XMLHttpRequest;V.open("GET",h,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?A(V.response):L(V.status)},V.onerror=L,V.send(null)});var P=await fetch(h,{credentials:"same-origin"});if(P.ok)return P.arrayBuffer();throw Error(P.status+" : "+P.url)});var k=console.log.bind(console),w=console.error.bind(console),v=k,I=w;Object.assign(s,f),f=null;var T,b,E,x,S,O,F,H,W,B,Y,X,J,re=s.wasmBinary,ne=!1,le=h=>h.startsWith("file://");function pe(){return T.buffer!=x.buffer&&Te(),x}function oe(){return T.buffer!=x.buffer&&Te(),S}function K(){return T.buffer!=x.buffer&&Te(),O}function N(){return T.buffer!=x.buffer&&Te(),F}function D(){return T.buffer!=x.buffer&&Te(),H}function te(){return T.buffer!=x.buffer&&Te(),W}function he(){return T.buffer!=x.buffer&&Te(),B}function Ae(){return T.buffer!=x.buffer&&Te(),J}if(a){let h=function(P){try{var A=P.data,L=A.Bb;if(L==="load"){let V=[];self.onmessage=ie=>V.push(ie),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ie of V)h(ie);self.onmessage=h};for(let ie of A.Rb)s[ie]&&!s[ie].proxy||(s[ie]=(...Pe)=>{postMessage({Bb:"callHandler",Qb:ie,args:Pe})},ie=="print"&&(v=s[ie]),ie=="printErr"&&(I=s[ie]));T=A.kc,Te(),Ie(A.lc)}else if(L==="run"){qs(A.Ab),fn(A.Ab,0,0,1,0,0),Or(),ee(A.Ab),je||(mn(),je=!0);try{Qs(A.fc,A.Hb)}catch(V){if(V!="unwind")throw V}}else A.target!=="setimmediate"&&(L==="checkMailbox"?je&&se():L&&(I(`worker: received unknown command ${L}`),I(A)))}catch(V){throw Po(),V}};var Ie,je=!1;I=function(...P){P=P.join(" "),console.error(P)},self.alert=function(...P){postMessage({Bb:"alert",text:P.join(" "),ic:hn()})},self.onunhandledrejection=P=>{throw P.reason||P},self.onmessage=h}function Te(){var h=T.buffer;s.HEAP8=x=new Int8Array(h),s.HEAP16=O=new Int16Array(h),s.HEAPU8=S=new Uint8Array(h),s.HEAPU16=F=new Uint16Array(h),s.HEAP32=H=new Int32Array(h),s.HEAPU32=W=new Uint32Array(h),s.HEAPF32=B=new Float32Array(h),s.HEAPF64=J=new Float64Array(h),s.HEAP64=Y=new BigInt64Array(h),s.HEAPU64=X=new BigUint64Array(h)}function Q(){a?startWorker(s):dt.Ca()}a||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Te());var z,de=0,be=null;function ve(){if(--de==0&&be){var h=be;be=null,h()}}function xe(h){throw I(h="Aborted("+h+")"),ne=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),t(h),h}function Ce(){return{a:{L:fe,Aa:De,b:or,$:Qr,A:Ps,pa:Cs,X:Ss,Z:C,qa:q,na:R,ga:G,ma:Z,J:ce,Y:ye,V:et,oa:ut,W:He,va:Tt,E:Is,Q:$s,O:Rs,D:As,u:Fs,r:ss,P:Nr,z:Dn,R:ue,ja:$,T:Me,aa:Xe,M:Je,F:Ye,ia:ee,sa:Ke,t:rr,Ba:br,w:ps,o:os,l:_r,c:ts,n:Ur,j:ra,v:sa,p:na,f:oa,s:Ys,m:aa,e:ia,k:la,i:ca,g:ua,d:Zs,da,ea:pa,fa:fo,ba:go,ca:Mo,N:Ln,xa:ha,ua:yi,h:bo,C:Rn,G:_a,ta:wo,x:fa,ra:ga,U:Ma,q:ma,y:wa,K:ba,S:yo,za:ya,ya:jn,ka:Ls,la:vo,_:Oe,B:va,I:xo,ha:xa,H:Wn,a:T,wa:Ze}}}var ge={829644:(h,P,A,L,V)=>{if(s===void 0||!s.Eb)return 1;if((h=qt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=s.Eb.get(h)))return 2;if(P=Number(P>>>0),A=Number(A>>>0),L=Number(L>>>0),P+A>h.byteLength)return 3;try{let ie=h.subarray(P,P+A);switch(V){case 0:oe().set(ie,L>>>0);break;case 1:s.mc?s.mc(L,ie):s.bc(L,ie);break;default:return 4}return 0}catch{return 4}},830468:(h,P,A)=>{s.Ob(h,oe().subarray(P>>>0,P+A>>>0))},830532:()=>s.nc(),830574:h=>{s.Nb(h)},830611:()=>{s.Vb()},830642:()=>{s.Wb()},830671:()=>{s.$b()},830696:h=>s.Ub(h),830729:h=>s.Yb(h),830761:(h,P,A)=>{s.Kb(Number(h),Number(P),Number(A),!0)},830824:(h,P,A)=>{s.Kb(Number(h),Number(P),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{s.jb("Abs",h,void 0)},830989:h=>{s.jb("Neg",h,void 0)},831040:h=>{s.jb("Floor",h,void 0)},831093:h=>{s.jb("Ceil",h,void 0)},831145:h=>{s.jb("Reciprocal",h,void 0)},831203:h=>{s.jb("Sqrt",h,void 0)},831255:h=>{s.jb("Exp",h,void 0)},831306:h=>{s.jb("Erf",h,void 0)},831357:h=>{s.jb("Sigmoid",h,void 0)},831412:(h,P,A)=>{s.jb("HardSigmoid",h,{alpha:P,beta:A})},831491:h=>{s.jb("Log",h,void 0)},831542:h=>{s.jb("Sin",h,void 0)},831593:h=>{s.jb("Cos",h,void 0)},831644:h=>{s.jb("Tan",h,void 0)},831695:h=>{s.jb("Asin",h,void 0)},831747:h=>{s.jb("Acos",h,void 0)},831799:h=>{s.jb("Atan",h,void 0)},831851:h=>{s.jb("Sinh",h,void 0)},831903:h=>{s.jb("Cosh",h,void 0)},831955:h=>{s.jb("Asinh",h,void 0)},832008:h=>{s.jb("Acosh",h,void 0)},832061:h=>{s.jb("Atanh",h,void 0)},832114:h=>{s.jb("Tanh",h,void 0)},832166:h=>{s.jb("Not",h,void 0)},832217:(h,P,A)=>{s.jb("Clip",h,{min:P,max:A})},832286:h=>{s.jb("Clip",h,void 0)},832338:(h,P)=>{s.jb("Elu",h,{alpha:P})},832396:h=>{s.jb("Gelu",h,void 0)},832448:h=>{s.jb("Relu",h,void 0)},832500:(h,P)=>{s.jb("LeakyRelu",h,{alpha:P})},832564:(h,P)=>{s.jb("ThresholdedRelu",h,{alpha:P})},832634:(h,P)=>{s.jb("Cast",h,{to:P})},832692:h=>{s.jb("Add",h,void 0)},832743:h=>{s.jb("Sub",h,void 0)},832794:h=>{s.jb("Mul",h,void 0)},832845:h=>{s.jb("Div",h,void 0)},832896:h=>{s.jb("Pow",h,void 0)},832947:h=>{s.jb("Equal",h,void 0)},833e3:h=>{s.jb("Greater",h,void 0)},833055:h=>{s.jb("GreaterOrEqual",h,void 0)},833117:h=>{s.jb("Less",h,void 0)},833169:h=>{s.jb("LessOrEqual",h,void 0)},833228:(h,P,A,L,V)=>{s.jb("ReduceMean",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833403:(h,P,A,L,V)=>{s.jb("ReduceMax",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833577:(h,P,A,L,V)=>{s.jb("ReduceMin",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833751:(h,P,A,L,V)=>{s.jb("ReduceProd",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833926:(h,P,A,L,V)=>{s.jb("ReduceSum",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834100:(h,P,A,L,V)=>{s.jb("ReduceL1",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834273:(h,P,A,L,V)=>{s.jb("ReduceL2",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834446:(h,P,A,L,V)=>{s.jb("ReduceLogSum",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834623:(h,P,A,L,V)=>{s.jb("ReduceSumSquare",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834803:(h,P,A,L,V)=>{s.jb("ReduceLogSumExp",h,{keepDims:!!P,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834983:h=>{s.jb("Where",h,void 0)},835036:(h,P,A)=>{s.jb("Transpose",h,{perm:P?Array.from(D().subarray(Number(P)>>>0,Number(A)>>>0)):[]})},835160:(h,P,A,L)=>{s.jb("DepthToSpace",h,{blocksize:P,mode:qt(A),format:L?"NHWC":"NCHW"})},835293:(h,P,A,L)=>{s.jb("DepthToSpace",h,{blocksize:P,mode:qt(A),format:L?"NHWC":"NCHW"})},835426:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:P,dilations:[A],group:L,kernelShape:[V],pads:[ie,Pe],strides:[Be],wIsConst:()=>!!pe()[at>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Ot)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},835859:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:P,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],outputShape:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},836520:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:P,dilations:[A],group:L,kernelShape:[V],pads:[ie,Pe],strides:[Be],wIsConst:()=>!!pe()[at>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Ot)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},836953:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:P,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],outputShape:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},837614:(h,P)=>{s.jb("GlobalAveragePool",h,{format:P?"NHWC":"NCHW"})},837705:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},838184:(h,P)=>{s.jb("GlobalAveragePool",h,{format:P?"NHWC":"NCHW"})},838275:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},838754:(h,P)=>{s.jb("GlobalMaxPool",h,{format:P?"NHWC":"NCHW"})},838841:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},839316:(h,P)=>{s.jb("GlobalMaxPool",h,{format:P?"NHWC":"NCHW"})},839403:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:P,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],strides:Ot?Array.from(D().subarray(Number(Ot)>>>0,Number(Vt)>>>0)):[]})},839878:(h,P,A,L,V)=>{s.jb("Gemm",h,{alpha:P,beta:A,transA:L,transB:V})},839982:h=>{s.jb("MatMul",h,void 0)},840036:(h,P,A,L)=>{s.jb("ArgMax",h,{keepDims:!!P,selectLastIndex:!!A,axis:L})},840144:(h,P,A,L)=>{s.jb("ArgMin",h,{keepDims:!!P,selectLastIndex:!!A,axis:L})},840252:(h,P)=>{s.jb("Softmax",h,{axis:P})},840315:(h,P)=>{s.jb("Concat",h,{axis:P})},840375:(h,P,A,L,V)=>{s.jb("Split",h,{axis:P,numOutputs:A,splitSizes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},840531:h=>{s.jb("Expand",h,void 0)},840585:(h,P)=>{s.jb("Gather",h,{axis:Number(P)})},840656:(h,P)=>{s.jb("GatherElements",h,{axis:Number(P)})},840735:(h,P)=>{s.jb("GatherND",h,{batch_dims:Number(P)})},840814:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt)=>{s.jb("Resize",h,{antialias:P,axes:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],coordinateTransformMode:qt(V),cubicCoeffA:ie,excludeOutside:Pe,extrapolationValue:Be,keepAspectRatioPolicy:qt(Qe),mode:qt(at),nearestMode:qt(vt)})},841176:(h,P,A,L,V,ie,Pe)=>{s.jb("Slice",h,{starts:P?Array.from(D().subarray(Number(P)>>>0,Number(A)>>>0)):[],ends:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[],axes:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[]})},841440:h=>{s.jb("Tile",h,void 0)},841492:(h,P,A)=>{s.jb("InstanceNormalization",h,{epsilon:P,format:A?"NHWC":"NCHW"})},841606:(h,P,A)=>{s.jb("InstanceNormalization",h,{epsilon:P,format:A?"NHWC":"NCHW"})},841720:h=>{s.jb("Range",h,void 0)},841773:(h,P)=>{s.jb("Einsum",h,{equation:qt(P)})},841854:(h,P,A,L,V)=>{s.jb("Pad",h,{mode:P,value:A,pads:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},841997:(h,P,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:P,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842166:(h,P,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:P,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842335:(h,P,A)=>{s.jb("CumSum",h,{exclusive:Number(P),reverse:Number(A)})},842432:(h,P,A)=>{s.jb("DequantizeLinear",h,{axis:P,blockSize:A})},842522:(h,P,A,L,V)=>{s.jb("GridSample",h,{align_corners:P,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842692:(h,P,A,L,V)=>{s.jb("GridSample",h,{align_corners:P,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842862:(h,P)=>{s.jb("ScatterND",h,{reduction:qt(P)})},842947:(h,P,A,L,V,ie,Pe,Be,Qe)=>{s.jb("Attention",h,{numHeads:P,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie,qkvHiddenSizes:Pe?Array.from(D().subarray(Number(Be)>>>0,Number(Be)+Pe>>>0)):[],pastPresentShareBuffer:!!Qe})},843219:h=>{s.jb("BiasAdd",h,void 0)},843274:h=>{s.jb("BiasSplitGelu",h,void 0)},843335:h=>{s.jb("FastGelu",h,void 0)},843391:(h,P,A,L,V,ie,Pe,Be,Qe,at,vt,Ot,Vt,xr,Us,Pa)=>{s.jb("Conv",h,{format:Ot?"NHWC":"NCHW",auto_pad:P,dilations:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],group:V,kernel_shape:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Pe)>>>0)):[],pads:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],strides:at?Array.from(D().subarray(Number(at)>>>0,Number(vt)>>>0)):[],w_is_const:()=>!!pe()[Number(Vt)>>>0],activation:qt(xr),activation_params:Us?Array.from(he().subarray(Number(Us)>>>0,Number(Pa)>>>0)):[]})},843975:h=>{s.jb("Gelu",h,void 0)},844027:(h,P,A,L,V,ie,Pe,Be,Qe)=>{s.jb("GroupQueryAttention",h,{numHeads:P,kvNumHeads:A,scale:L,softcap:V,doRotary:ie,rotaryInterleaved:Pe,smoothSoftmax:Be,localWindowSize:Qe})},844244:(h,P,A,L)=>{s.jb("LayerNormalization",h,{axis:P,epsilon:A,simplified:!!L})},844355:(h,P,A,L)=>{s.jb("LayerNormalization",h,{axis:P,epsilon:A,simplified:!!L})},844466:(h,P,A,L,V,ie)=>{s.jb("MatMulNBits",h,{k:P,n:A,accuracyLevel:L,bits:V,blockSize:ie})},844593:(h,P,A,L,V,ie)=>{s.jb("MultiHeadAttention",h,{numHeads:P,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie})},844752:(h,P)=>{s.jb("QuickGelu",h,{alpha:P})},844816:(h,P,A,L,V)=>{s.jb("RotaryEmbedding",h,{interleaved:!!P,numHeads:A,rotaryEmbeddingDim:L,scale:V})},844955:(h,P,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:P,simplified:!!A})},845057:(h,P,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:P,simplified:!!A})},845159:(h,P,A,L)=>{s.jb("GatherBlockQuantized",h,{gatherAxis:P,quantizeAxis:A,blockSize:L})},845280:h=>{s.Zb(h)},845314:(h,P)=>s.ac(Number(h),Number(P),s.Fb.dc,s.Fb.errors)};function De(h,P,A){return Xr(async()=>{await s.Xb(Number(h),Number(P),Number(A))})}function fe(){return typeof wasmOffsetConverter<"u"}class Ee{name="ExitStatus";constructor(P){this.message=`Program terminated with exit(${P})`,this.status=P}}var We=h=>{h.terminate(),h.onmessage=()=>{}},Fe=[],tt=h=>{ot.length==0&&(Rr(),zt(ot[0]));var P=ot.pop();if(!P)return 6;ht.push(P),It[h.Ab]=P,P.Ab=h.Ab;var A={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return P.postMessage(A,h.Mb),0},Re=0,rt=(h,P,...A)=>{for(var L=2*A.length,V=qn(),ie=Mn(8*L),Pe=ie>>>3,Be=0;Be>>0]=Qe)}return h=Co(h,0,L,ie,P),gn(V),h};function Ze(h){if(a)return rt(0,1,h);if(E=h,!(0{if(E=h,a)throw Ne(h),"unwind";Ze(h)},ot=[],ht=[],Rt=[],It={},gr=h=>{var P=h.Ab;delete It[P],ot.push(h),ht.splice(ht.indexOf(h),1),h.Ab=0,Gn(P)};function Or(){Rt.forEach(h=>h())}var zt=h=>new Promise(P=>{h.onmessage=V=>{var ie=(V=V.data).Bb;if(V.Gb&&V.Gb!=hn()){var Pe=It[V.Gb];Pe?Pe.postMessage(V,V.Mb):I(`Internal error! Worker sent a message "${ie}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ie==="checkMailbox"?se():ie==="spawnThread"?tt(V):ie==="cleanupThread"?gr(It[V.hc]):ie==="loaded"?(h.loaded=!0,P(h)):ie==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?h.postMessage(V):ie==="callHandler"?s[V.Qb](...V.args):ie&&I(`worker sent an unknown command ${ie}`)},h.onerror=V=>{throw I(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var A,L=[];for(A of[])s.propertyIsEnumerable(A)&&L.push(A);h.postMessage({Bb:"load",Rb:L,kc:T,lc:b})});function Rr(){var h=new Worker((()=>{let P=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new P("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ot.push(h)}var qs=h=>{Te();var P=te()[h+52>>>2>>>0];h=te()[h+56>>>2>>>0],Io(P,P-h),gn(P)},Qs=(h,P)=>{Re=0,h=$o(h,P),0>>=0);throw P>>>=0,A>>>=0,te()[L.Ib+16>>>2>>>0]=0,te()[L.Ib+4>>>2>>>0]=P,te()[L.Ib+8>>>2>>>0]=A,h}function Sr(h,P,A,L){return a?rt(2,1,h,P,A,L):Qr(h,P,A,L)}function Qr(h,P,A,L){if(h>>>=0,A>>>=0,L>>>=0,l===void 0)return 6;var V=[];return a&&V.length===0?Sr(h,P>>>=0,A,L):(h={ec:A,Ab:h,Hb:L,Mb:V},a?(h.Bb="spawnThread",postMessage(h,V),0):tt(h))}var Bs=typeof TextDecoder<"u"?new TextDecoder:void 0,ft=(h,P=0,A=NaN)=>{var L=(P>>>=0)+A;for(A=P;h[A]&&!(A>=L);)++A;if(16(V=(240&V)==224?(15&V)<<12|ie<<6|Pe:(7&V)<<18|ie<<12|Pe<<6|63&h[P++])?L+=String.fromCharCode(V):(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else L+=String.fromCharCode(V)}return L},qt=(h,P)=>(h>>>=0)?ft(oe(),h,P):"";function Ps(h,P,A){return a?rt(3,1,h,P,A):0}function Cs(h,P){if(a)return rt(4,1,h,P)}var Kr=h=>{for(var P=0,A=0;A=L?P++:2047>=L?P+=2:55296<=L&&57343>=L?(P+=4,++A):P+=3}return P},yt=(h,P,A)=>{var L=oe();if(P>>>=0,0=Pe&&(Pe=65536+((1023&Pe)<<10)|1023&h.charCodeAt(++ie)),127>=Pe){if(P>=A)break;L[P++>>>0]=Pe}else{if(2047>=Pe){if(P+1>=A)break;L[P++>>>0]=192|Pe>>6}else{if(65535>=Pe){if(P+2>=A)break;L[P++>>>0]=224|Pe>>12}else{if(P+3>=A)break;L[P++>>>0]=240|Pe>>18,L[P++>>>0]=128|Pe>>12&63}L[P++>>>0]=128|Pe>>6&63}L[P++>>>0]=128|63&Pe}}L[P>>>0]=0,h=P-V}else h=0;return h};function Ss(h,P){if(a)return rt(5,1,h,P)}function C(h,P,A){if(a)return rt(6,1,h,P,A)}function q(h,P,A){return a?rt(7,1,h,P,A):0}function R(h,P){if(a)return rt(8,1,h,P)}function G(h,P,A){if(a)return rt(9,1,h,P,A)}function Z(h,P,A,L){if(a)return rt(10,1,h,P,A,L)}function ce(h,P,A,L){if(a)return rt(11,1,h,P,A,L)}function ye(h,P,A,L){if(a)return rt(12,1,h,P,A,L)}function et(h){if(a)return rt(13,1,h)}function ut(h,P){if(a)return rt(14,1,h,P)}function He(h,P,A){if(a)return rt(15,1,h,P,A)}var Mt,qe,Tt=()=>xe(""),kt=h=>{for(var P="";oe()[h>>>0];)P+=Mt[oe()[h++>>>0]];return P},Mr={},dr={};function ar(h,P,A={}){return(function(L,V,ie={}){var Pe=V.name;if(!L)throw new qe(`type "${Pe}" must have a positive integer typeid pointer`);if(dr.hasOwnProperty(L)){if(ie.Sb)return;throw new qe(`Cannot register type '${Pe}' twice`)}dr[L]=V,Mr.hasOwnProperty(L)&&(V=Mr[L],delete Mr[L],V.forEach(Be=>Be()))})(h,P,A)}var Tr=(h,P,A)=>{switch(P){case 1:return A?L=>pe()[L>>>0]:L=>oe()[L>>>0];case 2:return A?L=>K()[L>>>1>>>0]:L=>N()[L>>>1>>>0];case 4:return A?L=>D()[L>>>2>>>0]:L=>te()[L>>>2>>>0];case 8:return A?L=>Y[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${P}): ${h}`)}};function Is(h,P,A){A>>>=0,ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:L=>L,toWireType:function(L,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(L=typeof V)=="object"||L==="array"||L==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:Dr,readValueFromPointer:Tr(P,A,P.indexOf("u")==-1),Db:null})}var Dr=8;function $s(h,P,A,L){ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ie){return ie?A:L},Cb:Dr,readValueFromPointer:function(V){return this.fromWireType(oe()[V>>>0])},Db:null})}var Lr=[],zr=[];function ts(h){9<(h>>>=0)&&--zr[h+1]==0&&(zr[h]=void 0,Lr.push(h))}var wr=h=>{if(!h)throw new qe("Cannot use deleted val. handle = "+h);return zr[h]},ir=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let P=Lr.pop()||zr.length;return zr[P]=h,zr[P+1]=1,P}};function Hr(h){return this.fromWireType(te()[h>>>2>>>0])}var rs={name:"emscripten::val",fromWireType:h=>{var P=wr(h);return ts(h),P},toWireType:(h,P)=>ir(P),Cb:Dr,readValueFromPointer:Hr,Db:null};function Rs(h){return ar(h>>>0,rs)}var ks=(h,P)=>{switch(P){case 4:return function(A){return this.fromWireType(he()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ae()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${P}): ${h}`)}};function As(h,P,A){A>>>=0,ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:L=>L,toWireType:(L,V)=>V,Cb:Dr,readValueFromPointer:ks(P,A),Db:null})}function Fs(h,P,A,L,V){if(h>>>=0,A>>>=0,P=kt(P>>>0),V===-1&&(V=4294967295),V=Be=>Be,L===0){var ie=32-8*A;V=Be=>Be<>>ie}var Pe=P.includes("unsigned")?function(Be,Qe){return Qe>>>0}:function(Be,Qe){return Qe};ar(h,{name:P,fromWireType:V,toWireType:Pe,Cb:Dr,readValueFromPointer:Tr(P,A,L!==0),Db:null})}function ss(h,P,A){function L(ie){var Pe=te()[ie>>>2>>>0];return ie=te()[ie+4>>>2>>>0],new V(pe().buffer,ie,Pe)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][P];ar(h>>>=0,{name:A=kt(A>>>0),fromWireType:L,Cb:Dr,readValueFromPointer:L},{Sb:!0})}function Nr(h,P){ar(h>>>=0,{name:P=kt(P>>>0),fromWireType:function(A){for(var L,V=te()[A>>>2>>>0],ie=A+4,Pe=ie,Be=0;Be<=V;++Be){var Qe=ie+Be;Be!=V&&oe()[Qe>>>0]!=0||(Pe=qt(Pe,Qe-Pe),L===void 0?L=Pe:(L+="\0",L+=Pe),Pe=Qe+1)}return Jr(A),L},toWireType:function(A,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var V=typeof L=="string";if(!(V||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new qe("Cannot pass non-string to std::string");var ie=V?Kr(L):L.length,Pe=_n(4+ie+1),Be=Pe+4;if(te()[Pe>>>2>>>0]=ie,V)yt(L,Be,ie+1);else if(V)for(V=0;V>>0]=Qe}else for(V=0;V>>0]=L[V];return A!==null&&A.push(Jr,Pe),Pe},Cb:Dr,readValueFromPointer:Hr,Db(A){Jr(A)}})}var ze=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ue=(h,P)=>{for(var A=h>>1,L=A+P/2;!(A>=L)&&N()[A>>>0];)++A;if(32<(A<<=1)-h&&ze)return ze.decode(oe().slice(h,A));for(A="",L=0;!(L>=P/2);++L){var V=K()[h+2*L>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},nt=(h,P,A)=>{if(A??=2147483647,2>A)return 0;var L=P;A=(A-=2)<2*h.length?A/2:h.length;for(var V=0;V>>1>>>0]=ie,P+=2}return K()[P>>>1>>>0]=0,P-L},Kt=h=>2*h.length,Ns=(h,P)=>{for(var A=0,L="";!(A>=P/4);){var V=D()[h+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V)):L+=String.fromCharCode(V)}return L},Os=(h,P,A)=>{if(P>>>=0,A??=2147483647,4>A)return 0;var L=P;A=L+A-4;for(var V=0;V=ie&&(ie=65536+((1023&ie)<<10)|1023&h.charCodeAt(++V)),D()[P>>>2>>>0]=ie,(P+=4)+4>A)break}return D()[P>>>2>>>0]=0,P-L},js=h=>{for(var P=0,A=0;A=L&&++A,P+=4}return P};function Dn(h,P,A){if(h>>>=0,P>>>=0,A=kt(A>>>=0),P===2)var L=Ue,V=nt,ie=Kt,Pe=Be=>N()[Be>>>1>>>0];else P===4&&(L=Ns,V=Os,ie=js,Pe=Be=>te()[Be>>>2>>>0]);ar(h,{name:A,fromWireType:Be=>{for(var Qe,at=te()[Be>>>2>>>0],vt=Be+4,Ot=0;Ot<=at;++Ot){var Vt=Be+4+Ot*P;Ot!=at&&Pe(Vt)!=0||(vt=L(vt,Vt-vt),Qe===void 0?Qe=vt:(Qe+="\0",Qe+=vt),vt=Vt+P)}return Jr(Be),Qe},toWireType:(Be,Qe)=>{if(typeof Qe!="string")throw new qe(`Cannot pass non-string to C++ string type ${A}`);var at=ie(Qe),vt=_n(4+at+P);return te()[vt>>>2>>>0]=at/P,V(Qe,vt+4,at+P),Be!==null&&Be.push(Jr,vt),vt},Cb:Dr,readValueFromPointer:Hr,Db(Be){Jr(Be)}})}function ue(h,P){ar(h>>>=0,{Tb:!0,name:P=kt(P>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function $(h){fn(h>>>0,!i,1,!o,131072,!1),Or()}var U=h=>{if(!ne)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(D(),h>>>2,h).value.then(se),h+=128,Atomics.store(D(),h>>>2,1))}var se=()=>{var h=hn();h&&(ee(h),U(Hn))};function Me(h,P){(h>>>=0)==P>>>0?setTimeout(se):a?postMessage({Gb:h,Bb:"checkMailbox"}):(h=It[h])&&h.postMessage({Bb:"checkMailbox"})}var $e=[];function Xe(h,P,A,L,V){for(P>>>=0,L/=2,$e.length=L,A=V>>>0>>>3,V=0;V>>0];return(P?ge[P]:Ea[h])(...$e)}var Je=()=>{Re=0};function Ye(h){h>>>=0,a?postMessage({Bb:"cleanupThread",hc:h}):gr(It[h])}function Ke(h){}var $t=(h,P)=>{var A=dr[h];if(A===void 0)throw h=Eo(h),A=kt(h),Jr(h),new qe(`${P} has unknown type ${A}`);return A},Et=(h,P,A)=>{var L=[];return h=h.toWireType(L,A),L.length&&(te()[P>>>2>>>0]=ir(L)),h};function rr(h,P,A){return P>>>=0,A>>>=0,h=wr(h>>>0),P=$t(P,"emval::as"),Et(P,A,h)}function br(h,P){return P>>>=0,h=wr(h>>>0),(P=$t(P,"emval::as")).toWireType(null,h)}var Xt=h=>{try{h()}catch(P){xe(P)}},sr=0,Ht=null,qr=0,ns=[],Er={},ds={},Yt=0,hr=null,Ir=[];function Xr(h){return(function(P){if(!ne){if(sr===0){var A=!1,L=!1;P((V=0)=>{if(!ne&&(qr=V,A=!0,L)){sr=2,Xt(()=>Ao(Ht)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ie=(function(){var Qe=D()[Ht+8>>>2>>>0];return Qe=dt[ds[Qe]],--Re,Qe()})()}catch(Qe){ie=Qe,V=!0}var Pe=!1;if(!Ht){var Be=hr;Be&&(hr=null,(V?Be.reject:Be.resolve)(ie),Pe=!0)}if(V&&!Pe)throw ie}}),L=!0,A||(sr=1,Ht=(function(){var V=_n(65548),ie=V+12;te()[V>>>2>>>0]=ie,te()[V+4>>>2>>>0]=ie+65536,ie=ns[0];var Pe=Er[ie];return Pe===void 0&&(Pe=Yt++,Er[ie]=Pe,ds[Pe]=ie),ie=Pe,D()[V+8>>>2>>>0]=ie,V})(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Xt(()=>Qn(Ht)))}else sr===2?(sr=0,Xt(Xn),Jr(Ht),Ht=null,Ir.forEach(U)):xe(`invalid state: ${sr}`);return qr}})(P=>{h().then(P)})}function ps(h){return h>>>=0,Xr(async()=>{var P=await wr(h);return ir(P)})}var yr=[];function os(h,P,A,L){return A>>>=0,L>>>=0,(h=yr[h>>>0])(null,P=wr(P>>>0),A,L)}var vr={},Zt=h=>{var P=vr[h];return P===void 0?kt(h):P};function _r(h,P,A,L,V){return A>>>=0,L>>>=0,V>>>=0,(h=yr[h>>>0])(P=wr(P>>>0),P[A=Zt(A)],L,V)}var lr=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ur(h){return(h>>>=0)==0?ir(lr()):(h=Zt(h),ir(lr()[h]))}var Js=h=>{var P=yr.length;return yr.push(h),P},Ds=(h,P)=>{for(var A=Array(h),L=0;L>>2>>>0],"parameter "+L);return A},po=(h,P)=>Object.defineProperty(P,"name",{value:h});function ra(h,P,A){var L=(P=Ds(h,P>>>0)).shift();h--;var V=`return function (obj, func, destructorsRef, args) { `,ie=0,Pe=[];A===0&&Pe.push("obj");for(var Be=["retType"],Qe=[L],at=0;atvt.name).join(", ")}) => ${L.name}>`,Js(po(A,h))}function sa(h){return h=Zt(h>>>0),ir(s[h])}function na(h,P){return P>>>=0,h=wr(h>>>0),P=wr(P),ir(h[P])}function oa(h){9<(h>>>=0)&&(zr[h+1]+=1)}function Ys(){return ir([])}function aa(h){h=wr(h>>>0);for(var P=Array(h.length),A=0;A>>0))}function la(){return ir({})}function ca(h){for(var P=wr(h>>>=0);P.length;){var A=P.pop();P.pop()(A)}ts(h)}function ua(h,P,A){P>>>=0,A>>>=0,h=wr(h>>>0),P=wr(P),A=wr(A),h[P]=A}function Zs(h,P){return P>>>=0,h=(h=$t(h>>>0,"_emval_take_value")).readValueFromPointer(P),ir(h)}function da(h,P){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[P>>>2>>>0]=h.getUTCSeconds(),D()[P+4>>>2>>>0]=h.getUTCMinutes(),D()[P+8>>>2>>>0]=h.getUTCHours(),D()[P+12>>>2>>>0]=h.getUTCDate(),D()[P+16>>>2>>>0]=h.getUTCMonth(),D()[P+20>>>2>>>0]=h.getUTCFullYear()-1900,D()[P+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,D()[P+28>>>2>>>0]=h}var mo=h=>h%4==0&&(h%100!=0||h%400==0),ho=[0,31,60,91,121,152,182,213,244,274,305,335],_o=[0,31,59,90,120,151,181,212,243,273,304,334];function pa(h,P){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[P>>>2>>>0]=h.getSeconds(),D()[P+4>>>2>>>0]=h.getMinutes(),D()[P+8>>>2>>>0]=h.getHours(),D()[P+12>>>2>>>0]=h.getDate(),D()[P+16>>>2>>>0]=h.getMonth(),D()[P+20>>>2>>>0]=h.getFullYear()-1900,D()[P+24>>>2>>>0]=h.getDay();var A=(mo(h.getFullYear())?ho:_o)[h.getMonth()]+h.getDate()-1|0;D()[P+28>>>2>>>0]=A,D()[P+36>>>2>>>0]=-60*h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(A!=L&&h.getTimezoneOffset()==Math.min(L,A)),D()[P+32>>>2>>>0]=h}function fo(h){h>>>=0;var P=new Date(D()[h+20>>>2>>>0]+1900,D()[h+16>>>2>>>0],D()[h+12>>>2>>>0],D()[h+8>>>2>>>0],D()[h+4>>>2>>>0],D()[h>>>2>>>0],0),A=D()[h+32>>>2>>>0],L=P.getTimezoneOffset(),V=new Date(P.getFullYear(),6,1).getTimezoneOffset(),ie=new Date(P.getFullYear(),0,1).getTimezoneOffset(),Pe=Math.min(ie,V);return 0>A?D()[h+32>>>2>>>0]=+(V!=ie&&Pe==L):0>>2>>>0]=P.getDay(),A=(mo(P.getFullYear())?ho:_o)[P.getMonth()]+P.getDate()-1|0,D()[h+28>>>2>>>0]=A,D()[h>>>2>>>0]=P.getSeconds(),D()[h+4>>>2>>>0]=P.getMinutes(),D()[h+8>>>2>>>0]=P.getHours(),D()[h+12>>>2>>>0]=P.getDate(),D()[h+16>>>2>>>0]=P.getMonth(),D()[h+20>>>2>>>0]=P.getYear(),h=P.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function go(h,P,A,L,V,ie,Pe){return a?rt(16,1,h,P,A,L,V,ie,Pe):-52}function Mo(h,P,A,L,V,ie){if(a)return rt(17,1,h,P,A,L,V,ie)}var Vs={},ma=()=>performance.timeOrigin+performance.now();function Ln(h,P){if(a)return rt(18,1,h,P);if(Vs[h]&&(clearTimeout(Vs[h].id),delete Vs[h]),!P)return 0;var A=setTimeout(()=>{delete Vs[h],U(()=>So(h,performance.timeOrigin+performance.now()))},P);return Vs[h]={id:A,qc:P},0}function ha(h,P,A,L){h>>>=0,P>>>=0,A>>>=0,L>>>=0;var V=new Date().getFullYear(),ie=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Pe=Math.max(ie,V);te()[h>>>2>>>0]=60*Pe,D()[P>>>2>>>0]=+(ie!=V),h=(P=Be=>{var Qe=Math.abs(Be);return`UTC${0<=Be?"-":"+"}${String(Math.floor(Qe/60)).padStart(2,"0")}${String(Qe%60).padStart(2,"0")}`})(ie),P=P(V),VDate.now();function bi(h,P,A){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Y[A>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var zn=[],Bn=(h,P)=>{zn.length=0;for(var A;A=oe()[h++>>>0];){var L=A!=105;P+=(L&=A!=112)&&P%8?4:0,zn.push(A==112?te()[P>>>2>>>0]:A==106?Y[P>>>3]:A==105?D()[P>>>2>>>0]:Ae()[P>>>3>>>0]),P+=L?8:4}return zn};function bo(h,P,A){return h>>>=0,P=Bn(P>>>0,A>>>0),ge[h](...P)}function Rn(h,P,A){return h>>>=0,P=Bn(P>>>0,A>>>0),ge[h](...P)}var _a=()=>{};function fa(h,P){return I(qt(h>>>0,P>>>0))}var ga=()=>{throw Re+=1,"unwind"};function Ma(){return 4294901760}var wa=()=>navigator.hardwareConcurrency;function ba(){return xe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function yo(h){h>>>=0;var P=oe().length;if(h<=P||4294901760=A;A*=2){var L=P*(1+.2/A);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(L),Te();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var un=()=>(xe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),en={},Nn=h=>{h.forEach(P=>{un()})};function ya(){var h=Error().stack.toString().split(` +`),h=(function(vt){var Ot=Function;if(!(Ot instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof Ot} which is not a function`);var Vt=po(Ot.name||"unknownFunctionName",function(){});return Vt.prototype=Ot.prototype,Vt=new Vt,(vt=Ot.apply(Vt,vt))instanceof Object?vt:Vt})(Be)(...Qe),A=`methodCaller<(${P.map(vt=>vt.name).join(", ")}) => ${L.name}>`,Js(po(A,h))}function sa(h){return h=Zt(h>>>0),ir(s[h])}function na(h,P){return P>>>=0,h=wr(h>>>0),P=wr(P),ir(h[P])}function oa(h){9<(h>>>=0)&&(zr[h+1]+=1)}function Ys(){return ir([])}function aa(h){h=wr(h>>>0);for(var P=Array(h.length),A=0;A>>0))}function la(){return ir({})}function ca(h){for(var P=wr(h>>>=0);P.length;){var A=P.pop();P.pop()(A)}ts(h)}function ua(h,P,A){P>>>=0,A>>>=0,h=wr(h>>>0),P=wr(P),A=wr(A),h[P]=A}function Zs(h,P){return P>>>=0,h=(h=$t(h>>>0,"_emval_take_value")).readValueFromPointer(P),ir(h)}function da(h,P){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[P>>>2>>>0]=h.getUTCSeconds(),D()[P+4>>>2>>>0]=h.getUTCMinutes(),D()[P+8>>>2>>>0]=h.getUTCHours(),D()[P+12>>>2>>>0]=h.getUTCDate(),D()[P+16>>>2>>>0]=h.getUTCMonth(),D()[P+20>>>2>>>0]=h.getUTCFullYear()-1900,D()[P+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,D()[P+28>>>2>>>0]=h}var mo=h=>h%4==0&&(h%100!=0||h%400==0),ho=[0,31,60,91,121,152,182,213,244,274,305,335],_o=[0,31,59,90,120,151,181,212,243,273,304,334];function pa(h,P){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[P>>>2>>>0]=h.getSeconds(),D()[P+4>>>2>>>0]=h.getMinutes(),D()[P+8>>>2>>>0]=h.getHours(),D()[P+12>>>2>>>0]=h.getDate(),D()[P+16>>>2>>>0]=h.getMonth(),D()[P+20>>>2>>>0]=h.getFullYear()-1900,D()[P+24>>>2>>>0]=h.getDay();var A=(mo(h.getFullYear())?ho:_o)[h.getMonth()]+h.getDate()-1|0;D()[P+28>>>2>>>0]=A,D()[P+36>>>2>>>0]=-60*h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(A!=L&&h.getTimezoneOffset()==Math.min(L,A)),D()[P+32>>>2>>>0]=h}function fo(h){h>>>=0;var P=new Date(D()[h+20>>>2>>>0]+1900,D()[h+16>>>2>>>0],D()[h+12>>>2>>>0],D()[h+8>>>2>>>0],D()[h+4>>>2>>>0],D()[h>>>2>>>0],0),A=D()[h+32>>>2>>>0],L=P.getTimezoneOffset(),V=new Date(P.getFullYear(),6,1).getTimezoneOffset(),ie=new Date(P.getFullYear(),0,1).getTimezoneOffset(),Pe=Math.min(ie,V);return 0>A?D()[h+32>>>2>>>0]=+(V!=ie&&Pe==L):0>>2>>>0]=P.getDay(),A=(mo(P.getFullYear())?ho:_o)[P.getMonth()]+P.getDate()-1|0,D()[h+28>>>2>>>0]=A,D()[h>>>2>>>0]=P.getSeconds(),D()[h+4>>>2>>>0]=P.getMinutes(),D()[h+8>>>2>>>0]=P.getHours(),D()[h+12>>>2>>>0]=P.getDate(),D()[h+16>>>2>>>0]=P.getMonth(),D()[h+20>>>2>>>0]=P.getYear(),h=P.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function go(h,P,A,L,V,ie,Pe){return a?rt(16,1,h,P,A,L,V,ie,Pe):-52}function Mo(h,P,A,L,V,ie){if(a)return rt(17,1,h,P,A,L,V,ie)}var Vs={},ma=()=>performance.timeOrigin+performance.now();function Ln(h,P){if(a)return rt(18,1,h,P);if(Vs[h]&&(clearTimeout(Vs[h].id),delete Vs[h]),!P)return 0;var A=setTimeout(()=>{delete Vs[h],U(()=>So(h,performance.timeOrigin+performance.now()))},P);return Vs[h]={id:A,qc:P},0}function ha(h,P,A,L){h>>>=0,P>>>=0,A>>>=0,L>>>=0;var V=new Date().getFullYear(),ie=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Pe=Math.max(ie,V);te()[h>>>2>>>0]=60*Pe,D()[P>>>2>>>0]=+(ie!=V),h=(P=Be=>{var Qe=Math.abs(Be);return`UTC${0<=Be?"-":"+"}${String(Math.floor(Qe/60)).padStart(2,"0")}${String(Qe%60).padStart(2,"0")}`})(ie),P=P(V),VDate.now();function yi(h,P,A){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Y[A>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var zn=[],Bn=(h,P)=>{zn.length=0;for(var A;A=oe()[h++>>>0];){var L=A!=105;P+=(L&=A!=112)&&P%8?4:0,zn.push(A==112?te()[P>>>2>>>0]:A==106?Y[P>>>3]:A==105?D()[P>>>2>>>0]:Ae()[P>>>3>>>0]),P+=L?8:4}return zn};function bo(h,P,A){return h>>>=0,P=Bn(P>>>0,A>>>0),ge[h](...P)}function Rn(h,P,A){return h>>>=0,P=Bn(P>>>0,A>>>0),ge[h](...P)}var _a=()=>{};function fa(h,P){return I(qt(h>>>0,P>>>0))}var ga=()=>{throw Re+=1,"unwind"};function Ma(){return 4294901760}var wa=()=>navigator.hardwareConcurrency;function ba(){return xe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function yo(h){h>>>=0;var P=oe().length;if(h<=P||4294901760=A;A*=2){var L=P*(1+.2/A);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(L),Te();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var un=()=>(xe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),en={},Nn=h=>{h.forEach(P=>{un()})};function ya(){var h=Error().stack.toString().split(` `);return h[0]=="Error"&&h.shift(),Nn(h),en.Lb=un(),en.cc=h,en.Lb}function jn(h,P,A){if(h>>>=0,P>>>=0,en.Lb==h)var L=en.cc;else(L=Error().stack.toString().split(` -`))[0]=="Error"&&L.shift(),Nn(L);for(var V=3;L[V]&&un()!=h;)++V;for(h=0;h>>2>>>0]=un();return h}var dn,Vn={},Un=()=>{if(!dn){var h,P={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Vn)Vn[h]===void 0?delete P[h]:P[h]=Vn[h];var A=[];for(h in P)A.push(`${h}=${P[h]}`);dn=A}return dn};function Ls(h,P){if(a)return rt(19,1,h,P);h>>>=0,P>>>=0;var A=0;return Un().forEach((L,V)=>{var ie=P+A;for(V=te()[h+4*V>>>2>>>0]=ie,ie=0;ie>>0]=L.charCodeAt(ie);pe()[V>>>0]=0,A+=L.length+1}),0}function vo(h,P){if(a)return rt(20,1,h,P);h>>>=0,P>>>=0;var A=Un();te()[h>>>2>>>0]=A.length;var L=0;return A.forEach(V=>L+=V.length+1),te()[P>>>2>>>0]=L,0}function va(h){return a?rt(21,1,h):52}function xo(h,P,A,L){return a?rt(22,1,h,P,A,L):52}function xa(h,P,A,L){return a?rt(23,1,h,P,A,L):70}var Ta=[null,[],[]];function Wn(h,P,A,L){if(a)return rt(24,1,h,P,A,L);P>>>=0,A>>>=0,L>>>=0;for(var V=0,ie=0;ie>>2>>>0],Be=te()[P+4>>>2>>>0];P+=8;for(var Qe=0;Qe>>0],vt=Ta[h];at===0||at===10?((h===1?v:I)(ft(vt)),vt.length=0):vt.push(at)}V+=Be}return te()[L>>>2>>>0]=V,0}a||(function(){for(var h=s.numThreads-1;h--;)Rr();Fe.unshift(()=>{de++,(function(P){a?P():Promise.all(ot.map(zt)).then(P)})(()=>ve())})})();for(var To=Array(256),pn=0;256>pn;++pn)To[pn]=String.fromCharCode(pn);Mt=To,qe=s.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},s.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},zr.push(0,1,void 0,1,null,1,!0,1,!1,1),s.count_emval_handles=()=>zr.length/2-5-Lr.length;var dt,Ea=[Ze,Ne,Sr,Ps,Cs,Ss,C,q,R,G,Z,ce,ye,et,ut,He,go,Mo,Ln,Ls,vo,va,xo,xa,Wn];(async function(){function h(L,V){return dt=L.exports,dt=(function(){var ie=dt,Pe={};for(let[Be,Qe]of Object.entries(ie))Pe[Be]=typeof Qe=="function"?(...at)=>{ns.push(Be);try{return Qe(...at)}finally{ne||(ns.pop(),Ht&&sr===1&&ns.length===0&&(sr=0,Re+=1,Xt(ko),typeof Fibers<"u"&&Fibers.rc()))}}:Qe;return Pe})(),dt=(function(){var ie=dt,Pe=Qe=>at=>Qe(at)>>>0,Be=Qe=>()=>Qe()>>>0;return(ie=Object.assign({},ie)).Da=Pe(ie.Da),ie.fb=Be(ie.fb),ie.hb=Pe(ie.hb),ie.tb=Pe(ie.tb),ie.ub=Be(ie.ub),ie.__cxa_get_exception_ptr=Pe(ie.__cxa_get_exception_ptr),ie})(),Rt.push(dt.ib),b=V,ve(),dt}de++;var P=Ce();if(s.instantiateWasm)return new Promise(L=>{s.instantiateWasm(P,(V,ie)=>{h(V,ie),L(V.exports)})});if(a)return new Promise(L=>{Ie=V=>{var ie=new WebAssembly.Instance(V,Ce());L(h(ie,V))}});z??=s.locateFile?s.locateFile?s.locateFile("ort-wasm-simd-threaded.jsep.wasm",y):y+"ort-wasm-simd-threaded.jsep.wasm":new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href;try{var A=await(async function(L){var V=z;if(!re&&typeof WebAssembly.instantiateStreaming=="function"&&!le(V))try{var ie=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ie,L)}catch(Pe){I(`wasm streaming compile failed: ${Pe}`),I("falling back to ArrayBuffer instantiation")}return(async function(Pe,Be){try{var Qe=await(async function(at){if(!re)try{var vt=await d(at);return new Uint8Array(vt)}catch{}if(at==z&&re)at=new Uint8Array(re);else{if(!u)throw"both async and sync fetching of the wasm failed";at=u(at)}return at})(Pe);return await WebAssembly.instantiate(Qe,Be)}catch(at){I(`failed to asynchronously prepare wasm: ${at}`),xe(at)}})(V,L)})(P);return h(A.instance,A.module)}catch(L){return t(L),Promise.reject(L)}})();var Eo=h=>(Eo=dt.Da)(h),mn=()=>(mn=dt.Ea)();s._OrtInit=(h,P)=>(s._OrtInit=dt.Fa)(h,P),s._OrtGetLastError=(h,P)=>(s._OrtGetLastError=dt.Ga)(h,P),s._OrtCreateSessionOptions=(h,P,A,L,V,ie,Pe,Be,Qe,at)=>(s._OrtCreateSessionOptions=dt.Ha)(h,P,A,L,V,ie,Pe,Be,Qe,at),s._OrtAppendExecutionProvider=(h,P,A,L,V)=>(s._OrtAppendExecutionProvider=dt.Ia)(h,P,A,L,V),s._OrtAddFreeDimensionOverride=(h,P,A)=>(s._OrtAddFreeDimensionOverride=dt.Ja)(h,P,A),s._OrtAddSessionConfigEntry=(h,P,A)=>(s._OrtAddSessionConfigEntry=dt.Ka)(h,P,A),s._OrtReleaseSessionOptions=h=>(s._OrtReleaseSessionOptions=dt.La)(h),s._OrtCreateSession=(h,P,A)=>(s._OrtCreateSession=dt.Ma)(h,P,A),s._OrtReleaseSession=h=>(s._OrtReleaseSession=dt.Na)(h),s._OrtGetInputOutputCount=(h,P,A)=>(s._OrtGetInputOutputCount=dt.Oa)(h,P,A),s._OrtGetInputOutputMetadata=(h,P,A,L)=>(s._OrtGetInputOutputMetadata=dt.Pa)(h,P,A,L),s._OrtFree=h=>(s._OrtFree=dt.Qa)(h),s._OrtCreateTensor=(h,P,A,L,V,ie)=>(s._OrtCreateTensor=dt.Ra)(h,P,A,L,V,ie),s._OrtGetTensorData=(h,P,A,L,V)=>(s._OrtGetTensorData=dt.Sa)(h,P,A,L,V),s._OrtReleaseTensor=h=>(s._OrtReleaseTensor=dt.Ta)(h),s._OrtCreateRunOptions=(h,P,A,L)=>(s._OrtCreateRunOptions=dt.Ua)(h,P,A,L),s._OrtAddRunConfigEntry=(h,P,A)=>(s._OrtAddRunConfigEntry=dt.Va)(h,P,A),s._OrtReleaseRunOptions=h=>(s._OrtReleaseRunOptions=dt.Wa)(h),s._OrtCreateBinding=h=>(s._OrtCreateBinding=dt.Xa)(h),s._OrtBindInput=(h,P,A)=>(s._OrtBindInput=dt.Ya)(h,P,A),s._OrtBindOutput=(h,P,A,L)=>(s._OrtBindOutput=dt.Za)(h,P,A,L),s._OrtClearBoundOutputs=h=>(s._OrtClearBoundOutputs=dt._a)(h),s._OrtReleaseBinding=h=>(s._OrtReleaseBinding=dt.$a)(h),s._OrtRunWithBinding=(h,P,A,L,V)=>(s._OrtRunWithBinding=dt.ab)(h,P,A,L,V),s._OrtRun=(h,P,A,L,V,ie,Pe,Be)=>(s._OrtRun=dt.bb)(h,P,A,L,V,ie,Pe,Be),s._OrtEndProfiling=h=>(s._OrtEndProfiling=dt.cb)(h),s._JsepOutput=(h,P,A)=>(s._JsepOutput=dt.db)(h,P,A),s._JsepGetNodeName=h=>(s._JsepGetNodeName=dt.eb)(h);var hn=()=>(hn=dt.fb)(),Jr=s._free=h=>(Jr=s._free=dt.gb)(h),_n=s._malloc=h=>(_n=s._malloc=dt.hb)(h),fn=(h,P,A,L,V,ie)=>(fn=dt.kb)(h,P,A,L,V,ie),Po=()=>(Po=dt.lb)(),Co=(h,P,A,L,V)=>(Co=dt.mb)(h,P,A,L,V),Gn=h=>(Gn=dt.nb)(h),Kn=h=>(Kn=dt.ob)(h),So=(h,P)=>(So=dt.pb)(h,P),Hn=()=>(Hn=dt.qb)(),Io=(h,P)=>(Io=dt.rb)(h,P),gn=h=>(gn=dt.sb)(h),Mn=h=>(Mn=dt.tb)(h),qn=()=>(qn=dt.ub)(),$o=s.dynCall_ii=(h,P)=>($o=s.dynCall_ii=dt.vb)(h,P),Qn=h=>(Qn=dt.wb)(h),ko=()=>(ko=dt.xb)(),Ao=h=>(Ao=dt.yb)(h),Xn=()=>(Xn=dt.zb)();return s.stackSave=()=>qn(),s.stackRestore=h=>gn(h),s.stackAlloc=h=>Mn(h),s.setValue=function(h,P,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":pe()[h>>>0]=P;break;case"i16":K()[h>>>1>>>0]=P;break;case"i32":D()[h>>>2>>>0]=P;break;case"i64":Y[h>>>3]=BigInt(P);break;case"float":he()[h>>>2>>>0]=P;break;case"double":Ae()[h>>>3>>>0]=P;break;case"*":te()[h>>>2>>>0]=P;break;default:xe(`invalid type for setValue: ${A}`)}},s.getValue=function(h,P="i8"){switch(P.endsWith("*")&&(P="*"),P){case"i1":case"i8":return pe()[h>>>0];case"i16":return K()[h>>>1>>>0];case"i32":return D()[h>>>2>>>0];case"i64":return Y[h>>>3];case"float":return he()[h>>>2>>>0];case"double":return Ae()[h>>>3>>>0];case"*":return te()[h>>>2>>>0];default:xe(`invalid type for getValue: ${P}`)}},s.UTF8ToString=qt,s.stringToUTF8=yt,s.lengthBytesUTF8=Kr,(function h(){if(0{fu(),rc=typeof location>"u"?void 0:location.origin,Jc=import.meta.url>"file:"&&import.meta.url<"file;",rf=()=>{{if(Jc){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,rc).href}return import.meta.url}},Yr=rf(),ab=()=>{if(Yr&&!Yr.startsWith("blob:"))return Yr.substring(0,Yr.lastIndexOf("/")+1)},qa=(e,r)=>{try{let t=r??Yr;return(t?new URL(e,t):new URL(e)).origin===rc}catch{return!1}},sf=(e,r)=>{let t=r??Yr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},nf=(e,r)=>`${r??"./"}${e}`,sc=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},of=async e=>(await import(e)).default,nc=(nT(),Jo(rb)).default,ib=async()=>{if(!Yr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qa(Yr))return[void 0,nc()];let e=await sc(Yr);return[e,nc(e)]},oc=(oT(),Jo(nb)).default,lb=async(e,r,t)=>{if(!e&&!r&&oc&&Yr&&qa(Yr))return[void 0,oc];{let s="ort-wasm-simd-threaded.jsep.mjs",n=e??sf(s,r),o=t&&n&&!qa(n,r),i=o?await sc(n):n??nf(s,r);return[o?i:void 0,await of(i)]}}}),ac,Qa,zo,ic,af,lf,cf,Mu,Qt,Fn=Ve(()=>{gu(),Qa=!1,zo=!1,ic=!1,af=()=>{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}},lf=()=>{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}},cf=()=>{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}},Mu=async e=>{if(Qa)return Promise.resolve();if(zo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(ic)throw new Error("previous call to 'initializeWebAssembly()' failed.");zo=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!cf())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!lf())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=af();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let n=e.wasmPaths,o=typeof n=="string"?n:void 0,i=n?.mjs,a=i?.href??i,l=n?.wasm,c=l?.href??l,p=e.wasmBinary,[d,u]=await lb(a,o,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(y=>{setTimeout(()=>{f=!0,y()},r)})),_.push(new Promise((y,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(c||o)w.locateFile=v=>c??o+v;else if(a&&a.indexOf("blob:")!==0)w.locateFile=v=>new URL(v,a).href;else if(d){let v=ab();v&&(w.locateFile=I=>v+I)}u(w).then(v=>{zo=!1,Qa=!0,ac=v,y(),d&&URL.revokeObjectURL(d)},v=>{zo=!1,ic=!0,k(v)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qt=()=>{if(Qa&&ac)return ac;throw new Error("WebAssembly is not initialized yet.")}}),bs,di,Gt,wu=Ve(()=>{Fn(),bs=(e,r)=>{let t=Qt(),s=t.lengthBytesUTF8(e)+1,n=t._malloc(s);return t.stringToUTF8(e,n,s),r.push(n),n},di=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([n,o])=>{let i=r?r+n:n;if(typeof o=="object")di(o,i+".",t,s);else if(typeof o=="string"||typeof o=="number")s(i,o.toString());else if(typeof o=="boolean")s(i,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Gt=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetLastError(n,n+s);let o=Number(r.getValue(n,s===4?"i32":"i64")),i=r.getValue(n+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),cb,aT=Ve(()=>{Fn(),wu(),cb=e=>{let r=Qt(),t=0,s=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let o=0;return e?.tag!==void 0&&(o=bs(e.tag,s)),t=r._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),t===0&&Gt("Can't create run options."),e?.extra!==void 0&&di(e.extra,"",new WeakSet,(i,a)=>{let l=bs(i,s),c=bs(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Gt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),o}}}),uf,df,pf,Bo,mf,ub,iT=Ve(()=>{Fn(),wu(),uf=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}`)}},df=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},pf=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},Bo=(e,r,t,s)=>{let n=bs(r,s),o=bs(t,s);Qt()._OrtAddSessionConfigEntry(e,n,o)!==0&&Gt(`Can't set a session config entry: ${r} - ${t}.`)},mf=async(e,r,t)=>{for(let s of r){let n=typeof s=="string"?s:s.name,o=[];switch(n){case"webnn":if(n="WEBNN",typeof s!="string"){let p=s?.deviceType;p&&Bo(e,"deviceType",p,t)}break;case"webgpu":if(n="JS",typeof s!="string"){let p=s;if(p?.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);Bo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let i=bs(n,t),a=o.length,l=0,c=0;if(a>0){l=Qt()._malloc(a*Qt().PTR_SIZE),t.push(l),c=Qt()._malloc(a*Qt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Qt(),t=0,s=[],n=e||{};pf(n);try{let o=uf(n.graphOptimizationLevel??"all"),i=df(n.executionMode??"sequential"),a=typeof n.logId=="string"?bs(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?bs(n.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,i,!!n.enableProfiling,0,a,l,c,p),t===0&&Gt("Can't create session options."),n.executionProviders&&await mf(t,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Bo(t,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[d,u]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let f=bs(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Gt(`Can't set a free dimension override: ${d} - ${u}.`)}return n.extra!==void 0&&di(n.extra,"",new WeakSet,(d,u)=>{Bo(t,d,u,s)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Gt("Can't release session options."),s.forEach(i=>r._free(i)),o}}}),no,Ks,Sn,bu,pi,yu,vu,Yc,gt=Ve(()=>{no=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}`)}},Ks=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}`)}},Sn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((n,o)=>n*o,1);return t>0?Math.ceil(s*t):void 0},bu=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}`)}},pi=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}`)}},yu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",vu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Yc=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}`)}}}),xu,db=Ve(()=>{fu(),xu=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=r.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await n.read();if(a)break;let c=l.byteLength;new Uint8Array(o,i,c).set(l),i+=c}return new Uint8Array(o,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),hf,_f,ff,gf,Tu,Mf,Dt,Hs=Ve(()=>{gt(),hf=["V","I","W","E","F"],_f=(e,r)=>{console.log(`[${hf[e]},${new Date().toISOString()}]${r}`)},Tu=(e,r)=>{ff=e,gf=r},Mf=(e,r)=>{let t=pi(e),s=pi(ff);t>=s&&_f(t,typeof r=="function"?r():r)},Dt=(...e)=>{gf&&Mf(...e)}}),wf,lo,we,mi,pb,mb,hb,Ct=Ve(()=>{wf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},lo=class{static calcShape(e,r,t=!1){let s=e.length,n=r.length;if(s===0)return r;if(n===0)return e;let o=Math.max(e.length,r.length),i=new Array(o);if(t){if(s<2||n<2)return;let a=wf.calcMatMulShape([e[s-2],e[s-1]],[r[n-2],r[n-1]]);if(a===void 0)return;[i[o-2],i[o-1]]=a}for(let a=t?3:1;a<=o;a++){let l=s-a<0?1:e[s-a],c=n-a<0?1:r[n-a];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)i[o-a]=Math.max(l,c);else{if(p>1)return;i[o-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let n=1;n<=t;n++)if(e[t-n]!==1&&e[t-n]!==r[s-n])return!1;return!0}},we=class ci{static size(r){return ci.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let n=new Array(s),o=s-1;for(;o>=0;){if(r[o]%t===0){n[o]=r[o]/t;break}if(t%r[o]!==0)throw new Error("cannot convert shape");n[o]=1,t/=r[o],o--}for(o--;o>=0;o--)n[o]=r[o];return n}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return ci.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return ci.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let n=1;for(let o=t;o=0;--n)s[n]=s[n+1]*r[n+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((n,o)=>n+t[o]+t[o+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,n)=>s===t[n])}},mi=class Ho{static adjustPoolAttributes(r,t,s,n,o,i){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,n,o,i,a){if(a){if(o.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{gt(),Eu=(e,r)=>new(bu(r))(e)}),Zc,lc,bf,cc,yf,uc,dc,pc,vf,fb,lT=Ve(()=>{Hs(),Zc=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),n=new Int32Array(t);for(let o=0;o2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${i}`);n[o]=Number(i)}return r?new Uint8Array(n.buffer):n},lc=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),n=BigInt64Array.from(s,BigInt);return r?new Uint8Array(n.buffer):n},bf=1,cc=()=>bf++,yf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),uc=(e,r)=>{let t=yf.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,n)=>s*n)*t/8):0},dc=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:n,shape:o,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return uc(this.dataType,this.tensorShape)}destroy(){Dt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=lc(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},pc=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let n=r,o=this.tensorManager.getMLContext(e),i=n==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(i&&(n="int32",Dt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(o,n,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==uc(n,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,n,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=Zc(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Dt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){if(this.activeUpload){let r=this.wrapper?.isInt64ToInt32Converted?lc(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(r):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(r);return}else return r.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32,e):this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32)}},vf=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=cc();return this.tensorTrackersById.set(e,new pc(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,n){Dt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(r);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(e,t,s,n)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Dt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r?.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let n=this.getMLContext(e),o=cc(),i=new dc({sessionId:e,context:n,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(o,new pc(this,i)),this.externalTensors.add(i),o}async getCachedTensor(e,r,t,s,n,o,i=!1){let a=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Dt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=e,d}Dt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new dc({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},fb=(...e)=>new vf(...e)}),Xa,xf,gb,cT=Ve(()=>{gt(),Fn(),_b(),lT(),Hs(),Xa=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),xf=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((n,o)=>n===s[o]&&e[n]===r[n])},gb=class{constructor(e){this.tensorManager=fb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Tu(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Dt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Dt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Dt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>xf(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(n=>n.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Dt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,n){let o=Xa.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,o,s,n)}async createTemporaryTensor(e,r,t){Dt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Xa.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,t,!1);let o=this.temporarySessionTensorIds.get(e);return o?o.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,r){if(!Qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Dt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return Eu(t,r)}}registerMLTensor(e,r,t,s){let n=Xa.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(e,r,n,s);return Dt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,r,t,s,n,o,i=!1){if(!o)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=o.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(r,r+t).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":i?(p=Zc(new Uint8Array(c),!1),n.dataType="int32"):p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return Dt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){return!!this.mlContextBySessionId.get(e)?.opSupportLimits().input.dataTypes.includes("int64")}flush(){}}}),Pu=Ve(()=>{}),mc,Ja,Ya,Tf,Ef,hc,eu,Pf,Mb,uT=Ve(()=>{Hs(),Pu(),mc=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]]),Ja=[],Ya=e=>Math.ceil(Number(e)/16)*16,Tf=e=>{for(let r=0;rEf++,eu=async(e,r,t,s)=>{let n=Ya(t),o=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,o,0,n),e.flush(),await o.mapAsync(GPUMapMode.READ);let a=o.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{o.destroy()}},Pf=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of mc)Ja.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,n=r.byteLength,o=Ya(n),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==n)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${n}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,n)),a.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(a,0,i.gpuData.buffer,0,o),this.backend.device.queue.submit([c.finish()]),a.destroy(),Dt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let n=Ya(t.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,n)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. - Please use the previous external buffer!`)}else s=hc();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Dt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Tf(e),s,n=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||o){let a=(n?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:hc(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Dt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){return this.storageCache.get(e)?.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Dt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await eu(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=mc.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Dt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Mb=(...e)=>new Pf(...e)}),Cf,jt,mr=Ve(()=>{Cf=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},jt=e=>new Cf(e)}),co,Za,Ar,jr,ct,ur,tu,io,ln,lt,Ro,ke,it,wb,Cu,Sf,bb,St=Ve(()=>{gt(),Ct(),co=64,Za=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ar=(e,r=1)=>{let t=Za(e,r);return typeof t=="string"?t:t[0]},jr=(e,r=1)=>{let t=Za(e,r);return typeof t=="string"?t:t[1]},ct=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:we.computeStrides(t)})}),r},ur=e=>e%4===0?4:e%2===0?2:1,tu=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,io=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,ln=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,lt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,Ro=(e,r,t,s,n)=>{let o=typeof t=="number",i=o?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,c=Za(r,n),p=typeof c=="string"?c:c[1],d=typeof c=="string"?c:c[0],u={indices:l,value:p,storage:d,tensor:r},f=oe=>typeof oe=="string"?oe:`${oe}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},y=o?"uniforms.":"",k=`${y}${e}_shape`,w=`${y}${e}_strides`,v="";for(let oe=0;oe>>2>>>0]=un();return h}var dn,Vn={},Un=()=>{if(!dn){var h,P={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Vn)Vn[h]===void 0?delete P[h]:P[h]=Vn[h];var A=[];for(h in P)A.push(`${h}=${P[h]}`);dn=A}return dn};function Ls(h,P){if(a)return rt(19,1,h,P);h>>>=0,P>>>=0;var A=0;return Un().forEach((L,V)=>{var ie=P+A;for(V=te()[h+4*V>>>2>>>0]=ie,ie=0;ie>>0]=L.charCodeAt(ie);pe()[V>>>0]=0,A+=L.length+1}),0}function vo(h,P){if(a)return rt(20,1,h,P);h>>>=0,P>>>=0;var A=Un();te()[h>>>2>>>0]=A.length;var L=0;return A.forEach(V=>L+=V.length+1),te()[P>>>2>>>0]=L,0}function va(h){return a?rt(21,1,h):52}function xo(h,P,A,L){return a?rt(22,1,h,P,A,L):52}function xa(h,P,A,L){return a?rt(23,1,h,P,A,L):70}var Ta=[null,[],[]];function Wn(h,P,A,L){if(a)return rt(24,1,h,P,A,L);P>>>=0,A>>>=0,L>>>=0;for(var V=0,ie=0;ie>>2>>>0],Be=te()[P+4>>>2>>>0];P+=8;for(var Qe=0;Qe>>0],vt=Ta[h];at===0||at===10?((h===1?v:I)(ft(vt)),vt.length=0):vt.push(at)}V+=Be}return te()[L>>>2>>>0]=V,0}a||(function(){for(var h=s.numThreads-1;h--;)Rr();Fe.unshift(()=>{de++,(function(P){a?P():Promise.all(ot.map(zt)).then(P)})(()=>ve())})})();for(var To=Array(256),pn=0;256>pn;++pn)To[pn]=String.fromCharCode(pn);Mt=To,qe=s.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},s.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},zr.push(0,1,void 0,1,null,1,!0,1,!1,1),s.count_emval_handles=()=>zr.length/2-5-Lr.length;var dt,Ea=[Ze,Ne,Sr,Ps,Cs,Ss,C,q,R,G,Z,ce,ye,et,ut,He,go,Mo,Ln,Ls,vo,va,xo,xa,Wn];(async function(){function h(L,V){return dt=L.exports,dt=(function(){var ie=dt,Pe={};for(let[Be,Qe]of Object.entries(ie))Pe[Be]=typeof Qe=="function"?(...at)=>{ns.push(Be);try{return Qe(...at)}finally{ne||(ns.pop(),Ht&&sr===1&&ns.length===0&&(sr=0,Re+=1,Xt(ko),typeof Fibers<"u"&&Fibers.rc()))}}:Qe;return Pe})(),dt=(function(){var ie=dt,Pe=Qe=>at=>Qe(at)>>>0,Be=Qe=>()=>Qe()>>>0;return(ie=Object.assign({},ie)).Da=Pe(ie.Da),ie.fb=Be(ie.fb),ie.hb=Pe(ie.hb),ie.tb=Pe(ie.tb),ie.ub=Be(ie.ub),ie.__cxa_get_exception_ptr=Pe(ie.__cxa_get_exception_ptr),ie})(),Rt.push(dt.ib),b=V,ve(),dt}de++;var P=Ce();if(s.instantiateWasm)return new Promise(L=>{s.instantiateWasm(P,(V,ie)=>{h(V,ie),L(V.exports)})});if(a)return new Promise(L=>{Ie=V=>{var ie=new WebAssembly.Instance(V,Ce());L(h(ie,V))}});z??=s.locateFile?s.locateFile?s.locateFile("ort-wasm-simd-threaded.jsep.wasm",y):y+"ort-wasm-simd-threaded.jsep.wasm":new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href;try{var A=await(async function(L){var V=z;if(!re&&typeof WebAssembly.instantiateStreaming=="function"&&!le(V))try{var ie=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ie,L)}catch(Pe){I(`wasm streaming compile failed: ${Pe}`),I("falling back to ArrayBuffer instantiation")}return(async function(Pe,Be){try{var Qe=await(async function(at){if(!re)try{var vt=await d(at);return new Uint8Array(vt)}catch{}if(at==z&&re)at=new Uint8Array(re);else{if(!u)throw"both async and sync fetching of the wasm failed";at=u(at)}return at})(Pe);return await WebAssembly.instantiate(Qe,Be)}catch(at){I(`failed to asynchronously prepare wasm: ${at}`),xe(at)}})(V,L)})(P);return h(A.instance,A.module)}catch(L){return t(L),Promise.reject(L)}})();var Eo=h=>(Eo=dt.Da)(h),mn=()=>(mn=dt.Ea)();s._OrtInit=(h,P)=>(s._OrtInit=dt.Fa)(h,P),s._OrtGetLastError=(h,P)=>(s._OrtGetLastError=dt.Ga)(h,P),s._OrtCreateSessionOptions=(h,P,A,L,V,ie,Pe,Be,Qe,at)=>(s._OrtCreateSessionOptions=dt.Ha)(h,P,A,L,V,ie,Pe,Be,Qe,at),s._OrtAppendExecutionProvider=(h,P,A,L,V)=>(s._OrtAppendExecutionProvider=dt.Ia)(h,P,A,L,V),s._OrtAddFreeDimensionOverride=(h,P,A)=>(s._OrtAddFreeDimensionOverride=dt.Ja)(h,P,A),s._OrtAddSessionConfigEntry=(h,P,A)=>(s._OrtAddSessionConfigEntry=dt.Ka)(h,P,A),s._OrtReleaseSessionOptions=h=>(s._OrtReleaseSessionOptions=dt.La)(h),s._OrtCreateSession=(h,P,A)=>(s._OrtCreateSession=dt.Ma)(h,P,A),s._OrtReleaseSession=h=>(s._OrtReleaseSession=dt.Na)(h),s._OrtGetInputOutputCount=(h,P,A)=>(s._OrtGetInputOutputCount=dt.Oa)(h,P,A),s._OrtGetInputOutputMetadata=(h,P,A,L)=>(s._OrtGetInputOutputMetadata=dt.Pa)(h,P,A,L),s._OrtFree=h=>(s._OrtFree=dt.Qa)(h),s._OrtCreateTensor=(h,P,A,L,V,ie)=>(s._OrtCreateTensor=dt.Ra)(h,P,A,L,V,ie),s._OrtGetTensorData=(h,P,A,L,V)=>(s._OrtGetTensorData=dt.Sa)(h,P,A,L,V),s._OrtReleaseTensor=h=>(s._OrtReleaseTensor=dt.Ta)(h),s._OrtCreateRunOptions=(h,P,A,L)=>(s._OrtCreateRunOptions=dt.Ua)(h,P,A,L),s._OrtAddRunConfigEntry=(h,P,A)=>(s._OrtAddRunConfigEntry=dt.Va)(h,P,A),s._OrtReleaseRunOptions=h=>(s._OrtReleaseRunOptions=dt.Wa)(h),s._OrtCreateBinding=h=>(s._OrtCreateBinding=dt.Xa)(h),s._OrtBindInput=(h,P,A)=>(s._OrtBindInput=dt.Ya)(h,P,A),s._OrtBindOutput=(h,P,A,L)=>(s._OrtBindOutput=dt.Za)(h,P,A,L),s._OrtClearBoundOutputs=h=>(s._OrtClearBoundOutputs=dt._a)(h),s._OrtReleaseBinding=h=>(s._OrtReleaseBinding=dt.$a)(h),s._OrtRunWithBinding=(h,P,A,L,V)=>(s._OrtRunWithBinding=dt.ab)(h,P,A,L,V),s._OrtRun=(h,P,A,L,V,ie,Pe,Be)=>(s._OrtRun=dt.bb)(h,P,A,L,V,ie,Pe,Be),s._OrtEndProfiling=h=>(s._OrtEndProfiling=dt.cb)(h),s._JsepOutput=(h,P,A)=>(s._JsepOutput=dt.db)(h,P,A),s._JsepGetNodeName=h=>(s._JsepGetNodeName=dt.eb)(h);var hn=()=>(hn=dt.fb)(),Jr=s._free=h=>(Jr=s._free=dt.gb)(h),_n=s._malloc=h=>(_n=s._malloc=dt.hb)(h),fn=(h,P,A,L,V,ie)=>(fn=dt.kb)(h,P,A,L,V,ie),Po=()=>(Po=dt.lb)(),Co=(h,P,A,L,V)=>(Co=dt.mb)(h,P,A,L,V),Gn=h=>(Gn=dt.nb)(h),Kn=h=>(Kn=dt.ob)(h),So=(h,P)=>(So=dt.pb)(h,P),Hn=()=>(Hn=dt.qb)(),Io=(h,P)=>(Io=dt.rb)(h,P),gn=h=>(gn=dt.sb)(h),Mn=h=>(Mn=dt.tb)(h),qn=()=>(qn=dt.ub)(),$o=s.dynCall_ii=(h,P)=>($o=s.dynCall_ii=dt.vb)(h,P),Qn=h=>(Qn=dt.wb)(h),ko=()=>(ko=dt.xb)(),Ao=h=>(Ao=dt.yb)(h),Xn=()=>(Xn=dt.zb)();return s.stackSave=()=>qn(),s.stackRestore=h=>gn(h),s.stackAlloc=h=>Mn(h),s.setValue=function(h,P,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":pe()[h>>>0]=P;break;case"i16":K()[h>>>1>>>0]=P;break;case"i32":D()[h>>>2>>>0]=P;break;case"i64":Y[h>>>3]=BigInt(P);break;case"float":he()[h>>>2>>>0]=P;break;case"double":Ae()[h>>>3>>>0]=P;break;case"*":te()[h>>>2>>>0]=P;break;default:xe(`invalid type for setValue: ${A}`)}},s.getValue=function(h,P="i8"){switch(P.endsWith("*")&&(P="*"),P){case"i1":case"i8":return pe()[h>>>0];case"i16":return K()[h>>>1>>>0];case"i32":return D()[h>>>2>>>0];case"i64":return Y[h>>>3];case"float":return he()[h>>>2>>>0];case"double":return Ae()[h>>>3>>>0];case"*":return te()[h>>>2>>>0];default:xe(`invalid type for getValue: ${P}`)}},s.UTF8ToString=qt,s.stringToUTF8=yt,s.lengthBytesUTF8=Kr,(function h(){if(0{gu(),sc=typeof location>"u"?void 0:location.origin,Yc=import.meta.url>"file:"&&import.meta.url<"file;",sf=()=>{{if(Yc){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,sc).href}return import.meta.url}},Yr=sf(),ib=()=>{if(Yr&&!Yr.startsWith("blob:"))return Yr.substring(0,Yr.lastIndexOf("/")+1)},qa=(e,r)=>{try{let t=r??Yr;return(t?new URL(e,t):new URL(e)).origin===sc}catch{return!1}},nf=(e,r)=>{let t=r??Yr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},of=(e,r)=>`${r??"./"}${e}`,nc=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},af=async e=>(await import(e)).default,oc=(nT(),Jo(sb)).default,lb=async()=>{if(!Yr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qa(Yr))return[void 0,oc()];let e=await nc(Yr);return[e,oc(e)]},ac=(oT(),Jo(ob)).default,cb=async(e,r,t)=>{if(!e&&!r&&ac&&Yr&&qa(Yr))return[void 0,ac];{let s="ort-wasm-simd-threaded.jsep.mjs",n=e??nf(s,r),o=t&&n&&!qa(n,r),i=o?await nc(n):n??of(s,r);return[o?i:void 0,await af(i)]}}}),ic,Qa,zo,lc,lf,cf,uf,wu,Qt,Fn=Ve(()=>{Mu(),Qa=!1,zo=!1,lc=!1,lf=()=>{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}},cf=()=>{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}},uf=()=>{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}},wu=async e=>{if(Qa)return Promise.resolve();if(zo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(lc)throw new Error("previous call to 'initializeWebAssembly()' failed.");zo=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!uf())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!cf())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=lf();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let n=e.wasmPaths,o=typeof n=="string"?n:void 0,i=n?.mjs,a=i?.href??i,l=n?.wasm,c=l?.href??l,p=e.wasmBinary,[d,u]=await cb(a,o,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(y=>{setTimeout(()=>{f=!0,y()},r)})),_.push(new Promise((y,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(c||o)w.locateFile=v=>c??o+v;else if(a&&a.indexOf("blob:")!==0)w.locateFile=v=>new URL(v,a).href;else if(d){let v=ib();v&&(w.locateFile=I=>v+I)}u(w).then(v=>{zo=!1,Qa=!0,ic=v,y(),d&&URL.revokeObjectURL(d)},v=>{zo=!1,lc=!0,k(v)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qt=()=>{if(Qa&&ic)return ic;throw new Error("WebAssembly is not initialized yet.")}}),bs,di,Gt,bu=Ve(()=>{Fn(),bs=(e,r)=>{let t=Qt(),s=t.lengthBytesUTF8(e)+1,n=t._malloc(s);return t.stringToUTF8(e,n,s),r.push(n),n},di=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([n,o])=>{let i=r?r+n:n;if(typeof o=="object")di(o,i+".",t,s);else if(typeof o=="string"||typeof o=="number")s(i,o.toString());else if(typeof o=="boolean")s(i,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Gt=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetLastError(n,n+s);let o=Number(r.getValue(n,s===4?"i32":"i64")),i=r.getValue(n+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),ub,aT=Ve(()=>{Fn(),bu(),ub=e=>{let r=Qt(),t=0,s=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let o=0;return e?.tag!==void 0&&(o=bs(e.tag,s)),t=r._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),t===0&&Gt("Can't create run options."),e?.extra!==void 0&&di(e.extra,"",new WeakSet,(i,a)=>{let l=bs(i,s),c=bs(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Gt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),o}}}),df,pf,mf,Bo,hf,db,iT=Ve(()=>{Fn(),bu(),df=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}`)}},pf=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},mf=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},Bo=(e,r,t,s)=>{let n=bs(r,s),o=bs(t,s);Qt()._OrtAddSessionConfigEntry(e,n,o)!==0&&Gt(`Can't set a session config entry: ${r} - ${t}.`)},hf=async(e,r,t)=>{for(let s of r){let n=typeof s=="string"?s:s.name,o=[];switch(n){case"webnn":if(n="WEBNN",typeof s!="string"){let p=s?.deviceType;p&&Bo(e,"deviceType",p,t)}break;case"webgpu":if(n="JS",typeof s!="string"){let p=s;if(p?.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);Bo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let i=bs(n,t),a=o.length,l=0,c=0;if(a>0){l=Qt()._malloc(a*Qt().PTR_SIZE),t.push(l),c=Qt()._malloc(a*Qt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Qt(),t=0,s=[],n=e||{};mf(n);try{let o=df(n.graphOptimizationLevel??"all"),i=pf(n.executionMode??"sequential"),a=typeof n.logId=="string"?bs(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?bs(n.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,i,!!n.enableProfiling,0,a,l,c,p),t===0&&Gt("Can't create session options."),n.executionProviders&&await hf(t,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Bo(t,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[d,u]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let f=bs(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Gt(`Can't set a free dimension override: ${d} - ${u}.`)}return n.extra!==void 0&&di(n.extra,"",new WeakSet,(d,u)=>{Bo(t,d,u,s)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Gt("Can't release session options."),s.forEach(i=>r._free(i)),o}}}),no,Ks,Sn,yu,pi,vu,xu,Zc,gt=Ve(()=>{no=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}`)}},Ks=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}`)}},Sn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((n,o)=>n*o,1);return t>0?Math.ceil(s*t):void 0},yu=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}`)}},pi=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}`)}},vu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",xu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Zc=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}`)}}}),Tu,pb=Ve(()=>{gu(),Tu=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let n=r.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await n.read();if(a)break;let c=l.byteLength;new Uint8Array(o,i,c).set(l),i+=c}return new Uint8Array(o,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),_f,ff,gf,Mf,Eu,wf,Dt,Hs=Ve(()=>{gt(),_f=["V","I","W","E","F"],ff=(e,r)=>{console.log(`[${_f[e]},${new Date().toISOString()}]${r}`)},Eu=(e,r)=>{gf=e,Mf=r},wf=(e,r)=>{let t=pi(e),s=pi(gf);t>=s&&ff(t,typeof r=="function"?r():r)},Dt=(...e)=>{Mf&&wf(...e)}}),bf,lo,we,mi,mb,hb,_b,Ct=Ve(()=>{bf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},lo=class{static calcShape(e,r,t=!1){let s=e.length,n=r.length;if(s===0)return r;if(n===0)return e;let o=Math.max(e.length,r.length),i=new Array(o);if(t){if(s<2||n<2)return;let a=bf.calcMatMulShape([e[s-2],e[s-1]],[r[n-2],r[n-1]]);if(a===void 0)return;[i[o-2],i[o-1]]=a}for(let a=t?3:1;a<=o;a++){let l=s-a<0?1:e[s-a],c=n-a<0?1:r[n-a];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)i[o-a]=Math.max(l,c);else{if(p>1)return;i[o-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let n=1;n<=t;n++)if(e[t-n]!==1&&e[t-n]!==r[s-n])return!1;return!0}},we=class ci{static size(r){return ci.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let n=new Array(s),o=s-1;for(;o>=0;){if(r[o]%t===0){n[o]=r[o]/t;break}if(t%r[o]!==0)throw new Error("cannot convert shape");n[o]=1,t/=r[o],o--}for(o--;o>=0;o--)n[o]=r[o];return n}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return ci.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return ci.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let n=1;for(let o=t;o=0;--n)s[n]=s[n+1]*r[n+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((n,o)=>n+t[o]+t[o+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,n)=>s===t[n])}},mi=class Ho{static adjustPoolAttributes(r,t,s,n,o,i){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,n,o,i,a){if(a){if(o.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(n.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{gt(),Pu=(e,r)=>new(yu(r))(e)}),eu,cc,yf,uc,vf,dc,pc,mc,xf,gb,lT=Ve(()=>{Hs(),eu=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),n=new Int32Array(t);for(let o=0;o2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${i}`);n[o]=Number(i)}return r?new Uint8Array(n.buffer):n},cc=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),n=BigInt64Array.from(s,BigInt);return r?new Uint8Array(n.buffer):n},yf=1,uc=()=>yf++,vf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),dc=(e,r)=>{let t=vf.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,n)=>s*n)*t/8):0},pc=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:n,shape:o,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return dc(this.dataType,this.tensorShape)}destroy(){Dt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=cc(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,n)=>s===t[n])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},mc=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let n=r,o=this.tensorManager.getMLContext(e),i=n==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(i&&(n="int32",Dt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(o,n,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==dc(n,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,n,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=eu(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Dt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){if(this.activeUpload){let r=this.wrapper?.isInt64ToInt32Converted?cc(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(r):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(r);return}else return r.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32,e):this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32)}},xf=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=uc();return this.tensorTrackersById.set(e,new mc(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,n){Dt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(r);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(e,t,s,n)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Dt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r?.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let n=this.getMLContext(e),o=uc(),i=new pc({sessionId:e,context:n,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(o,new mc(this,i)),this.externalTensors.add(i),o}async getCachedTensor(e,r,t,s,n,o,i=!1){let a=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Dt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=e,d}Dt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new pc({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},gb=(...e)=>new xf(...e)}),Xa,Tf,Mb,cT=Ve(()=>{gt(),Fn(),fb(),lT(),Hs(),Xa=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Tf=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((n,o)=>n===s[o]&&e[n]===r[n])},Mb=class{constructor(e){this.tensorManager=gb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Eu(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Dt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Dt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Dt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>Tf(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(n=>n.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Dt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,n){let o=Xa.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,o,s,n)}async createTemporaryTensor(e,r,t){Dt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Xa.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,t,!1);let o=this.temporarySessionTensorIds.get(e);return o?o.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,r){if(!Qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Dt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return Pu(t,r)}}registerMLTensor(e,r,t,s){let n=Xa.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(e,r,n,s);return Dt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,r,t,s,n,o,i=!1){if(!o)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=o.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(r,r+t).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":i?(p=eu(new Uint8Array(c),!1),n.dataType="int32"):p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return Dt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){return!!this.mlContextBySessionId.get(e)?.opSupportLimits().input.dataTypes.includes("int64")}flush(){}}}),Cu=Ve(()=>{}),hc,Ja,Ya,Ef,Pf,_c,tu,Cf,wb,uT=Ve(()=>{Hs(),Cu(),hc=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]]),Ja=[],Ya=e=>Math.ceil(Number(e)/16)*16,Ef=e=>{for(let r=0;rPf++,tu=async(e,r,t,s)=>{let n=Ya(t),o=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,o,0,n),e.flush(),await o.mapAsync(GPUMapMode.READ);let a=o.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{o.destroy()}},Cf=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of hc)Ja.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,n=r.byteLength,o=Ya(n),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==n)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${n}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,n)),a.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(a,0,i.gpuData.buffer,0,o),this.backend.device.queue.submit([c.finish()]),a.destroy(),Dt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let n=Ya(t.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,n)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else s=_c();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Dt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Ef(e),s,n=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||o){let a=(n?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:_c(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Dt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){return this.storageCache.get(e)?.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Dt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await tu(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=hc.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Dt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},wb=(...e)=>new Cf(...e)}),Sf,jt,mr=Ve(()=>{Sf=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},jt=e=>new Sf(e)}),co,Za,Ar,jr,ct,ur,ru,io,ln,lt,Ro,ke,it,bb,Su,If,yb,St=Ve(()=>{gt(),Ct(),co=64,Za=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Ar=(e,r=1)=>{let t=Za(e,r);return typeof t=="string"?t:t[0]},jr=(e,r=1)=>{let t=Za(e,r);return typeof t=="string"?t:t[1]},ct=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:we.computeStrides(t)})}),r},ur=e=>e%4===0?4:e%2===0?2:1,ru=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,io=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,ln=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,lt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,Ro=(e,r,t,s,n)=>{let o=typeof t=="number",i=o?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,c=Za(r,n),p=typeof c=="string"?c:c[1],d=typeof c=="string"?c:c[0],u={indices:l,value:p,storage:d,tensor:r},f=oe=>typeof oe=="string"?oe:`${oe}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},y=o?"uniforms.":"",k=`${y}${e}_shape`,w=`${y}${e}_strides`,v="";for(let oe=0;oe{if(r&&typeof r.init=="function"&&typeof r.cr fn set_${e}(${oe}, value: ${p}) { set_${e}ByIndices(${S(K)}, value); }`})();return{impl:()=>{let oe=[],K=!1;return _.offsetToIndices&&(oe.push(I),K=!0),_.indicesToOffset&&(oe.push(E),K=!0),_.broadcastedIndicesToOffset&&(Object.values(H).forEach(N=>oe.push(N)),K=!0),_.set&&(oe.push(pe),K=!0),_.setByIndices&&(oe.push(le),K=!0),_.get&&(oe.push(J),K=!0),_.getByIndices&&(oe.push(X),K=!0),!o&&K&&oe.unshift(`const ${k} = ${u.indices}(${t.join(",")});`,`const ${w} = ${u.indices}(${we.computeStrides(t).join(",")});`),oe.join(` -`)},type:u,offsetToIndices:T,indicesToOffset:x,broadcastedIndicesToOffset:W,indices:S,indicesGet:O,indicesSet:F,set:(...oe)=>{if(oe.length!==i+1)throw new Error(`indices length must be ${i}`);let K=oe[i];if(typeof K!="string")throw new Error("value must be string");let N=oe.slice(0,i).map(f).join(",");return i===0?B("0u",K):i===1?B(N[0],K):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${N}, ${K})`)},setByOffset:B,setByIndices:(oe,K)=>i<2?B(oe,K):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${oe}, ${K});`),get:re,getByOffset:Y,getByIndices:ne,usage:s,name:e,strides:w,shape:k,rank:i}},ke=(e,r,t,s=1)=>Ro(e,r,t,"input",s),it=(e,r,t,s=1)=>Ro(e,r,t,"output",s),wb=(e,r,t)=>Ro(e,r,t,"atomicOutput",1),Cu=(e,r,t,s=1)=>Ro(e,r,t,"internal",s),Sf=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=co){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let n=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=n?`@builtin(global_invocation_id) global_id : vec3, +`)},type:u,offsetToIndices:T,indicesToOffset:x,broadcastedIndicesToOffset:W,indices:S,indicesGet:O,indicesSet:F,set:(...oe)=>{if(oe.length!==i+1)throw new Error(`indices length must be ${i}`);let K=oe[i];if(typeof K!="string")throw new Error("value must be string");let N=oe.slice(0,i).map(f).join(",");return i===0?B("0u",K):i===1?B(N[0],K):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${N}, ${K})`)},setByOffset:B,setByIndices:(oe,K)=>i<2?B(oe,K):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${oe}, ${K});`),get:re,getByOffset:Y,getByIndices:ne,usage:s,name:e,strides:w,shape:k,rank:i}},ke=(e,r,t,s=1)=>Ro(e,r,t,"input",s),it=(e,r,t,s=1)=>Ro(e,r,t,"output",s),bb=(e,r,t)=>Ro(e,r,t,"atomicOutput",1),Su=(e,r,t,s=1)=>Ro(e,r,t,"internal",s),If=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=co){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let n=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=n?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @@ -54,13 +54,13 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` -`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},bb=(e,r)=>new Sf(e,r)}),If,_c,$f,kf,Af,Ff,es,yb,vb,cn=Ve(()=>{gt(),Ct(),mr(),St(),If=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},_c=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),$f=(e,r)=>we.sortBasedOnPerm(e,_c(e.length,r)),kf=(e,r,t,s)=>{let n=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { - var a: ${t.type.indices};`;for(let o=0;o{let t=[],s=[];for(let n=0;n{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,n=_c(s,r),o=$f(e.dims,n),i=e.dims,a=o,l=s<2||Ff(n,e.dims),c;if(l)return c=_=>{let y=ke("input",t,i,4),k=it("output",t,a,4);return` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},yb=(e,r)=>new If(e,r)}),$f,fc,kf,Af,Ff,Of,es,vb,xb,cn=Ve(()=>{gt(),Ct(),mr(),St(),$f=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},fc=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),kf=(e,r)=>we.sortBasedOnPerm(e,fc(e.length,r)),Af=(e,r,t,s)=>{let n=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let o=0;o{let t=[],s=[];for(let n=0;n{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,n=fc(s,r),o=kf(e.dims,n),i=e.dims,a=o,l=s<2||Of(n,e.dims),c;if(l)return c=_=>{let y=ke("input",t,i,4),k=it("output",t,a,4);return` ${_.registerUniform("output_size","u32").declareVariables(y,k)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:d}=Af(e.dims,n),u=we.areEqual(d,[2,3,1]),f=we.areEqual(d,[3,1,2]);if(p.length===2||u||f){i=u?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return c=y=>{let k=ke("a",t,i.length),w=it("output",t,a.length);return` + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:d}=Ff(e.dims,n),u=we.areEqual(d,[2,3,1]),f=we.areEqual(d,[3,1,2]);if(p.length===2||u||f){i=u?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return c=y=>{let k=ke("a",t,i.length),w=it("output",t,a.length);return` ${y.registerUniform("output_size","u32").declareVariables(k,w)} var tile : array, ${_}>; ${y.mainStart([_,_,1])} @@ -82,7 +82,7 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let y=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:y},...ct(i,a)]}},getShaderSource:c}}return c=_=>{let y=ke("a",t,i.length),k=it("output",t,a.length);return` ${_.registerUniform("output_size","u32").declareVariables(y,k)} - ${kf(n,s,y,k)} + ${Af(n,s,y,k)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -91,7 +91,7 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr let aIndices = perm(indices); ${k.setByOffset("global_idx",y.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},yb=(e,r)=>{If(e.inputs,r.perm),e.compute(es(e.inputs[0],r.perm))},vb=e=>jt({perm:e.perm})}),Of,Df,Lf,zf,Bf,Rf,Nf,jf,Vf,Uf,_s,xb,Tb,Eb,Pb,Cb,Sb,Ib,$b,kb,Ab,dT=Ve(()=>{gt(),Ct(),St(),Su(),cn(),Of={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Df={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"},Lf={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},zf={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Bf=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let o=0;oe[o]);return[t,n]},Nf=(e,r)=>{let t=e.length+r.length,s=[],n=0;for(let o=0;o{for(let t=0;t{let t=[];if(!jf(e,r)){for(let s=0;st.push(s))}return t},Uf=(e,r,t,s,n,o,i)=>{let a=t[0].dims,l=we.size(o),c=we.size(i),p=ke("_A",t[0].dataType,a),d=it("output",n,o),u=64;l===1&&(u=256);let f=` + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},vb=(e,r)=>{$f(e.inputs,r.perm),e.compute(es(e.inputs[0],r.perm))},xb=e=>jt({perm:e.perm})}),Df,Lf,zf,Bf,Rf,Nf,jf,Vf,Uf,Wf,_s,Tb,Eb,Pb,Cb,Sb,Ib,$b,kb,Ab,Fb,dT=Ve(()=>{gt(),Ct(),St(),Iu(),cn(),Df={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"},Lf={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"},zf={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Bf={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Rf=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let o=0;oe[o]);return[t,n]},jf=(e,r)=>{let t=e.length+r.length,s=[],n=0;for(let o=0;o{for(let t=0;t{let t=[];if(!Vf(e,r)){for(let s=0;st.push(s))}return t},Wf=(e,r,t,s,n,o,i)=>{let a=t[0].dims,l=we.size(o),c=we.size(i),p=ke("_A",t[0].dataType,a),d=it("output",n,o),u=64;l===1&&(u=256);let f=` var aBestValues : array; `,_=y=>` ${y.registerUniform("reduceSize","u32").declareVariables(p,d)} @@ -104,11 +104,11 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; - var bestValue = f32(${Lf[s]}); + var bestValue = f32(${zf[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${p.getByOffset("offset + k")}); - bestValue = ${Of[s]}; + bestValue = ${Df[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); @@ -119,7 +119,7 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; - bestValue = ${Df[s]}; + bestValue = ${Lf[s]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; @@ -127,9 +127,9 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr } if (local_idx == 0u) { - ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${zf[s]})`}`)}; + ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${Bf[s]})`}`)}; } - }`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},_s=(e,r,t,s)=>{let n=e.inputs.length===1?t:ru(e.inputs,t),o=n.axes;o.length===0&&!n.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((f,_)=>_));let i=we.normalizeAxes(o,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=Vf(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(es(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=Bf(a.length,l.dims.length));let[p,d]=Rf(l.dims,a),u=p;n.keepDims&&(u=Nf(p,i)),e.compute(Uf(r,n.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},xb=(e,r)=>{_s(e,"ReduceMeanShared",r,"mean")},Tb=(e,r)=>{_s(e,"ReduceL1Shared",r,"l1")},Eb=(e,r)=>{_s(e,"ReduceL2Shared",r,"l2")},Pb=(e,r)=>{_s(e,"ReduceLogSumExpShared",r,"logSumExp")},Cb=(e,r)=>{_s(e,"ReduceMaxShared",r,"max")},Sb=(e,r)=>{_s(e,"ReduceMinShared",r,"min")},Ib=(e,r)=>{_s(e,"ReduceProdShared",r,"prod")},$b=(e,r)=>{_s(e,"ReduceSumShared",r,"sum")},kb=(e,r)=>{_s(e,"ReduceSumSquareShared",r,"sumSquare")},Ab=(e,r)=>{_s(e,"ReduceLogSumShared",r,"logSum")}}),fs,Wf,hi,ru,gs,Gf,Kf,Hf,qf,Qf,Xf,Jf,Yf,Zf,eg,Ms,Fb,Ob,Db,Lb,zb,Bb,Rb,Nb,jb,Vb,Su=Ve(()=>{gt(),Ct(),mr(),St(),dT(),fs=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.")},Wf=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],hi=(e,r,t,s,n,o,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=we.normalizeAxes(n,p),u=!a&&d.length===0;c.forEach((y,k)=>{u||d.indexOf(k)>=0?i&&l.push(1):l.push(y)});let f=l.length,_=we.size(l);return{name:e,shaderCache:r,getShaderSource:y=>{let k=[],w=ke("_A",t[0].dataType,p),v=it("output",o,f),I=s(w,v,d),T=I[2];for(let b=0,E=0;b=0?(i&&E++,T=`for(var j${b}: u32 = 0; j${b} < ${c[b]}; j${b}++) { + }`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},_s=(e,r,t,s)=>{let n=e.inputs.length===1?t:su(e.inputs,t),o=n.axes;o.length===0&&!n.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((f,_)=>_));let i=we.normalizeAxes(o,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=Uf(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(es(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=Rf(a.length,l.dims.length));let[p,d]=Nf(l.dims,a),u=p;n.keepDims&&(u=jf(p,i)),e.compute(Wf(r,n.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},Tb=(e,r)=>{_s(e,"ReduceMeanShared",r,"mean")},Eb=(e,r)=>{_s(e,"ReduceL1Shared",r,"l1")},Pb=(e,r)=>{_s(e,"ReduceL2Shared",r,"l2")},Cb=(e,r)=>{_s(e,"ReduceLogSumExpShared",r,"logSumExp")},Sb=(e,r)=>{_s(e,"ReduceMaxShared",r,"max")},Ib=(e,r)=>{_s(e,"ReduceMinShared",r,"min")},$b=(e,r)=>{_s(e,"ReduceProdShared",r,"prod")},kb=(e,r)=>{_s(e,"ReduceSumShared",r,"sum")},Ab=(e,r)=>{_s(e,"ReduceSumSquareShared",r,"sumSquare")},Fb=(e,r)=>{_s(e,"ReduceLogSumShared",r,"logSum")}}),fs,Gf,hi,su,gs,Kf,Hf,qf,Qf,Xf,Jf,Yf,Zf,eg,tg,Ms,Ob,Db,Lb,zb,Bb,Rb,Nb,jb,Vb,Ub,Iu=Ve(()=>{gt(),Ct(),mr(),St(),dT(),fs=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.")},Gf=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],hi=(e,r,t,s,n,o,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=we.normalizeAxes(n,p),u=!a&&d.length===0;c.forEach((y,k)=>{u||d.indexOf(k)>=0?i&&l.push(1):l.push(y)});let f=l.length,_=we.size(l);return{name:e,shaderCache:r,getShaderSource:y=>{let k=[],w=ke("_A",t[0].dataType,p),v=it("output",o,f),I=s(w,v,d),T=I[2];for(let b=0,E=0;b=0?(i&&E++,T=`for(var j${b}: u32 = 0; j${b} < ${c[b]}; j${b}++) { ${I[2].includes("last_index")?`let last_index = j${b};`:""} ${w.indicesSet("input_indices",b,`j${b}`)} ${T} @@ -150,19 +150,19 @@ const ii=new Map,Pn=[],vx=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.cr ${I[3]} ${I.length===4?v.setByOffset("global_idx","value"):I.slice(4).join(` `)} - }`},getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(c,l)]})}},ru=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),jt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},gs=(e,r,t,s)=>{let n=e.inputs,o=n.length===1?t:ru(n,t);e.compute(hi(r,{hint:o.cacheKey,inputDependencies:["rank"]},[n[0]],o.noopWithEmptyAxes&&o.axes.length===0?Wf:s,o.axes,n[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Gf=(e,r)=>{fs(e.inputs),gs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Kf=(e,r)=>{fs(e.inputs),gs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Hf=(e,r)=>{fs(e.inputs),gs(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},qf=(e,r)=>{fs(e.inputs),gs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Qf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMax",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(t.indicesSet("input_indices",i,0));return[`${o.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Xf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMean",r,(t,s,n)=>{let o=1;for(let i=0;i=0||n.length===0)&&(o*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${o});`]})},Jf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMin",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(`input_indices[${i}] = 0;`);return[`${o.join(` -`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Yf=(e,r)=>{fs(e.inputs),gs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Zf=(e,r)=>{fs(e.inputs),gs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},eg=(e,r)=>{fs(e.inputs),gs(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},Ms=(e,r,t)=>{if(r.length===0)return t;let s=1,n=1;for(let o=0;o1024},Fb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Xf(e,r):xb(e,r)},Ob=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Kf(e,r):Tb(e,r)},Db=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Hf(e,r):Eb(e,r)},Lb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?qf(e,r):Pb(e,r)},zb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Qf(e,r):Cb(e,r)},Bb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Jf(e,r):Sb(e,r)},Rb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Yf(e,r):Ib(e,r)},Nb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Zf(e,r):$b(e,r)},jb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?eg(e,r):kb(e,r)},Vb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Gf(e,r):Ab(e,r)}}),fc,Ub,Wb,su,pT=Ve(()=>{gt(),mr(),Su(),fc=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.")},Ub=(e,r)=>{fc(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` + }`},getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(c,l)]})}},su=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),jt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},gs=(e,r,t,s)=>{let n=e.inputs,o=n.length===1?t:su(n,t);e.compute(hi(r,{hint:o.cacheKey,inputDependencies:["rank"]},[n[0]],o.noopWithEmptyAxes&&o.axes.length===0?Gf:s,o.axes,n[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Kf=(e,r)=>{fs(e.inputs),gs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Hf=(e,r)=>{fs(e.inputs),gs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},qf=(e,r)=>{fs(e.inputs),gs(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Qf=(e,r)=>{fs(e.inputs),gs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Xf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMax",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(t.indicesSet("input_indices",i,0));return[`${o.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Jf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMean",r,(t,s,n)=>{let o=1;for(let i=0;i=0||n.length===0)&&(o*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${o});`]})},Yf=(e,r)=>{fs(e.inputs),gs(e,"ReduceMin",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(`input_indices[${i}] = 0;`);return[`${o.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Zf=(e,r)=>{fs(e.inputs),gs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},eg=(e,r)=>{fs(e.inputs),gs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},tg=(e,r)=>{fs(e.inputs),gs(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},Ms=(e,r,t)=>{if(r.length===0)return t;let s=1,n=1;for(let o=0;o1024},Ob=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Jf(e,r):Tb(e,r)},Db=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Hf(e,r):Eb(e,r)},Lb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?qf(e,r):Pb(e,r)},zb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Qf(e,r):Cb(e,r)},Bb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Xf(e,r):Sb(e,r)},Rb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Yf(e,r):Ib(e,r)},Nb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Zf(e,r):$b(e,r)},jb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?eg(e,r):kb(e,r)},Vb=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?tg(e,r):Ab(e,r)},Ub=(e,r)=>{Ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Kf(e,r):Fb(e,r)}}),gc,Wb,Gb,nu,pT=Ve(()=>{gt(),mr(),Iu(),gc=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.")},Wb=(e,r)=>{gc(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",n.setByOffset("global_idx","best_index")]};e.compute(hi("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Wb=(e,r)=>{fc(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` + }`,"",n.setByOffset("global_idx","best_index")]};e.compute(hi("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Gb=(e,r)=>{gc(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` `)}`,`var value = ${s.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { value = ${s.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",n.setByOffset("global_idx","best_index")]};e.compute(hi("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},su=e=>jt(e)}),tg,ei,rg,sg,ng,Zo,og,Gb,Iu=Ve(()=>{gt(),Ct(),Pu(),St(),tg=(e,r)=>{let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.dims[2];if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=n.dims[0]/3,u=d,f=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let I of r.qkvHiddenSizes)if(I%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==d+u+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let y=0;if(i){if(u!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(y=i.dims[3])}let k=_+y,w=-1,v=0;if(o)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ei=(e,r,t)=>r&&e?` + }`,"",n.setByOffset("global_idx","best_index")]};e.compute(hi("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},nu=e=>jt(e)}),rg,ei,sg,ng,og,Zo,ag,Kb,$u=Ve(()=>{gt(),Ct(),Cu(),St(),rg=(e,r)=>{let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.dims[2];if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(n.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=n.dims[0]/3,u=d,f=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let I of r.qkvHiddenSizes)if(I%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==d+u+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let y=0;if(i){if(u!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(y=i.dims[3])}let k=_+y,w=-1,v=0;if(o)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ei=(e,r,t)=>r&&e?` let total_sequence_length_input = u32(${r.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; @@ -175,7 +175,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas `:` ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; - `,rg=(e,r,t,s,n,o,i,a)=>{let l=ur(i?1:o),c=64,p=o/l;p{let v=it("x",e.dataType,e.dims,l),I=[v],T=i?ke("seq_lens",i.dataType,i.dims):void 0;T&&I.push(T);let b=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;b&&I.push(b);let E=jr(e.dataType),x=[{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` + `,sg=(e,r,t,s,n,o,i,a)=>{let l=ur(i?1:o),c=64,p=o/l;p{let v=it("x",e.dataType,e.dims,l),I=[v],T=i?ke("seq_lens",i.dataType,i.dims):void 0;T&&I.push(T);let b=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;b&&I.push(b);let E=jr(e.dataType),x=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${w.registerUniforms(x).declareVariables(...I)} @@ -226,7 +226,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas 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}(${E}(0)); }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:y},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:n,z:r*t},programUniforms:u})}},sg=(e,r,t,s,n,o,i,a,l)=>{let c=i+o.kvSequenceLength,p=[o.batchSize,o.numHeads,o.sequenceLength,c],d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,u,c,o.headSize]:void 0,_=o.nReps?o.nReps:1,y=o.scale===0?1/Math.sqrt(o.headSize):o.scale,k=ur(o.headSize),w=o.headSize/k,v=12,I={x:Math.ceil(c/v),y:Math.ceil(o.sequenceLength/v),z:o.batchSize*o.numHeads},T=[{type:12,data:o.sequenceLength},{type:12,data:w},{type:12,data:c},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:y},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:_}],b=d&&s&&we.size(s.dims)>0,E=["type","type"];b&&E.push("type"),n&&E.push("type"),a&&E.push("type"),l&&E.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:f,dataType:r.dataType,gpuDataType:0});let S=O=>{let F=ke("q",r.dataType,r.dims,k),H=ke("key",t.dataType,t.dims,k),W=[F,H];if(b){let le=ke("past_key",s.dataType,s.dims,k);W.push(le)}n&&W.push(ke("attention_bias",n.dataType,n.dims));let B=a?ke("seq_lens",a.dataType,a.dims):void 0;B&&W.push(B);let Y=l?ke("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&W.push(Y);let X=it("output",r.dataType,p),J=[X];d&&J.push(it("present_key",r.dataType,f,k));let re=jr(1,k),ne=[{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` + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:y},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:n,z:r*t},programUniforms:u})}},ng=(e,r,t,s,n,o,i,a,l)=>{let c=i+o.kvSequenceLength,p=[o.batchSize,o.numHeads,o.sequenceLength,c],d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,u,c,o.headSize]:void 0,_=o.nReps?o.nReps:1,y=o.scale===0?1/Math.sqrt(o.headSize):o.scale,k=ur(o.headSize),w=o.headSize/k,v=12,I={x:Math.ceil(c/v),y:Math.ceil(o.sequenceLength/v),z:o.batchSize*o.numHeads},T=[{type:12,data:o.sequenceLength},{type:12,data:w},{type:12,data:c},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:y},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:_}],b=d&&s&&we.size(s.dims)>0,E=["type","type"];b&&E.push("type"),n&&E.push("type"),a&&E.push("type"),l&&E.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:f,dataType:r.dataType,gpuDataType:0});let S=O=>{let F=ke("q",r.dataType,r.dims,k),H=ke("key",t.dataType,t.dims,k),W=[F,H];if(b){let le=ke("past_key",s.dataType,s.dims,k);W.push(le)}n&&W.push(ke("attention_bias",n.dataType,n.dims));let B=a?ke("seq_lens",a.dataType,a.dims):void 0;B&&W.push(B);let Y=l?ke("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&W.push(Y);let X=it("output",r.dataType,p),J=[X];d&&J.push(it("present_key",r.dataType,f,k));let re=jr(1,k),ne=[{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<${F.type.storage}, ${v*v}>; @@ -283,7 +283,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas var sum: f32 = ${(()=>{switch(k){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${k}`)}})()}; output[outputIdx] = ${X.type.value} (sum * uniforms.alpha) + ${n?"attention_bias[outputIdx]":"0.0"}; } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${n!==void 0};${s!==void 0};${e}`,inputDependencies:E},getRunData:()=>({outputs:x,dispatchGroup:I,programUniforms:T}),getShaderSource:S}},ng=(e,r,t,s,n,o,i=void 0,a=void 0)=>{let l=o+n.kvSequenceLength,c=n.nReps?n.nReps:1,p=n.vHiddenSize*c,d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,u,l,n.headSize]:void 0,_=[n.batchSize,n.sequenceLength,p],y=12,k={x:Math.ceil(n.vHeadSize/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},w=[{type:12,data:n.sequenceLength},{type:12,data:l},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:12,data:p},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:c}],v=d&&s&&we.size(s.dims)>0,I=["type","type"];v&&I.push("type"),i&&I.push("type"),a&&I.push("type");let T=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&T.push({dims:f,dataType:r.dataType,gpuDataType:0});let b=E=>{let x=ke("probs",r.dataType,r.dims),S=ke("v",t.dataType,t.dims),O=[x,S];v&&O.push(ke("past_value",s.dataType,s.dims));let F=i?ke("seq_lens",i.dataType,i.dims):void 0;i&&O.push(F);let H=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(H);let W=[it("output",r.dataType,_)];d&&W.push(it("present_value",r.dataType,f));let B=[{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` + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${n!==void 0};${s!==void 0};${e}`,inputDependencies:E},getRunData:()=>({outputs:x,dispatchGroup:I,programUniforms:T}),getShaderSource:S}},og=(e,r,t,s,n,o,i=void 0,a=void 0)=>{let l=o+n.kvSequenceLength,c=n.nReps?n.nReps:1,p=n.vHiddenSize*c,d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,u,l,n.headSize]:void 0,_=[n.batchSize,n.sequenceLength,p],y=12,k={x:Math.ceil(n.vHeadSize/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},w=[{type:12,data:n.sequenceLength},{type:12,data:l},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:12,data:p},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:c}],v=d&&s&&we.size(s.dims)>0,I=["type","type"];v&&I.push("type"),i&&I.push("type"),a&&I.push("type");let T=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&T.push({dims:f,dataType:r.dataType,gpuDataType:0});let b=E=>{let x=ke("probs",r.dataType,r.dims),S=ke("v",t.dataType,t.dims),O=[x,S];v&&O.push(ke("past_value",s.dataType,s.dims));let F=i?ke("seq_lens",i.dataType,i.dims):void 0;i&&O.push(F);let H=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(H);let W=[it("output",r.dataType,_)];d&&W.push(it("present_value",r.dataType,f));let B=[{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 = ${y}u; var tileQ: array<${x.type.value}, ${y*y}>; var tileV: array<${x.type.value}, ${y*y}>; @@ -338,7 +338,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas + headIdx * uniforms.N + n; output[outputIdx] = value; } - }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:I},getRunData:()=>({outputs:T,dispatchGroup:k,programUniforms:w}),getShaderSource:b}},Zo=(e,r,t,s,n,o,i,a,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=u>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,y=l&&we.size(l.dims)>0?l:void 0,k=[r,t];u>1&&i&&we.size(i.dims)>0&&k.push(i),y&&k.push(y),p&&k.push(p),d&&k.push(d);let w=e.compute(sg(u,r,t,i,y,c,f,p,d),{inputs:k,outputs:u>1?[-1,1]:[-1]})[0];e.compute(rg(w,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let v=[w,s];u>1&&a&&we.size(a.dims)>0&&v.push(a),p&&v.push(p),d&&v.push(d),e.compute(ng(u,w,s,a,c,f,p,d),{inputs:v,outputs:u>1?[0,2]:[0]})},og=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,n=r.inputHiddenSize,o=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:n},{type:12,data:o},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=it("output_q",l[0].dataType,t),f=it("output_k",l[0].dataType,t),_=it("output_v",l[0].dataType,t),y=ke("input",l[0].dataType,l[0].dims),k=ke("weight",l[1].dataType,l[1].dims),w=ke("bias",l[2].dataType,l[2].dims),v=y.type.storage,I=[{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` + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:I},getRunData:()=>({outputs:T,dispatchGroup:k,programUniforms:w}),getShaderSource:b}},Zo=(e,r,t,s,n,o,i,a,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=u>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,y=l&&we.size(l.dims)>0?l:void 0,k=[r,t];u>1&&i&&we.size(i.dims)>0&&k.push(i),y&&k.push(y),p&&k.push(p),d&&k.push(d);let w=e.compute(ng(u,r,t,i,y,c,f,p,d),{inputs:k,outputs:u>1?[-1,1]:[-1]})[0];e.compute(sg(w,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let v=[w,s];u>1&&a&&we.size(a.dims)>0&&v.push(a),p&&v.push(p),d&&v.push(d),e.compute(og(u,w,s,a,c,f,p,d),{inputs:v,outputs:u>1?[0,2]:[0]})},ag=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,n=r.inputHiddenSize,o=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:n},{type:12,data:o},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=it("output_q",l[0].dataType,t),f=it("output_k",l[0].dataType,t),_=it("output_v",l[0].dataType,t),y=ke("input",l[0].dataType,l[0].dims),k=ke("weight",l[1].dataType,l[1].dims),w=ke("bias",l[2].dataType,l[2].dims),v=y.type.storage,I=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` const TILE_SIZE = ${i}u; var tileInput: array<${v}, ${i*i}>; var tileWeightQ: array<${v}, ${i*i}>; @@ -393,7 +393,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas output_k[outputIdx] = valueK; output_v[outputIdx] = valueV; } - }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Gb=(e,r)=>{let t=tg(e.inputs,r),[s,n,o]=og(e,t);return Zo(e,s,n,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),ag,ig,lg,Kb,mT=Ve(()=>{Es(),gt(),Ct(),mr(),St(),ag=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,n,o)=>{let i=n.length;if(i!==s.length)throw new Error(`${o}: num dimensions != ${i}`);n.forEach((a,l)=>{if(a!==s[l])throw new Error(`${o}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},ig=(e,r)=>{let{epsilon:t,spatial:s,format:n}=r,o=e[0].dims,i=s?ur(o[o.length-1]):1,a=n==="NHWC"&&o.length>1?i:1,l=we.size(o)/i,c=s,p=c?o.length:o,d=ke("x",e[0].dataType,e[0].dims,i),u=ke("scale",e[1].dataType,e[1].dims,a),f=ke("bias",e[2].dataType,e[2].dims,a),_=ke("inputMean",e[3].dataType,e[3].dims,a),y=ke("inputVar",e[4].dataType,e[4].dims,a),k=it("y",e[0].dataType,p,i),w=()=>{let I="";if(s)I=`let cOffset = ${o.length===1?"0u":n==="NHWC"?`outputIndices[${o.length-1}] / ${i}`:"outputIndices[1]"};`;else if(n==="NCHW")I=` + }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Kb=(e,r)=>{let t=rg(e.inputs,r),[s,n,o]=ag(e,t);return Zo(e,s,n,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),ig,lg,cg,Hb,mT=Ve(()=>{Es(),gt(),Ct(),mr(),St(),ig=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,n,o)=>{let i=n.length;if(i!==s.length)throw new Error(`${o}: num dimensions != ${i}`);n.forEach((a,l)=>{if(a!==s[l])throw new Error(`${o}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},lg=(e,r)=>{let{epsilon:t,spatial:s,format:n}=r,o=e[0].dims,i=s?ur(o[o.length-1]):1,a=n==="NHWC"&&o.length>1?i:1,l=we.size(o)/i,c=s,p=c?o.length:o,d=ke("x",e[0].dataType,e[0].dims,i),u=ke("scale",e[1].dataType,e[1].dims,a),f=ke("bias",e[2].dataType,e[2].dims,a),_=ke("inputMean",e[3].dataType,e[3].dims,a),y=ke("inputVar",e[4].dataType,e[4].dims,a),k=it("y",e[0].dataType,p,i),w=()=>{let I="";if(s)I=`let cOffset = ${o.length===1?"0u":n==="NHWC"?`outputIndices[${o.length-1}] / ${i}`:"outputIndices[1]"};`;else if(n==="NCHW")I=` ${k.indicesSet("outputIndices","0","0")} let cOffset = ${k.indicesToOffset("outputIndices")};`;else{I=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${o.length-1}];`;for(let T=1;T` @@ -410,7 +410,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas let x = ${d.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${k.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...ct(o)]:[{type:12,data:l}]})}},lg=e=>jt(e),Kb=(e,r)=>{let{inputs:t,outputCount:s}=e,n=lg({...r,outputCount:s});if(Jt.webgpu.validateInputContent&&ag(t,n),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(ig(t,n))}}),cg,ug,Hb,hT=Ve(()=>{Ct(),St(),cg=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")},ug=e=>{let r=e[0].dims,t=e[0].dims[2],s=we.size(r)/4,n=e[0].dataType,o=ke("input",n,r,4),i=ke("bias",n,[t],4),a=ke("residual",n,r,4),l=it("output",n,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>` + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,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(l/64)},programUniforms:c?[{type:12,data:l},...ct(o)]:[{type:12,data:l}]})}},cg=e=>jt(e),Hb=(e,r)=>{let{inputs:t,outputCount:s}=e,n=cg({...r,outputCount:s});if(Jt.webgpu.validateInputContent&&ig(t,n),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(lg(t,n))}}),ug,dg,qb,hT=Ve(()=>{Ct(),St(),ug=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")},dg=e=>{let r=e[0].dims,t=e[0].dims[2],s=we.size(r)/4,n=e[0].dataType,o=ke("input",n,r,4),i=ke("bias",n,[t],4),a=ke("residual",n,r,4),l=it("output",n,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>` const channels = ${t}u / 4; ${c.declareVariables(o,i,a,l)} @@ -419,7 +419,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas let value = ${o.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} - }`}},Hb=e=>{cg(e.inputs),e.compute(ug(e.inputs))}}),dg,Bt,qb,Qb,Xb,Jb,Yb,Zb,ey,ty,ry,pg,sy,ny,oy,ay,qo,iy,ui,ly,cy,uy,dy,py,my,hy,_y,fy,gy,My,wy,by,yy,vy,xy,gc,Ty,nu,ou,Ey,Py,Cy,mg,hg,Sy,$u=Ve(()=>{gt(),Ct(),mr(),St(),dg=(e,r,t,s,n,o,i)=>{let a=Math.ceil(r/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let c=ke("inputData",t,[a],4),p=it("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` + }`}},qb=e=>{ug(e.inputs),e.compute(dg(e.inputs))}}),pg,Bt,Qb,Xb,Jb,Yb,Zb,ey,ty,ry,sy,mg,ny,oy,ay,iy,qo,ly,ui,cy,uy,dy,py,my,hy,_y,fy,gy,My,wy,by,yy,vy,xy,Ty,Mc,Ey,ou,au,Py,Cy,Sy,hg,_g,Iy,ku=Ve(()=>{gt(),Ct(),mr(),St(),pg=(e,r,t,s,n,o,i)=>{let a=Math.ceil(r/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let c=ke("inputData",t,[a],4),p=it("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` ${e.registerUniforms(d).declareVariables(c,p)} ${o??""} @@ -429,7 +429,7 @@ var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLas let a = ${c.getByOffset("global_idx")}; ${p.setByOffset("global_idx",l)} - }`},Bt=(e,r,t,s,n,o=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(we.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:c=>dg(c,we.size(e.dims),e.dataType,o,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(we.size(c[0].dims)/64/4)},programUniforms:l})}},qb=e=>{e.compute(Bt(e.inputs[0],"Abs","abs"))},Qb=e=>{e.compute(Bt(e.inputs[0],"Acos","acos"))},Xb=e=>{e.compute(Bt(e.inputs[0],"Acosh","acosh"))},Jb=e=>{e.compute(Bt(e.inputs[0],"Asin","asin"))},Yb=e=>{e.compute(Bt(e.inputs[0],"Asinh","asinh"))},Zb=e=>{e.compute(Bt(e.inputs[0],"Atan","atan"))},ey=e=>{e.compute(Bt(e.inputs[0],"Atanh","atanh"))},ty=e=>jt(e),ry=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute(Bt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},pg=e=>{let r,t,s=e.length>=2&&e[1].data!==0,n=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=n?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=n?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return jt({min:r,max:t})},sy=(e,r)=>{let t=r||pg(e.inputs),s=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Clip",n=>`clamp(${n}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},ny=e=>{e.compute(Bt(e.inputs[0],"Ceil","ceil"))},oy=e=>{e.compute(Bt(e.inputs[0],"Cos","cos"))},ay=e=>{e.compute(Bt(e.inputs[0],"Cosh","cosh"))},qo=e=>jt(e),iy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + }`},Bt=(e,r,t,s,n,o=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(we.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:c=>pg(c,we.size(e.dims),e.dataType,o,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(we.size(c[0].dims)/64/4)},programUniforms:l})}},Qb=e=>{e.compute(Bt(e.inputs[0],"Abs","abs"))},Xb=e=>{e.compute(Bt(e.inputs[0],"Acos","acos"))},Jb=e=>{e.compute(Bt(e.inputs[0],"Acosh","acosh"))},Yb=e=>{e.compute(Bt(e.inputs[0],"Asin","asin"))},Zb=e=>{e.compute(Bt(e.inputs[0],"Asinh","asinh"))},ey=e=>{e.compute(Bt(e.inputs[0],"Atan","atan"))},ty=e=>{e.compute(Bt(e.inputs[0],"Atanh","atanh"))},ry=e=>jt(e),sy=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute(Bt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},mg=e=>{let r,t,s=e.length>=2&&e[1].data!==0,n=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=n?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=n?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return jt({min:r,max:t})},ny=(e,r)=>{let t=r||mg(e.inputs),s=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Clip",n=>`clamp(${n}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},oy=e=>{e.compute(Bt(e.inputs[0],"Ceil","ceil"))},ay=e=>{e.compute(Bt(e.inputs[0],"Cos","cos"))},iy=e=>{e.compute(Bt(e.inputs[0],"Cosh","cosh"))},qo=e=>jt(e),ly=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` const elu_alpha_ = ${t}(${r.alpha}); fn elu_f32(a: ${t}) -> ${t} { @@ -450,15 +450,15 @@ 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)); -}`,ly=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ui(r)))},cy=e=>{e.compute(Bt(e.inputs[0],"Exp","exp"))},uy=e=>{e.compute(Bt(e.inputs[0],"Floor","floor"))},dy=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ui(r)))},py=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},my=e=>{e.compute(Bt(e.inputs[0],"Not",r=>`!${r}`))},hy=e=>{e.compute(Bt(e.inputs[0],"Neg",r=>`-${r}`))},_y=e=>{e.compute(Bt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},fy=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},gy=e=>{e.compute(Bt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},My=e=>jt(e),wy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},by=e=>{e.compute(Bt(e.inputs[0],"Sin","sin"))},yy=e=>{e.compute(Bt(e.inputs[0],"Sinh","sinh"))},vy=e=>{e.compute(Bt(e.inputs[0],"Sqrt","sqrt"))},xy=e=>{e.compute(Bt(e.inputs[0],"Tan","tan"))},gc=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ty=e=>{e.compute(Bt(e.inputs[0],"Tanh",gc))},nu=(e="f32")=>` +}`,cy=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ui(r)))},uy=e=>{e.compute(Bt(e.inputs[0],"Exp","exp"))},dy=e=>{e.compute(Bt(e.inputs[0],"Floor","floor"))},py=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ui(r)))},my=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},hy=e=>{e.compute(Bt(e.inputs[0],"Not",r=>`!${r}`))},_y=e=>{e.compute(Bt(e.inputs[0],"Neg",r=>`-${r}`))},fy=e=>{e.compute(Bt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},gy=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},My=e=>{e.compute(Bt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},wy=e=>jt(e),by=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},yy=e=>{e.compute(Bt(e.inputs[0],"Sin","sin"))},vy=e=>{e.compute(Bt(e.inputs[0],"Sinh","sinh"))},xy=e=>{e.compute(Bt(e.inputs[0],"Sqrt","sqrt"))},Ty=e=>{e.compute(Bt(e.inputs[0],"Tan","tan"))},Mc=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ey=e=>{e.compute(Bt(e.inputs[0],"Tanh",Mc))},ou=(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 ${gc("v")}; + return ${Mc("v")}; } -`,ou=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Ey=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"FastGelu",ou,nu(r),void 0,e.inputs[0].dataType))},Py=(e,r)=>{let t=jr(e.inputs[0].dataType);return e.compute(Bt(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},Cy=e=>{e.compute(Bt(e.inputs[0],"Log","log"))},mg=(e,r)=>` +`,au=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Py=e=>{let r=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"FastGelu",au,ou(r),void 0,e.inputs[0].dataType))},Cy=(e,r)=>{let t=jr(e.inputs[0].dataType);return e.compute(Bt(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},Sy=e=>{e.compute(Bt(e.inputs[0],"Log","log"))},hg=(e,r)=>` const alpha = vec4<${e}>(${r}); const one = ${e}(1.0); const zero = ${e}(0.0); @@ -475,7 +475,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } return x * x1; } -`,hg=e=>`quick_gelu_impl(${e})`,Sy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"QuickGelu",hg,mg(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),_g,fg,Iy,_T=Ve(()=>{Ct(),St(),$u(),_g=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")},fg=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=ke("input",e[0].dataType,e[0].dims,4),s=ke("bias",e[0].dataType,[e[0].dims[2]],4),n=it("output",e[0].dataType,r,4),o=we.size(r)/4,i=Ar(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:a=>` +`,_g=e=>`quick_gelu_impl(${e})`,Iy=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Bt(e.inputs[0],"QuickGelu",_g,hg(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),fg,gg,$y,_T=Ve(()=>{Ct(),St(),ku(),fg=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")},gg=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=ke("input",e[0].dataType,e[0].dims,4),s=ke("bias",e[0].dataType,[e[0].dims[2]],4),n=it("output",e[0].dataType,r,4),o=we.size(r)/4,i=Ar(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:a=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; @@ -493,7 +493,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${n.setByOffset("global_idx","valueLeft * geluRight")} - }`}},Iy=e=>{_g(e.inputs),e.compute(fg(e.inputs))}}),gg,Mg,ws,$y,ky,Ay,Fy,Oy,Dy,Ly,zy,By,Ry,fT=Ve(()=>{gt(),Ct(),St(),gg=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(v,I)=>`${a}((${v}),(${I}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=it("outputData",p,s.length,4),y=ke("aData",l,r.length,4),k=ke("bData",c,t.length,4),w;if(n)if(o){let v=we.size(r)===1,I=we.size(t)===1,T=r.length>0&&r[r.length-1]%4===0,b=t.length>0&&t[t.length-1]%4===0;v||I?w=_.setByOffset("global_idx",f(v?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"),I?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` + }`}},$y=e=>{fg(e.inputs),e.compute(gg(e.inputs))}}),Mg,wg,ws,ky,Ay,Fy,Oy,Dy,Ly,zy,By,Ry,Ny,fT=Ve(()=>{gt(),Ct(),St(),Mg=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(v,I)=>`${a}((${v}),(${I}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=it("outputData",p,s.length,4),y=ke("aData",l,r.length,4),k=ke("bData",c,t.length,4),w;if(n)if(o){let v=we.size(r)===1,I=we.size(t)===1,T=r.length>0&&r[r.length-1]%4===0,b=t.length>0&&t[t.length-1]%4===0;v||I?w=_.setByOffset("global_idx",f(v?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"),I?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; let offsetA = ${y.broadcastedIndicesToOffset("outputIndices",_)}; let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; @@ -526,7 +526,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${w} - }`},Mg=(e,r,t,s,n,o,i=t.dataType)=>{let a=t.dims.map(y=>Number(y)??1),l=s.dims.map(y=>Number(y)??1),c=!we.areEqual(a,l),p=a,d=we.size(a),u=!1,f=!1,_=[c];if(c){let y=lo.calcShape(a,l,!1);if(!y)throw new Error("Can't perform binary op on the given tensors");p=y.slice(),d=we.size(p);let k=we.size(a)===1,w=we.size(l)===1,v=a.length>0&&a[a.length-1]%4===0,I=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(w),_.push(v),_.push(I);let T=1;for(let b=1;by.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:y=>gg(y,a,l,p,u,c,f,n,t.dataType,s.dataType,i,o),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(we.size(p)/4)},...ct(a,l,p)]})}},ws=(e,r,t,s,n,o)=>{e.compute(Mg(r,n??"",e.inputs[0],e.inputs[1],t,s,o))},$y=e=>{ws(e,"Add",(r,t)=>`${r}+${t}`)},ky=e=>{ws(e,"Div",(r,t)=>`${r}/${t}`)},Ay=e=>{ws(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Fy=e=>{ws(e,"Mul",(r,t)=>`${r}*${t}`)},Oy=e=>{let r=ke("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ws(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + }`},wg=(e,r,t,s,n,o,i=t.dataType)=>{let a=t.dims.map(y=>Number(y)??1),l=s.dims.map(y=>Number(y)??1),c=!we.areEqual(a,l),p=a,d=we.size(a),u=!1,f=!1,_=[c];if(c){let y=lo.calcShape(a,l,!1);if(!y)throw new Error("Can't perform binary op on the given tensors");p=y.slice(),d=we.size(p);let k=we.size(a)===1,w=we.size(l)===1,v=a.length>0&&a[a.length-1]%4===0,I=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(w),_.push(v),_.push(I);let T=1;for(let b=1;by.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:y=>Mg(y,a,l,p,u,c,f,n,t.dataType,s.dataType,i,o),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(we.size(p)/4)},...ct(a,l,p)]})}},ws=(e,r,t,s,n,o)=>{e.compute(wg(r,n??"",e.inputs[0],e.inputs[1],t,s,o))},ky=e=>{ws(e,"Add",(r,t)=>`${r}+${t}`)},Ay=e=>{ws(e,"Div",(r,t)=>`${r}/${t}`)},Fy=e=>{ws(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Oy=e=>{ws(e,"Mul",(r,t)=>`${r}*${t}`)},Dy=e=>{let r=ke("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ws(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` fn pow_custom(a : ${r}, b : ${r}) -> ${r} { if (b == ${r}(0.0)) { return ${r}(1.0); @@ -539,7 +539,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${r}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } - `)},Dy=e=>{ws(e,"Sub",(r,t)=>`${r}-${t}`)},Ly=e=>{ws(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},zy=e=>{ws(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},By=e=>{ws(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Ry=e=>{ws(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),wg,bg,yg,vg,Ny,jy,gT=Ve(()=>{gt(),Ct(),mr(),St(),wg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],n=s.dataType,o=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==n)throw new Error("input tensors should be one type");if(i.dims.length!==o)throw new Error("input tensors should have the same shape");i.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},bg=(e,r)=>` + `)},Ly=e=>{ws(e,"Sub",(r,t)=>`${r}-${t}`)},zy=e=>{ws(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},By=e=>{ws(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Ry=e=>{ws(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Ny=e=>{ws(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),bg,yg,vg,xg,jy,Vy,gT=Ve(()=>{gt(),Ct(),mr(),St(),bg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],n=s.dataType,o=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==n)throw new Error("input tensors should be one type");if(i.dims.length!==o)throw new Error("input tensors should have the same shape");i.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},yg=(e,r)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${r}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { @@ -548,12 +548,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } } return ${e}u; - }`,yg=(e,r)=>{let t=e.length,s=[];for(let n=0;n{let n=we.size(t),o=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:n}];for(let y=0;y`uniforms.sizeInConcatAxis${y}`).join(","),_=y=>` + }`,vg=(e,r)=>{let t=e.length,s=[];for(let n=0;n{let n=we.size(t),o=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:n}];for(let y=0;y`uniforms.sizeInConcatAxis${y}`).join(","),_=y=>` ${(()=>{y.registerUniform("outputSize","u32");for(let k=0;k) -> vec4<${e}> { ${u} -= sizeInConcatAxis[inputIndex - 1u]; } - ${yg(i,d)} - }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}),getShaderSource:_}},Ny=(e,r)=>{let t=e.inputs,s=t[0].dims,n=we.normalizeAxis(r.axis,s.length);wg(t,n);let o=s.slice();o[n]=t.reduce((a,l)=>a+(l.dims.length>n?l.dims[n]:0),0);let i=t.filter(a=>we.size(a.dims)>0);e.compute(vg(i,n,o,t[0].dataType),{inputs:i})},jy=e=>jt({axis:e.axis})}),$n,kn,An,ku,On=Ve(()=>{gt(),Ct(),$n=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + ${vg(i,d)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}),getShaderSource:_}},jy=(e,r)=>{let t=e.inputs,s=t[0].dims,n=we.normalizeAxis(r.axis,s.length);bg(t,n);let o=s.slice();o[n]=t.reduce((a,l)=>a+(l.dims.length>n?l.dims[n]:0),0);let i=t.filter(a=>we.size(a.dims)>0);e.compute(xg(i,n,o,t[0].dataType),{inputs:i})},Vy=e=>jt({axis:e.axis})}),$n,kn,An,Au,On=Ve(()=>{gt(),Ct(),$n=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); - `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},kn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},An=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},ku=e=>{let r=e?.activation||"";if(r==="HardSigmoid"){let[t,s]=e?.activation_params||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=e?.activation_params||[mb,hb];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=e?.activation_params||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Fr,Vy,Au=Ve(()=>{Fr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},Vy=e=>` + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},kn=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},An=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},Au=e=>{let r=e?.activation||"";if(r==="HardSigmoid"){let[t,s]=e?.activation_params||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=e?.activation_params||[hb,_b];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=e?.activation_params||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Fr,Uy,Fu=Ve(()=>{Fr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},Uy=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),Uy,MT=Ve(()=>{Uy=e=>` + `}),Wy,MT=Ve(()=>{Wy=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)); @@ -580,14 +580,14 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } -`}),Xo,Fu,Ou=Ve(()=>{gt(),Ct(),St(),On(),Xo=(e,r,t,s,n)=>{let o=s-t;return` +`}),Xo,Ou,Du=Ve(()=>{gt(),Ct(),St(),On(),Xo=(e,r,t,s,n)=>{let o=s-t;return` ${Array.from({length:t}).map((i,a)=>` if (${lt(r.shape,a,r.rank)} != 1) { ${r.indicesSet(e,a,lt(n,a+o,s))} } else { ${r.indicesSet(e,a,0)} }`).join("")} -`},Fu=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],c=a[a.length-1],p=i[i.length-1],d=ur(c),u=ur(p),f=ur(l),_=we.size(t)/d/f,y=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[we.size(k),l,c],v=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];kn(r,v),v.push(...ct(k,i,a)),y&&v.push(...ct(e[2].dims)),v.push(...ct(w));let I=T=>{let b=Cu("batch_dims",e[0].dataType,k.length),E=ke("a",e[0].dataType,i.length,u),x=ke("b",e[1].dataType,a.length,d),S=it("output",e[0].dataType,w.length,d),O=Ar(S.type.tensor),F=$n(r,S.type.value,O),H=[E,x],W="";if(y){let X=n?d:1;H.push(ke("bias",e[2].dataType,e[2].dims.length,X)),W=`${n?`value += bias[col / ${X}];`:`value += ${S.type.value}(bias[row + i]);`}`}let B=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];An(r,B);let Y=()=>{let X=`var a_data: ${E.type.value};`;for(let J=0;J{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],c=a[a.length-1],p=i[i.length-1],d=ur(c),u=ur(p),f=ur(l),_=we.size(t)/d/f,y=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[we.size(k),l,c],v=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];kn(r,v),v.push(...ct(k,i,a)),y&&v.push(...ct(e[2].dims)),v.push(...ct(w));let I=T=>{let b=Su("batch_dims",e[0].dataType,k.length),E=ke("a",e[0].dataType,i.length,u),x=ke("b",e[1].dataType,a.length,d),S=it("output",e[0].dataType,w.length,d),O=Ar(S.type.tensor),F=$n(r,S.type.value,O),H=[E,x],W="";if(y){let X=n?d:1;H.push(ke("bias",e[2].dataType,e[2].dims.length,X)),W=`${n?`value += bias[col / ${X}];`:`value += ${S.type.value}(bias[row + i]);`}`}let B=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];An(r,B);let Y=()=>{let X=`var a_data: ${E.type.value};`;for(let J=0;J) -> i32 { ${S.setByOffset(`offset / ${d}`,"value")}; } } - `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${u};${f};${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:I}}}),xg,Tg,au,Mc,Eg,iu,Pg,_i,Du=Ve(()=>{gt(),Ct(),St(),On(),Ou(),Au(),xg=(e,r)=>e?` + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${u};${f};${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:I}}}),Tg,Eg,iu,wc,Pg,lu,Cg,_i,Lu=Ve(()=>{gt(),Ct(),St(),On(),Du(),Fu(),Tg=(e,r)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); @@ -634,7 +634,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${r?", batchIndices":""}); - `,Tg=(e,r)=>e?` + `,Eg=(e,r)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; @@ -651,7 +651,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,au=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=n?l:o,d=n?o:l,u=p/r[0],f=o/r[1];if(!((n&&u===4&&e[1]===4||!n&&(u===3||u===4))&&p%r[0]===0&&o%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. + }`,iu=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=n?l:o,d=n?o:l,u=p/r[0],f=o/r[1];if(!((n&&u===4&&e[1]===4||!n&&(u===3||u===4))&&p%r[0]===0&&o%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${u} must be 3 or 4. tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${p/u}>, ${d}>; @@ -688,7 +688,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; - ${xg(n,s)} + ${Tg(n,s)} } // Load one tile of B into local memory. @@ -707,7 +707,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - ${Tg(n,u)} + ${Eg(n,u)} } workgroupBarrier(); @@ -716,7 +716,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } -}`},Mc=(e,r)=>e?` +}`},wc=(e,r)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${r?", batchIndices":""}); @@ -724,7 +724,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${r?", batchIndices":""}); - `,Eg=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",iu=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=n?c:o,u=n?o:c;if(!(u%r[1]===0&&d%r[0]===0&&o%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${o} must be divisible by workgroupSize[1]${r[1]}`);let f=u/r[1],_=d/r[0],y=o/r[1],k=l?` + `,Pg=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",lu=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=n?c:o,u=n?o:c;if(!(u%r[1]===0&&d%r[0]===0&&o%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${o} must be divisible by workgroupSize[1]${r[1]}`);let f=u/r[1],_=d/r[0],y=o/r[1],k=l?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${c}; @@ -735,7 +735,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${r[1]}) { for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { - ${Mc(n,s)} + ${wc(n,s)} } } // Load one tile of B into local memory. @@ -790,7 +790,7 @@ for (var t = 0; t < num_tiles; t = t + 1) { for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; - ${Mc(n,s)} + ${wc(n,s)} } } @@ -815,7 +815,7 @@ for (var t = 0; t < num_tiles; t = t + 1) { } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${Eg(n)} + ${Pg(n)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } @@ -850,7 +850,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, var acc : array, rowPerThread>; ${k} } -`},Pg=(e,r,t,s,n=!1)=>{let[o,i,a,l]=s,c=Ar(s[0].type.tensor);return` +`},Cg=(e,r,t,s,n=!1)=>{let[o,i,a,l]=s,c=Ar(s[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${Fr(e,c)} { var value = ${Fr(e,c)}(0.0); let col = colIn * ${e}; @@ -889,11 +889,11 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${l.setByIndices("vec3(coords)","value")} } } - `},_i=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),c=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=we.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],y=f%4===0&&_%4===0,k=u<=8?[4,1,1]:[4,4,1],w=[8,8,1],v=[Math.ceil(_/w[0]/k[0]),Math.ceil(u/w[1]/k[1]),Math.ceil(d/w[2]/k[2])],I=y?4:1,T=[...l,u,f/I],b=T.length,E=[...c,f,_/I],x=E.length,S=[d,u,_/I],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];kn(r,O),O.push(...ct(p,T,E));let F=["rank","rank"],H=e.length>2;H&&(O.push(...ct(e[2].dims)),F.push("rank")),O.push(...ct(S));let W=B=>{let Y=p.length,X=Cu("batchDims",e[0].dataType,Y,1),J=Ar(e[0].dataType),re=ke("a",e[0].dataType,b,I),ne=ke("b",e[1].dataType,x,I),le=it("result",e[0].dataType,S.length,I),pe=[re,ne];if(H){let te=n?I:1;pe.push(ke("bias",e[2].dataType,e[2].dims.length,te))}let oe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];An(r,oe);let K=Ar(le.type.tensor),N=$n(r,le.type.value,K),D=Pg(I,H,N,[X,re,ne,le],n);return` + `},_i=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),c=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=we.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],y=f%4===0&&_%4===0,k=u<=8?[4,1,1]:[4,4,1],w=[8,8,1],v=[Math.ceil(_/w[0]/k[0]),Math.ceil(u/w[1]/k[1]),Math.ceil(d/w[2]/k[2])],I=y?4:1,T=[...l,u,f/I],b=T.length,E=[...c,f,_/I],x=E.length,S=[d,u,_/I],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];kn(r,O),O.push(...ct(p,T,E));let F=["rank","rank"],H=e.length>2;H&&(O.push(...ct(e[2].dims)),F.push("rank")),O.push(...ct(S));let W=B=>{let Y=p.length,X=Su("batchDims",e[0].dataType,Y,1),J=Ar(e[0].dataType),re=ke("a",e[0].dataType,b,I),ne=ke("b",e[1].dataType,x,I),le=it("result",e[0].dataType,S.length,I),pe=[re,ne];if(H){let te=n?I:1;pe.push(ke("bias",e[2].dataType,e[2].dims.length,te))}let oe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];An(r,oe);let K=Ar(le.type.tensor),N=$n(r,le.type.value,K),D=Cg(I,H,N,[X,re,ne,le],n);return` ${B.registerUniforms(oe).registerInternalVariables(X).declareVariables(...pe,le)} ${D} - ${y?au(k,w,J,X):iu(k,w,J,X)} - `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${y};${n}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:O}),getShaderSource:W}}}),Cg,Wy,wT=Ve(()=>{gt(),Hs(),St(),On(),Au(),MT(),Du(),Cg=(e,r,t,s,n=!1,o,i=4,a=4,l=4,c="f32")=>{let p=O=>{switch(O){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},d=O=>{switch(O){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},u=e?` + ${y?iu(k,w,J,X):lu(k,w,J,X)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${y};${n}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:O}),getShaderSource:W}}}),Sg,Gy,wT=Ve(()=>{gt(),Hs(),St(),On(),Fu(),MT(),Lu(),Sg=(e,r,t,s,n=!1,o,i=4,a=4,l=4,c="f32")=>{let p=O=>{switch(O){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},d=O=>{switch(O){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); @@ -968,11 +968,11 @@ fn main(@builtin(local_invocation_id) localId : vec3, var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${f} - ${Vy(n)} + ${Uy(n)} ${S} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } - }`},Wy=(e,r,t,s,n,o,i,a,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],y=c&&(p%4===0||p%3===0)&&_%4===0,k=c?_:u*f,w=c?u*f:_,v=[8,8,1],I=s<=8?[4,1,1]:[4,4,1],T=[Math.ceil(k/v[0]/I[0]),Math.ceil(w/v[1]/I[1]),Math.ceil(d/v[2]/I[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let b=y?c&&p%4!==0?3:4:1,E=v[1]*I[1],x=v[0]*I[0],S=Math.max(v[0]*b,v[1]),O=s%E===0,F=n%x===0,H=o%S===0,W=y?[b,4,4]:[1,1,1],B=[{type:6,data:s},{type:6,data:n},{type:6,data:o},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];kn(r,B),B.push(...ct(e[0].dims,e[1].dims));let Y=["rank","rank"];i&&(B.push(...ct(e[2].dims)),Y.push("rank")),B.push(...ct(t));let X=J=>{let re=[{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}];An(r,re);let ne=y?4:1,le=Ar(e[0].dataType),pe=` + }`},Gy=(e,r,t,s,n,o,i,a,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],y=c&&(p%4===0||p%3===0)&&_%4===0,k=c?_:u*f,w=c?u*f:_,v=[8,8,1],I=s<=8?[4,1,1]:[4,4,1],T=[Math.ceil(k/v[0]/I[0]),Math.ceil(w/v[1]/I[1]),Math.ceil(d/v[2]/I[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let b=y?c&&p%4!==0?3:4:1,E=v[1]*I[1],x=v[0]*I[0],S=Math.max(v[0]*b,v[1]),O=s%E===0,F=n%x===0,H=o%S===0,W=y?[b,4,4]:[1,1,1],B=[{type:6,data:s},{type:6,data:n},{type:6,data:o},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];kn(r,B),B.push(...ct(e[0].dims,e[1].dims));let Y=["rank","rank"];i&&(B.push(...ct(e[2].dims)),Y.push("rank")),B.push(...ct(t));let X=J=>{let re=[{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}];An(r,re);let ne=y?4:1,le=Ar(e[0].dataType),pe=` fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${le}>`:le}) { result[flatIndex] = ${y?`vec4<${le}>`:le}(value); } @@ -983,14 +983,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${le}>`:le} { return bias[coords.${c?"w":"y"}${y?"/ 4":""}]; }`}return` - ${Uy("uniforms.result_strides")} + ${Wy("uniforms.result_strides")} //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; ${J.registerUniforms(re).declareVariables(...N,D)} ${pe} - ${Cg(c,O,F,H,i,r,W[0],W[1],W[2],le)} - ${y?au(I,v,le,void 0,!c,S):iu(I,v,le,void 0,!c,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${b};${y};${O};${F};${H};${E};${x};${S}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:B}),getShaderSource:X}}}),Sg,wc,No,Ig,bc,$g,Gy,Ky,bT=Ve(()=>{gt(),Hs(),Ct(),St(),On(),Au(),Sg=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,No=(e,r)=>r<=1?e:e+(e-1)*(r-1),Ig=(e,r,t,s=1)=>{let n=No(r,s);return Math.floor((e[0]*(t-1)-t+n)/2)},bc=(e,r,t,s,n)=>{n==null&&(n=Ig(e,r[0],s[0]));let o=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*n>=r[i]&&(o[i]=Math.trunc((e[i]-r[i]+2*n)/s[i]+1));return o},$g=(e,r,t,s,n,o,i,a,l,c)=>{let p,d,u,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=bc([r,t,s,1],[a,l,c],1,[n,o,i],e);d=_[0],u=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((y,k,w)=>y===w[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=bc([r,t,s,1],[a,l,c],1,[n,o,i],e[0]);d=_[0],u=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/n),u=Math.ceil(t/o),f=Math.ceil(s/i);let _=(d-1)*n+a-r,y=(u-1)*o+l-t,k=(f-1)*i+c-s,w=Math.floor(_/2),v=_-w,I=Math.floor(y/2),T=y-I,b=Math.floor(k/2),E=k-b;p={top:I,bottom:T,left:b,right:E,front:w,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},Gy=(e,r,t,s,n,o=!1,i="channelsLast")=>{let a,l,c,p,d;if(i==="channelsLast")[a,l,c,p,d]=e;else if(i==="channelsFirst")[a,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,f,_,y]=r,[k,w,v]=wc(t),[I,T,b]=wc(s),E=No(f,I),x=No(_,T),S=No(y,b),{padInfo:O,outDepth:F,outHeight:H,outWidth:W}=$g(n,l,c,p,k,w,v,E,x,S),B=o?u*d:u,Y=[0,0,0,0,0];return i==="channelsFirst"?Y=[a,B,F,H,W]:i==="channelsLast"&&(Y=[a,F,H,W,B]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:F,outHeight:H,outWidth:W,outChannels:B,padInfo:O,strideDepth:k,strideHeight:w,strideWidth:v,filterDepth:f,filterHeight:_,filterWidth:y,effectiveFilterDepth:E,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:I,dilationHeight:T,dilationWidth:b,inShape:e,outShape:Y,filterShape:r}},Ky=(e,r,t,s,n,o)=>{let i=o==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},c=[Math.ceil(Sg(l.x.map(k=>t[k]))/a[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=we.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:n},{type:12,data:r.strides},{type:12,data:r.dilations}];kn(r,u),u.push(...ct(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(u.push(...ct(e[2].dims)),f.push("rank")),u.push(...ct(t));let y=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:n.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];An(r,w);let v=1,I=Ar(e[0].dataType),T=ke("x",e[0].dataType,e[0].dims.length,p),b=ke("W",e[1].dataType,e[1].dims.length,v),E=[T,b],x=it("result",e[0].dataType,t.length,v),S="";if(_){let H=ke("bias",e[2].dataType,e[2].dims.length,v);E.push(H),S+=` + ${Sg(c,O,F,H,i,r,W[0],W[1],W[2],le)} + ${y?iu(I,v,le,void 0,!c,S):lu(I,v,le,void 0,!c,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${b};${y};${O};${F};${H};${E};${x};${S}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:B}),getShaderSource:X}}}),Ig,bc,No,$g,yc,kg,Ky,Hy,bT=Ve(()=>{gt(),Hs(),Ct(),St(),On(),Fu(),Ig=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,No=(e,r)=>r<=1?e:e+(e-1)*(r-1),$g=(e,r,t,s=1)=>{let n=No(r,s);return Math.floor((e[0]*(t-1)-t+n)/2)},yc=(e,r,t,s,n)=>{n==null&&(n=$g(e,r[0],s[0]));let o=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*n>=r[i]&&(o[i]=Math.trunc((e[i]-r[i]+2*n)/s[i]+1));return o},kg=(e,r,t,s,n,o,i,a,l,c)=>{let p,d,u,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=yc([r,t,s,1],[a,l,c],1,[n,o,i],e);d=_[0],u=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((y,k,w)=>y===w[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=yc([r,t,s,1],[a,l,c],1,[n,o,i],e[0]);d=_[0],u=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/n),u=Math.ceil(t/o),f=Math.ceil(s/i);let _=(d-1)*n+a-r,y=(u-1)*o+l-t,k=(f-1)*i+c-s,w=Math.floor(_/2),v=_-w,I=Math.floor(y/2),T=y-I,b=Math.floor(k/2),E=k-b;p={top:I,bottom:T,left:b,right:E,front:w,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},Ky=(e,r,t,s,n,o=!1,i="channelsLast")=>{let a,l,c,p,d;if(i==="channelsLast")[a,l,c,p,d]=e;else if(i==="channelsFirst")[a,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,f,_,y]=r,[k,w,v]=bc(t),[I,T,b]=bc(s),E=No(f,I),x=No(_,T),S=No(y,b),{padInfo:O,outDepth:F,outHeight:H,outWidth:W}=kg(n,l,c,p,k,w,v,E,x,S),B=o?u*d:u,Y=[0,0,0,0,0];return i==="channelsFirst"?Y=[a,B,F,H,W]:i==="channelsLast"&&(Y=[a,F,H,W,B]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:F,outHeight:H,outWidth:W,outChannels:B,padInfo:O,strideDepth:k,strideHeight:w,strideWidth:v,filterDepth:f,filterHeight:_,filterWidth:y,effectiveFilterDepth:E,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:I,dilationHeight:T,dilationWidth:b,inShape:e,outShape:Y,filterShape:r}},Hy=(e,r,t,s,n,o)=>{let i=o==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},c=[Math.ceil(Ig(l.x.map(k=>t[k]))/a[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=we.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:n},{type:12,data:r.strides},{type:12,data:r.dilations}];kn(r,u),u.push(...ct(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(u.push(...ct(e[2].dims)),f.push("rank")),u.push(...ct(t));let y=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:n.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];An(r,w);let v=1,I=Ar(e[0].dataType),T=ke("x",e[0].dataType,e[0].dims.length,p),b=ke("W",e[1].dataType,e[1].dims.length,v),E=[T,b],x=it("result",e[0].dataType,t.length,v),S="";if(_){let H=ke("bias",e[2].dataType,e[2].dims.length,v);E.push(H),S+=` fn getBiasByOutputCoords(coords : array) -> ${I} { return bias[${i?lt("coords",4,5):lt("coords",1,5)}]; }`}let O=Fr(p,I),F=$n(r,O,I);return` @@ -1098,7 +1098,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${_?"value = value + getBiasByOutputCoords(coords)":""}; ${F} result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:y}}}),Hy,qy,yT=Ve(()=>{gt(),Ct(),St(),On(),Hy=(e,r,t,s)=>{let n=e.length>2,o=n?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?ur(c):1,u=we.size(t)/d,f=[{type:12,data:u},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];kn(r,f),f.push(...ct(i,[a[0],a[1],a[2],a[3]/d]));let _=n?["rank","rank","rank"]:["rank","rank"];f.push(...ct([t[0],t[1],t[2],t[3]/d]));let y=k=>{let w=it("output",e[0].dataType,t.length,d),v=Ar(w.type.tensor),I=$n(r,w.type.value,v),T=ke("x",e[0].dataType,i.length),b=ke("w",e[1].dataType,a.length,d),E=[T,b];n&&E.push(ke("b",e[2].dataType,e[2].dims,d));let x=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];An(r,x);let S=l?` + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:y}}}),qy,Qy,yT=Ve(()=>{gt(),Ct(),St(),On(),qy=(e,r,t,s)=>{let n=e.length>2,o=n?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?ur(c):1,u=we.size(t)/d,f=[{type:12,data:u},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];kn(r,f),f.push(...ct(i,[a[0],a[1],a[2],a[3]/d]));let _=n?["rank","rank","rank"]:["rank","rank"];f.push(...ct([t[0],t[1],t[2],t[3]/d]));let y=k=>{let w=it("output",e[0].dataType,t.length,d),v=Ar(w.type.tensor),I=$n(r,w.type.value,v),T=ke("x",e[0].dataType,i.length),b=ke("w",e[1].dataType,a.length,d),E=[T,b];n&&E.push(ke("b",e[2].dataType,e[2].dims,d));let x=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];An(r,x);let S=l?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; @@ -1160,7 +1160,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${o} ${I} ${w.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},qy=(e,r,t,s)=>{let n=e.length>2,o=ur(t[3]),i=ur(t[2]),a=we.size(t)/o/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],p=[t[0],t[1],t[2],t[3]/o],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];kn(r,d),d.push(...ct(l,c,p));let u=(i-1)*r.strides[1]+c[1],f=_=>{let y=it("output",e[0].dataType,p.length,o),k=Ar(y.type.tensor),w=$n(r,y.type.value,k),v=ke("x",e[0].dataType,l.length,o),I=ke("w",e[1].dataType,c.length,o),T=[v,I];n&&T.push(ke("b",e[2].dataType,e[2].dims,o));let b=n?"value += b[output_channel];":"",E=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return An(r,E),` + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},Qy=(e,r,t,s)=>{let n=e.length>2,o=ur(t[3]),i=ur(t[2]),a=we.size(t)/o/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],p=[t[0],t[1],t[2],t[3]/o],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];kn(r,d),d.push(...ct(l,c,p));let u=(i-1)*r.strides[1]+c[1],f=_=>{let y=it("output",e[0].dataType,p.length,o),k=Ar(y.type.tensor),w=$n(r,y.type.value,k),v=ke("x",e[0].dataType,l.length,o),I=ke("w",e[1].dataType,c.length,o),T=[v,I];n&&T.push(ke("b",e[2].dataType,e[2].dims,o));let b=n?"value += b[output_channel];":"",E=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return An(r,E),` ${_.registerUniforms(E).declareVariables(...T,y)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1205,7 +1205,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${w} ${y.set("batch","row","col + i","output_channel","value")}; } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${o};${i};${u};${c[0]};${c[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),kg,ti,Ag,ri,lu,yc,Fg,Og,cu,vT=Ve(()=>{Ct(),wT(),bT(),Du(),yT(),On(),Ou(),cn(),kg=(e,r,t,s,n,o)=>{let i=e[0],a=e.slice(o?1:2,o?3:4),l=a.length,c=r[0],p=r.slice(2).map((u,f)=>u+(u-1)*(t[f]-1)),d=a.map((u,f)=>u+s[f]+s[f+l]).map((u,f)=>Math.floor((u-p[f]+n[f])/n[f]));return d.splice(0,0,i),d.splice(o?3:1,0,c),d},ti=[2,3,1,0],Ag=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ri=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=ku(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,o=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},yc=(e,r,t,s)=>{let n=t.format==="NHWC",o=kg(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,n);if(t.group!==1){let E=[r[0]];if(n){let x=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),E.push(x)}else E.push(r[1]);r.length===3&&E.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&n&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(qy(E,t,o,s),{inputs:E}):e.compute(Hy(E,t,o,s),{inputs:E});return}let i=r.length===3,a=r[0].dims[n?1:2],l=r[0].dims[n?2:3],c=r[0].dims[n?3:1],p=r[1].dims[2],d=r[1].dims[3],u=o[n?1:2],f=o[n?2:3],_=o[n?3:1],y=n&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(y||p===1&&d===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let E=o[0],x,S,O,F=[];if(n){let B=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B),y){let Y=a*l*c;x=r[0].reshape([1,E,Y]),S=B.reshape([1,Y,_]),O=[1,E,_]}else x=r[0].reshape([E,a*l,c]),S=B.reshape([1,c,_]),O=[E,u*f,_];F.push(x),F.push(S)}else x=r[0].reshape([E,c,a*l]),S=r[1].reshape([1,_,c]),O=[E,_,u*f],F.push(S),F.push(x);i&&F.push(r[2]);let H=O[2],W=F[0].dims[F[0].dims.length-1];H<8&&W<8?e.compute(Fu(F,t,o,O,n,s),{inputs:F}):e.compute(_i(F,t,o,O,n,s),{inputs:F});return}let k=!0,w=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let v=[r[0],w];i&&v.push(r[2]);let I=n?u*f:_,T=n?_:u*f,b=p*d*c;e.compute(Wy(v,t,o,I,T,b,i,k,s),{inputs:v})},Fg=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=[0,r.pads[0],0,r.pads[1]],o=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=ri({...r,pads:n,strides:o,dilations:i,kernelShape:a},s);yc(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Og=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",n=ri(t,r),o=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=Gy(r[0].dims,r[1].dims,t.strides,t.dilations,o,!1,s);e.compute(Ky(r,n,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},cu=(e,r)=>{if(Ag(e.inputs,r),e.inputs[0].dims.length===3)Fg(e,r);else if(e.inputs[0].dims.length===5)Og(e,e.inputs,r);else{let t=ri(r,e.inputs);yc(e,e.inputs,t)}}}),Qy,xT=Ve(()=>{gt(),Hs(),Ct(),St(),Qy=(e,r,t)=>{let s=e.length>2,n=r.outputShape,o=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,c=a[3],p=o?ur(l):1,d=o&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-u,_=o?ur(c):1,y=o?c===1?p:_:1,k=we.size(n)/_,w=[Math.ceil(k/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let v=["rank","rank"],I=[r.strides[0],r.strides[1]],T=[r.kernelShape[o?1:2],r.kernelShape[o?2:3]],b=[r.dilations[0],r.dilations[1]],E=[T[0]+(r.dilations[0]<=1?0:(r.kernelShape[o?1:2]-1)*(r.dilations[0]-1)),T[1]+(r.dilations[1]<=1?0:(r.kernelShape[o?2:3]-1)*(r.dilations[1]-1))],x=[E[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),E[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:k},{type:12,data:I},{type:12,data:T},{type:12,data:b},{type:12,data:E},{type:6,data:x},{type:12,data:u},{type:12,data:l},{type:12,data:c},...ct(e[0].dims,e[1].dims)];s&&(S.push(...ct(e[2].dims)),v.push("rank")),S.push(...ct(n));let O=F=>{let H=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:I.length},{name:"filter_dims",type:"u32",length:T.length},{name:"dilations",type:"u32",length:T.length},{name:"effective_filter_dims",type:"u32",length:E.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],W=Ar(e[0].dataType),B=o?1:2,Y=o?2:3,X=o?3:1,J=ke("W",e[1].dataType,e[1].dims.length,y),re=ke("Dy",e[0].dataType,e[0].dims.length,p),ne=[re,J];s&&ne.push(ke("bias",e[2].dataType,[n[X]].length,_));let le=it("result",e[0].dataType,n.length,_),pe=()=>{let N="";if(d)p===4?N+=` + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${o};${i};${u};${c[0]};${c[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),Ag,ti,Fg,ri,cu,vc,Og,Dg,uu,vT=Ve(()=>{Ct(),wT(),bT(),Lu(),yT(),On(),Du(),cn(),Ag=(e,r,t,s,n,o)=>{let i=e[0],a=e.slice(o?1:2,o?3:4),l=a.length,c=r[0],p=r.slice(2).map((u,f)=>u+(u-1)*(t[f]-1)),d=a.map((u,f)=>u+s[f]+s[f+l]).map((u,f)=>Math.floor((u-p[f]+n[f])/n[f]));return d.splice(0,0,i),d.splice(o?3:1,0,c),d},ti=[2,3,1,0],Fg=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ri=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=Au(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,o=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},vc=(e,r,t,s)=>{let n=t.format==="NHWC",o=Ag(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,n);if(t.group!==1){let E=[r[0]];if(n){let x=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),E.push(x)}else E.push(r[1]);r.length===3&&E.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&n&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(Qy(E,t,o,s),{inputs:E}):e.compute(qy(E,t,o,s),{inputs:E});return}let i=r.length===3,a=r[0].dims[n?1:2],l=r[0].dims[n?2:3],c=r[0].dims[n?3:1],p=r[1].dims[2],d=r[1].dims[3],u=o[n?1:2],f=o[n?2:3],_=o[n?3:1],y=n&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(y||p===1&&d===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let E=o[0],x,S,O,F=[];if(n){let B=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B),y){let Y=a*l*c;x=r[0].reshape([1,E,Y]),S=B.reshape([1,Y,_]),O=[1,E,_]}else x=r[0].reshape([E,a*l,c]),S=B.reshape([1,c,_]),O=[E,u*f,_];F.push(x),F.push(S)}else x=r[0].reshape([E,c,a*l]),S=r[1].reshape([1,_,c]),O=[E,_,u*f],F.push(S),F.push(x);i&&F.push(r[2]);let H=O[2],W=F[0].dims[F[0].dims.length-1];H<8&&W<8?e.compute(Ou(F,t,o,O,n,s),{inputs:F}):e.compute(_i(F,t,o,O,n,s),{inputs:F});return}let k=!0,w=e.kernelCustomData.wT??e.compute(es(r[1],ti),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let v=[r[0],w];i&&v.push(r[2]);let I=n?u*f:_,T=n?_:u*f,b=p*d*c;e.compute(Gy(v,t,o,I,T,b,i,k,s),{inputs:v})},Og=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=[0,r.pads[0],0,r.pads[1]],o=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=ri({...r,pads:n,strides:o,dilations:i,kernelShape:a},s);vc(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Dg=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",n=ri(t,r),o=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=Ky(r[0].dims,r[1].dims,t.strides,t.dilations,o,!1,s);e.compute(Hy(r,n,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},uu=(e,r)=>{if(Fg(e.inputs,r),e.inputs[0].dims.length===3)Og(e,r);else if(e.inputs[0].dims.length===5)Dg(e,e.inputs,r);else{let t=ri(r,e.inputs);vc(e,e.inputs,t)}}}),Xy,xT=Ve(()=>{gt(),Hs(),Ct(),St(),Xy=(e,r,t)=>{let s=e.length>2,n=r.outputShape,o=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,c=a[3],p=o?ur(l):1,d=o&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-u,_=o?ur(c):1,y=o?c===1?p:_:1,k=we.size(n)/_,w=[Math.ceil(k/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let v=["rank","rank"],I=[r.strides[0],r.strides[1]],T=[r.kernelShape[o?1:2],r.kernelShape[o?2:3]],b=[r.dilations[0],r.dilations[1]],E=[T[0]+(r.dilations[0]<=1?0:(r.kernelShape[o?1:2]-1)*(r.dilations[0]-1)),T[1]+(r.dilations[1]<=1?0:(r.kernelShape[o?2:3]-1)*(r.dilations[1]-1))],x=[E[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),E[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:k},{type:12,data:I},{type:12,data:T},{type:12,data:b},{type:12,data:E},{type:6,data:x},{type:12,data:u},{type:12,data:l},{type:12,data:c},...ct(e[0].dims,e[1].dims)];s&&(S.push(...ct(e[2].dims)),v.push("rank")),S.push(...ct(n));let O=F=>{let H=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:I.length},{name:"filter_dims",type:"u32",length:T.length},{name:"dilations",type:"u32",length:T.length},{name:"effective_filter_dims",type:"u32",length:E.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],W=Ar(e[0].dataType),B=o?1:2,Y=o?2:3,X=o?3:1,J=ke("W",e[1].dataType,e[1].dims.length,y),re=ke("Dy",e[0].dataType,e[0].dims.length,p),ne=[re,J];s&&ne.push(ke("bias",e[2].dataType,[n[X]].length,_));let le=it("result",e[0].dataType,n.length,_),pe=()=>{let N="";if(d)p===4?N+=` let xValue = ${re.getByOffset("x_offset")}; let wValue = ${J.getByOffset("w_offset")}; dotProd = dotProd + dot(xValue, wValue); @@ -1293,7 +1293,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${F.registerUniforms(H).declareVariables(...ne,le)} ${F.mainStart()} ${F.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${K}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${y}${_}${d}${f}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(n):n,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:O}}}),Dg,Lg,zg,vc,Xy,Bg,xc,Rg,Jy,TT=Ve(()=>{xT(),On(),cn(),Dg=(e,r,t,s,n,o)=>(e-1)*r+t+(s-1)*n+1-o,Lg=(e,r,t,s,n)=>{let o=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=o,t[n]=e-o):r==="SAME_LOWER"&&(t[s]=e-o,t[n]=o)},zg=(e,r,t,s,n,o,i,a,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}zg(a,t,l,e.autoPad,e.group,n,c,s,i,o);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:n,outputPadding:i,outputShape:o,dilations:l,strides:c}),p},Xy=e=>{let r=ku(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,o=e.group,i=e.kernelShape,a=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Bg=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let o=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.outputPadding.length!==o&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(r.kernelShape.reduce((i,a)=>i+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},xc=(e,r,t,s)=>{let n=e.kernelCustomData.wT??e.compute(es(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=n);let o=[r[0],n];r.length===3&&o.push(r[2]),e.compute(Qy(o,t,s),{inputs:o})},Rg=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=r.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let o=r.dilations;(o.length===0||o[0]===0)&&(o=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),o=[1].concat(o),n=[1].concat(n);let l=r.outputPadding;l=[0].concat(l);let c=vc({...r,pads:a,strides:i,dilations:o,kernelShape:n,outputPadding:l},s);xc(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Jy=(e,r)=>{if(Bg(e.inputs,r),e.inputs[0].dims.length===3)Rg(e,r);else{let t=vc(r,e.inputs);xc(e,e.inputs,t)}}}),Ng,Yy,Zy,ET=Ve(()=>{gt(),Ct(),mr(),St(),Ng=(e,r,t,s)=>{let n=we.size(r),o=r.length,i=ke("input",e,o),a=it("output",e,o),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=we.normalizeAxis(l,o),p=d=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=lt("uniforms.input_shape","uniforms.axis",o),_=s.reverse?u+(s.exclusive?" + 1":""):"0",y=s.reverse?f:u+(s.exclusive?"":" + 1");return` + ${K}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${y}${_}${d}${f}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(n):n,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:O}}}),Lg,zg,Bg,xc,Jy,Rg,Tc,Ng,Yy,TT=Ve(()=>{xT(),On(),cn(),Lg=(e,r,t,s,n,o)=>(e-1)*r+t+(s-1)*n+1-o,zg=(e,r,t,s,n)=>{let o=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=o,t[n]=e-o):r==="SAME_LOWER"&&(t[s]=e-o,t[n]=o)},Bg=(e,r,t,s,n,o,i,a,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}Bg(a,t,l,e.autoPad,e.group,n,c,s,i,o);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:n,outputPadding:i,outputShape:o,dilations:l,strides:c}),p},Jy=e=>{let r=Au(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,o=e.group,i=e.kernelShape,a=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Rg=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let n=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let o=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.outputPadding.length!==o&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(r.kernelShape.reduce((i,a)=>i+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Tc=(e,r,t,s)=>{let n=e.kernelCustomData.wT??e.compute(es(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=n);let o=[r[0],n];r.length===3&&o.push(r[2]),e.compute(Xy(o,t,s),{inputs:o})},Ng=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let n=r.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let o=r.dilations;(o.length===0||o[0]===0)&&(o=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),o=[1].concat(o),n=[1].concat(n);let l=r.outputPadding;l=[0].concat(l);let c=xc({...r,pads:a,strides:i,dilations:o,kernelShape:n,outputPadding:l},s);Tc(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Yy=(e,r)=>{if(Rg(e.inputs,r),e.inputs[0].dims.length===3)Ng(e,r);else{let t=xc(r,e.inputs);Tc(e,e.inputs,t)}}}),jg,Zy,e0,ET=Ve(()=>{gt(),Ct(),mr(),St(),jg=(e,r,t,s)=>{let n=we.size(r),o=r.length,i=ke("input",e,o),a=it("output",e,o),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=we.normalizeAxis(l,o),p=d=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=lt("uniforms.input_shape","uniforms.axis",o),_=s.reverse?u+(s.exclusive?" + 1":""):"0",y=s.reverse?f:u+(s.exclusive?"":" + 1");return` ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -1306,12 +1306,12 @@ fn main(@builtin(local_invocation_id) localId : vec3, sum = sum + ${i.getByIndices("inputIndices")}; } ${a.setByOffset("global_idx","sum")}; - }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:12,data:c},...ct(r,r)]}),getShaderSource:p}},Yy=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(Ng(s,t,n,r),{inputs:[0]})},Zy=e=>{let r=e.exclusive===1,t=e.reverse===1;return jt({exclusive:r,reverse:t})}}),jg,Vg,Ug,e0,t0,PT=Ve(()=>{gt(),Ct(),mr(),St(),jg=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.")},Vg=(e,r,t,s)=>{let n=[];n.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},{type:12,data:c},...ct(r,r)]}),getShaderSource:p}},Zy=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(jg(s,t,n,r),{inputs:[0]})},e0=e=>{let r=e.exclusive===1,t=e.reverse===1;return jt({exclusive:r,reverse:t})}}),Vg,Ug,Wg,t0,r0,PT=Ve(()=>{gt(),Ct(),mr(),St(),Vg=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.")},Ug=(e,r,t,s)=>{let n=[];n.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { var a: ${t.type.indices};`);for(let o=0;o{let t,s,n,o,i,a,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,n,o]=e.dims,i=p?[t,s,n,c,c,o/c**2]:[t,s,n,o/c**2,c,c],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,n,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,c,c,o/c**2,s,n]:[t,o/c**2,c,c,s,n],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),u=d.dims.length,f=e.dataType,_=ke("a",f,u),y=it("output",f,u),k=w=>` +`)},Wg=(e,r)=>{let t,s,n,o,i,a,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,n,o]=e.dims,i=p?[t,s,n,c,c,o/c**2]:[t,s,n,o/c**2,c,c],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,n,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,c,c,o/c**2,s,n]:[t,o/c**2,c,c,s,n],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),u=d.dims.length,f=e.dataType,_=ke("a",f,u),y=it("output",f,u),k=w=>` ${w.registerUniform("output_size","u32").declareVariables(_,y)} - ${Vg(a,u,_,y)} + ${Ug(a,u,_,y)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1320,8 +1320,8 @@ fn main(@builtin(local_invocation_id) localId : vec3, let aIndices = perm(indices); ${y.setByOffset("global_idx",_.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let v=l?[t,s*c,n*c,o/c**2]:[t,o/c**2,s*c,n*c],I=we.size(v),T=d.dims,b=we.sortBasedOnPerm(T,a);return{outputs:[{dims:v,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:[{type:12,data:I},...ct(T,b)]}},getShaderSource:k}},e0=(e,r)=>{jg(e.inputs),e.compute(Ug(e.inputs[0],r))},t0=e=>jt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),si,jo,Tc,Wg,Gg,Kg,Hg,Ec,qg,r0,s0,CT=Ve(()=>{gt(),Ct(),mr(),St(),si="[a-zA-Z]|\\.\\.\\.",jo="("+si+")+",Tc="^"+jo+"$",Wg="("+jo+",)*"+jo,Gg="^"+Wg+"$",Kg=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},Hg=class{constructor(e,r){this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(Gg)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let i=e[o].dims.slice();if(!n.match(RegExp(Tc)))throw new Error("Invalid LHS term");let a=this.processTerm(n,!0,i,o);this.lhs.push(a)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(jo)))throw new Error("Invalid RHS");s.match(RegExp(si,"g"))?.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let n=t.length,o=!1,i=[],a=0;if(!e.match(RegExp(Tc))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(si,"g")),c=new Kg(s);return l?.forEach((p,d)=>{if(p==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let u=n-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",qg=(e,r,t,s)=>{let n=e.map(c=>c.length).map((c,p)=>ke(`input${p}`,r,c)),o=we.size(s),i=it("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",f="sum += prod;",_=[],y=[],k=[],w=[],v=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((T,b)=>{if(t.rhs.symbolToIndices.has(b)){let E=t.rhs.symbolToIndices.get(b)?.[0];E!==void 0&&t.lhs.forEach((x,S)=>{if(T.inputIndices.includes(S)){let O=x.symbolToIndices.get(b);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(F=>{p.push(`${n[S].indicesSet(`input${S}Indices`,F,i.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,x)=>{if(T.inputIndices.includes(x)){let S=E.symbolToIndices.get(b);if(S===void 0)throw new Error("Invalid symbol error");S.forEach(O=>{_.push(`${n[x].indicesSet(`input${x}Indices`,O,`${b}`)}`)}),w.push(`prod *= ${n[x].getByIndices(`input${x}Indices`)};`)}}),y.push(`for(var ${b}: u32 = 0; ${b} < uniforms.${Ec(b)}; ${b}++) {`),k.push("}")});let I=v?[...p,`let sum = ${n.map((T,b)=>T.getByIndices(`input${b}Indices`)).join(" * ")};`]:[...p,u,...y,..._,d,...w,f,...k];return` - ${c.registerUniforms(a.map(T=>({name:`${Ec(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,i)} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let v=l?[t,s*c,n*c,o/c**2]:[t,o/c**2,s*c,n*c],I=we.size(v),T=d.dims,b=we.sortBasedOnPerm(T,a);return{outputs:[{dims:v,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(I/64)},programUniforms:[{type:12,data:I},...ct(T,b)]}},getShaderSource:k}},t0=(e,r)=>{Vg(e.inputs),e.compute(Wg(e.inputs[0],r))},r0=e=>jt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),si,jo,Ec,Gg,Kg,Hg,qg,Pc,Qg,s0,n0,CT=Ve(()=>{gt(),Ct(),mr(),St(),si="[a-zA-Z]|\\.\\.\\.",jo="("+si+")+",Ec="^"+jo+"$",Gg="("+jo+",)*"+jo,Kg="^"+Gg+"$",Hg=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},qg=class{constructor(e,r){this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(Kg)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let i=e[o].dims.slice();if(!n.match(RegExp(Ec)))throw new Error("Invalid LHS term");let a=this.processTerm(n,!0,i,o);this.lhs.push(a)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(jo)))throw new Error("Invalid RHS");s.match(RegExp(si,"g"))?.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let n=t.length,o=!1,i=[],a=0;if(!e.match(RegExp(Ec))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(si,"g")),c=new Hg(s);return l?.forEach((p,d)=>{if(p==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let u=n-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",Qg=(e,r,t,s)=>{let n=e.map(c=>c.length).map((c,p)=>ke(`input${p}`,r,c)),o=we.size(s),i=it("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",f="sum += prod;",_=[],y=[],k=[],w=[],v=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((T,b)=>{if(t.rhs.symbolToIndices.has(b)){let E=t.rhs.symbolToIndices.get(b)?.[0];E!==void 0&&t.lhs.forEach((x,S)=>{if(T.inputIndices.includes(S)){let O=x.symbolToIndices.get(b);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(F=>{p.push(`${n[S].indicesSet(`input${S}Indices`,F,i.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,x)=>{if(T.inputIndices.includes(x)){let S=E.symbolToIndices.get(b);if(S===void 0)throw new Error("Invalid symbol error");S.forEach(O=>{_.push(`${n[x].indicesSet(`input${x}Indices`,O,`${b}`)}`)}),w.push(`prod *= ${n[x].getByIndices(`input${x}Indices`)};`)}}),y.push(`for(var ${b}: u32 = 0; ${b} < uniforms.${Pc(b)}; ${b}++) {`),k.push("}")});let I=v?[...p,`let sum = ${n.map((T,b)=>T.getByIndices(`input${b}Indices`)).join(" * ")};`]:[...p,u,...y,..._,d,...w,f,...k];return` + ${c.registerUniforms(a.map(T=>({name:`${Pc(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,i)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -1331,7 +1331,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${I.join(` `)}; ${i.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=a.filter(d=>t.symbolToInfo.has(d)).map(d=>({type:12,data:t.symbolToInfo.get(d)?.dimValue||0}));c.push({type:12,data:o});let p=e.map((d,u)=>[...ct(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...ct(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}},getShaderSource:l}},r0=(e,r)=>{let t=new Hg(e.inputs,r.equation),s=t.outputDims,n=e.inputs.map((o,i)=>o.dims);e.compute(qg(n,e.inputs[0].dataType,t,s))},s0=e=>{let r=e.equation.replace(/\s+/g,"");return jt({equation:r})}}),Qg,Pc,Xg,Jg,n0,ST=Ve(()=>{gt(),Ct(),St(),Qg=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let n=0;ne.length>r.length?Pc(e,r):Pc(r,e),Jg=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Xg(r,t),n=e[0].dataType,o=n===9||we.size(r)===1,i=n===9||r.length>0&&r[r.length-1]%4===0?4:1,a=o||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(we.size(s)/a),c=d=>{let u=ke("input",n,r.length,i),f=it("output",n,s.length,a),_;if(n===9){let y=(k,w,v="")=>` + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=a.filter(d=>t.symbolToInfo.has(d)).map(d=>({type:12,data:t.symbolToInfo.get(d)?.dimValue||0}));c.push({type:12,data:o});let p=e.map((d,u)=>[...ct(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...ct(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}},getShaderSource:l}},s0=(e,r)=>{let t=new qg(e.inputs,r.equation),s=t.outputDims,n=e.inputs.map((o,i)=>o.dims);e.compute(Qg(n,e.inputs[0].dataType,t,s))},n0=e=>{let r=e.equation.replace(/\s+/g,"");return jt({equation:r})}}),Xg,Cc,Jg,Yg,o0,ST=Ve(()=>{gt(),Ct(),St(),Xg=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let n=0;ne.length>r.length?Cc(e,r):Cc(r,e),Yg=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Jg(r,t),n=e[0].dataType,o=n===9||we.size(r)===1,i=n===9||r.length>0&&r[r.length-1]%4===0?4:1,a=o||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(we.size(s)/a),c=d=>{let u=ke("input",n,r.length,i),f=it("output",n,s.length,a),_;if(n===9){let y=(k,w,v="")=>` let outputIndices${w} = ${f.offsetToIndices(`outputOffset + ${w}u`)}; let offset${w} = ${u.broadcastedIndicesToOffset(`outputIndices${w}`,f)}; let index${w} = offset${w} / 4u; @@ -1354,13 +1354,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${d.registerUniform("vec_size","u32").declareVariables(u,f)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${_}`},p=[{type:12,data:l},...ct(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},n0=e=>{Qg(e.inputs),e.compute(Jg(e.inputs),{inputs:[0]})}}),Yg,o0,IT=Ve(()=>{gt(),Ct(),St(),$u(),Yg=e=>{let r=e[0].dataType,t=we.size(e[0].dims),s=we.size(e[1].dims),n=s%4===0,o=i=>{let a=ke("x",r,[1],4),l=ke("bias",r,[1],4),c=it("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` + ${_}`},p=[{type:12,data:l},...ct(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},o0=e=>{Xg(e.inputs),e.compute(Yg(e.inputs),{inputs:[0]})}}),Zg,a0,IT=Ve(()=>{gt(),Ct(),St(),ku(),Zg=e=>{let r=e[0].dataType,t=we.size(e[0].dims),s=we.size(e[1].dims),n=s%4===0,o=i=>{let a=ke("x",r,[1],4),l=ke("bias",r,[1],4),c=it("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,u=n?` let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,c)} - ${nu(jr(r))} + ${ou(jr(r))} ${i.mainStart(co)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} @@ -1368,8 +1368,8 @@ fn main(@builtin(local_invocation_id) localId : vec3, let x = ${a.getByOffset("global_idx")}; ${u} let x_in = x + bias; - ${c.setByOffset("global_idx",ou("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/co/4)}})}},o0=e=>{e.inputs.length<2||we.size(e.inputs[1].dims)===0?Ey(e):e.compute(Yg(e.inputs))}}),Zg,eM,a0,i0,$T=Ve(()=>{gt(),Ct(),mr(),St(),Zg=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},eM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.axis,n),i=t.slice(0);i.splice(o,1,...s);let a=t[o],l=e[0].dataType===9?4:1,c=Math.ceil(we.size(i)/l),p=[{type:12,data:c},{type:6,data:a},{type:12,data:o},...ct(e[0].dims,e[1].dims,i)],d=u=>{let f=ke("data",e[0].dataType,e[0].dims.length,l),_=ke("inputIndices",e[1].dataType,e[1].dims.length),y=it("output",e[0].dataType,i.length,l),k=v=>{let I=s.length,T=`var indicesIndices${v} = ${_.type.indices}(0);`;for(let b=0;b1?`indicesIndices${v}[${b}]`:`indicesIndices${v}`} = ${i.length>1?`outputIndices${v}[uniforms.axis + ${b}]`:`outputIndices${v}`};`;T+=` + ${c.setByOffset("global_idx",au("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/co/4)}})}},a0=e=>{e.inputs.length<2||we.size(e.inputs[1].dims)===0?Py(e):e.compute(Zg(e.inputs))}}),eM,tM,i0,l0,$T=Ve(()=>{gt(),Ct(),mr(),St(),eM=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},tM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.axis,n),i=t.slice(0);i.splice(o,1,...s);let a=t[o],l=e[0].dataType===9?4:1,c=Math.ceil(we.size(i)/l),p=[{type:12,data:c},{type:6,data:a},{type:12,data:o},...ct(e[0].dims,e[1].dims,i)],d=u=>{let f=ke("data",e[0].dataType,e[0].dims.length,l),_=ke("inputIndices",e[1].dataType,e[1].dims.length),y=it("output",e[0].dataType,i.length,l),k=v=>{let I=s.length,T=`var indicesIndices${v} = ${_.type.indices}(0);`;for(let b=0;b1?`indicesIndices${v}[${b}]`:`indicesIndices${v}`} = ${i.length>1?`outputIndices${v}[uniforms.axis + ${b}]`:`outputIndices${v}`};`;T+=` var idx${v} = ${_.getByIndices(`indicesIndices${v}`)}; if (idx${v} < 0) { idx${v} = idx${v} + uniforms.axisDimLimit; @@ -1400,7 +1400,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${w} - }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},a0=e=>jt({axis:e.axis}),i0=(e,r)=>{let t=e.inputs;Zg(t),e.compute(eM(e.inputs,r))}}),tM,l0,c0,kT=Ve(()=>{gt(),Ct(),St(),tM=(e,r,t,s,n,o,i,a,l)=>{let c=[{type:12,data:o},{type:12,data:s},{type:12,data:n},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[o];c.push(...ct(r.dims,p));let d=u=>{let f=ke("indices_data",r.dataType,r.dims.length),_=it("input_slice_offsets_data",12,1,1),y=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:n.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},i0=e=>jt({axis:e.axis}),l0=(e,r)=>{let t=e.inputs;eM(t),e.compute(tM(e.inputs,r))}}),rM,c0,u0,kT=Ve(()=>{gt(),Ct(),St(),rM=(e,r,t,s,n,o,i,a,l)=>{let c=[{type:12,data:o},{type:12,data:s},{type:12,data:n},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[o];c.push(...ct(r.dims,p));let d=u=>{let f=ke("indices_data",r.dataType,r.dims.length),_=it("input_slice_offsets_data",12,1,1),y=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:n.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${u.registerUniforms(k).declareVariables(...y)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1419,13 +1419,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); - }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${n.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},l0=(e,r)=>{let t=e.inputs,s=t[0].dims,n=t[0].dataType,o=t[1].dims,i=o[o.length-1],a=we.sizeToDimension(o,o.length-1),l=we.sizeFromDimension(s,r.batchDims+i),c=we.sizeToDimension(s,r.batchDims),p=we.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let T=0;Ts.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=o.slice(0,-1).concat(s.slice(y)),w=we.size(k),v=[{type:12,data:w},{type:12,data:l},...ct(t[0].dims,_.dims,k)],I=T=>{let b=ke("data",t[0].dataType,t[0].dims.length),E=ke("slice_offsets",12,_.dims.length),x=it("output",t[0].dataType,k.length);return` + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${n.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},c0=(e,r)=>{let t=e.inputs,s=t[0].dims,n=t[0].dataType,o=t[1].dims,i=o[o.length-1],a=we.sizeToDimension(o,o.length-1),l=we.sizeFromDimension(s,r.batchDims+i),c=we.sizeToDimension(s,r.batchDims),p=we.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let T=0;Ts.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=o.slice(0,-1).concat(s.slice(y)),w=we.size(k),v=[{type:12,data:w},{type:12,data:l},...ct(t[0].dims,_.dims,k)],I=T=>{let b=ke("data",t[0].dataType,t[0].dims.length),E=ke("slice_offsets",12,_.dims.length),x=it("output",t[0].dataType,k.length);return` ${T.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(b,E,x)} ${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:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:k,dataType:n}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:v}),getShaderSource:I},{inputs:[t[0],_]})},c0=e=>({batchDims:e.batch_dims,cacheKey:""})}),rM,sM,u0,d0,AT=Ve(()=>{gt(),Ct(),mr(),St(),rM=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=we.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,n=e[0],o=e[2],i=e.length===4?e[3]:void 0;if(o.dims.length!==n.dims.length||!n.dims.map((a,l)=>l===t?Math.ceil(a/s)===o.dims[l]:a===o.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==o.dims.length||!i.dims.map((a,l)=>a===o.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},sM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.gatherAxis,n),i=we.normalizeAxis(r.quantizeAxis,n),a=t.slice(0);a.splice(o,1,...s);let l=we.size(a),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:r.blockSize},...ct(...e.map((f,_)=>f.dims),a)],u=f=>{let _=ke("data",e[0].dataType,e[0].dims.length),y=ke("inputIndices",e[1].dataType,e[1].dims.length),k=ke("scales",e[2].dataType,e[2].dims.length),w=e.length>3?ke("zeroPoint",e[3].dataType,e[3].dims.length):void 0,v=it("output",c,a.length),I=[_,y,k];w&&I.push(w);let T=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:k,dataType:n}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:v}),getShaderSource:I},{inputs:[t[0],_]})},u0=e=>({batchDims:e.batch_dims,cacheKey:""})}),sM,nM,d0,p0,AT=Ve(()=>{gt(),Ct(),mr(),St(),sM=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=we.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,n=e[0],o=e[2],i=e.length===4?e[3]:void 0;if(o.dims.length!==n.dims.length||!n.dims.map((a,l)=>l===t?Math.ceil(a/s)===o.dims[l]:a===o.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==o.dims.length||!i.dims.map((a,l)=>a===o.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},nM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.gatherAxis,n),i=we.normalizeAxis(r.quantizeAxis,n),a=t.slice(0);a.splice(o,1,...s);let l=we.size(a),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:r.blockSize},...ct(...e.map((f,_)=>f.dims),a)],u=f=>{let _=ke("data",e[0].dataType,e[0].dims.length),y=ke("inputIndices",e[1].dataType,e[1].dims.length),k=ke("scales",e[2].dataType,e[2].dims.length),w=e.length>3?ke("zeroPoint",e[3].dataType,e[3].dims.length):void 0,v=it("output",c,a.length),I=[_,y,k];w&&I.push(w);let T=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${f.registerUniforms(T).declareVariables(...I,v)} ${f.mainStart()} let output_indices = ${v.offsetToIndices("global_idx")}; @@ -1470,8 +1470,8 @@ fn main(@builtin(local_invocation_id) localId : vec3, let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${jr(c)}(quantized_data - zero_point) * scale; ${v.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},u0=(e,r)=>{let t=e.inputs;rM(t,r),e.compute(sM(e.inputs,r))},d0=e=>jt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),nM,oM,p0,m0,FT=Ve(()=>{gt(),Ct(),mr(),St(),nM=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.`)},oM=(e,r)=>{let t=e[0].dims,s=e[0].dataType,n=t.length,o=e[1].dims,i=e[1].dataType,a=we.normalizeAxis(r.axis,n),l=t[a],c=o.slice(0),p=we.size(c),d=ke("input",s,n),u=ke("indicesInput",i,o.length),f=it("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...ct(t,o,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:y=>` + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},d0=(e,r)=>{let t=e.inputs;sM(t,r),e.compute(nM(e.inputs,r))},p0=e=>jt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),oM,aM,m0,h0,FT=Ve(()=>{gt(),Ct(),mr(),St(),oM=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.`)},aM=(e,r)=>{let t=e[0].dims,s=e[0].dataType,n=t.length,o=e[1].dims,i=e[1].dataType,a=we.normalizeAxis(r.axis,n),l=t[a],c=o.slice(0),p=we.size(c),d=ke("input",s,n),u=ke("indicesInput",i,o.length),f=it("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...ct(t,o,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:y=>` ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,f)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -1487,7 +1487,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let value = ${d.getByIndices("inputIndices")}; ${f.setByOffset("global_idx","value")}; - }`}},p0=e=>jt({axis:e.axis}),m0=(e,r)=>{let t=e.inputs;nM(t),e.compute(oM(e.inputs,r))}}),aM,iM,h0,_0,OT=Ve(()=>{gt(),Ct(),St(),aM=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")},iM=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[n,o,i]=pb.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[n,o];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(o/l),p=Math.ceil(n/l),d=!0,u=we.size(a),f=[{type:12,data:d?c:u},{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...ct(e[2].dims)),_.push("rank")),f.push(...ct(a));let y=w=>{let v="";r.transA&&r.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let I=r.alpha===1?"":"value *= uniforms.alpha;",T=ke("a",e[0].dataType,e[0].dims),b=ke("b",e[1].dataType,e[1].dims),E=T.type.value,x=null,S=[T,b];e.length===3&&(x=ke("c",e[2].dataType,e[2].dims.length),S.push(x));let O=it("output",e[0].dataType,a.length);S.push(O);let F=[{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` + }`}},m0=e=>jt({axis:e.axis}),h0=(e,r)=>{let t=e.inputs;oM(t),e.compute(aM(e.inputs,r))}}),iM,lM,_0,f0,OT=Ve(()=>{gt(),Ct(),St(),iM=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")},lM=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[n,o,i]=mb.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[n,o];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(o/l),p=Math.ceil(n/l),d=!0,u=we.size(a),f=[{type:12,data:d?c:u},{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...ct(e[2].dims)),_.push("rank")),f.push(...ct(a));let y=w=>{let v="";r.transA&&r.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let I=r.alpha===1?"":"value *= uniforms.alpha;",T=ke("a",e[0].dataType,e[0].dims),b=ke("b",e[1].dataType,e[1].dims),E=T.type.value,x=null,S=[T,b];e.length===3&&(x=ke("c",e[2].dataType,e[2].dims.length),S.push(x));let O=it("output",e[0].dataType,a.length);S.push(O);let F=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${w.registerUniforms(F).declareVariables(...S)} ${w.mainStart()} @@ -1596,7 +1596,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } - }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},h0=e=>{let r=e.transA,t=e.transB,s=e.alpha,n=e.beta;return{transA:r,transB:t,alpha:s,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},_0=(e,r)=>{aM(e.inputs),e.compute(iM(e.inputs,r))}}),zs,Ws,vn,xn,lM,cM,uM,dM,pM,mM,hM,_M,f0,g0,DT=Ve(()=>{gt(),Ct(),mr(),St(),[zs,Ws,vn,xn]=[0,1,2,3],lM=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")},cM=` + }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},_0=e=>{let r=e.transA,t=e.transB,s=e.alpha,n=e.beta;return{transA:r,transB:t,alpha:s,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},f0=(e,r)=>{iM(e.inputs),e.compute(lM(e.inputs,r))}}),zs,Ws,vn,xn,cM,uM,dM,pM,mM,hM,_M,fM,g0,M0,DT=Ve(()=>{gt(),Ct(),mr(),St(),[zs,Ws,vn,xn]=[0,1,2,3],cM=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")},uM=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); @@ -1607,7 +1607,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } -`,uM=e=>` +`,dM=e=>` fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); @@ -1618,7 +1618,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } -`,dM=e=>` +`,pM=e=>` fn gs_denormalize(n: f32, length: i32) -> f32 { ${e.alignCorners===0?` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] @@ -1628,7 +1628,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, return (n + 1.0) / 2.0 * (f32(length - 1)); `} } -`,pM=e=>` +`,mM=e=>` ${e.paddingMode==="reflection"?` fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { var dx = 0.0; @@ -1655,7 +1655,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, } return u32(fx); }`:""} -`,mM=(e,r,t)=>` +`,hM=(e,r,t)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { var pixel = ${r}(0); var indices = vec4(0); @@ -1676,7 +1676,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } -`,hM=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` +`,_M=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${zs}], indices[${Ws}], border); `;case"bilinear":return` let x1 = i32(floor(x)); @@ -1707,13 +1707,13 @@ fn main(@builtin(local_invocation_id) localId : vec3, let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); - `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,_M=(e,r)=>{let t=ke("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],n=ke("grid",e[1].dataType,s.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[zs,Ws,vn,xn]=[0,3,1,2]);let i=it("output",e[0].dataType,o.length),a=t.type.value,l=we.size(o),c=[{type:12,data:l},...ct(e[0].dims,s,o)],p=d=>` + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,fM=(e,r)=>{let t=ke("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],n=ke("grid",e[1].dataType,s.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[zs,Ws,vn,xn]=[0,3,1,2]);let i=it("output",e[0].dataType,o.length),a=t.type.value,l=we.size(o),c=[{type:12,data:l},...ct(e[0].dims,s,o)],p=d=>` ${d.registerUniform("output_size","u32").declareVariables(t,n,i)} - ${cM} - ${uM(a)} - ${dM(r)} + ${uM} + ${dM(a)} ${pM(r)} - ${mM(t,a,r)} + ${mM(r)} + ${hM(t,a,r)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1739,15 +1739,15 @@ fn main(@builtin(local_invocation_id) localId : vec3, var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); - ${hM(i,a,r)} - }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=we.size(o);return{outputs:[{dims:o,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},f0=(e,r)=>{lM(e.inputs),e.compute(_M(e.inputs,r))},g0=e=>jt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Gr,fM,M0,Cc,gM,Qo,w0,b0=Ve(()=>{gt(),Ct(),mr(),Pu(),Iu(),St(),cn(),Gr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,fM=(e,r)=>{let t=e[0],s=Gr(e,1),n=Gr(e,2),o=Gr(e,3),i=Gr(e,4),a=Gr(e,5),l=Gr(e,6),c=Gr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,y=0,k=Math.floor(u/r.numHeads);if(l&&c&&we.size(l.dims)&&we.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],y=l.dims[2]}else if(l&&we.size(l.dims)||c&&we.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&we.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(o&&we.size(o.dims)>0){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=_+f,I=0;if(i&&we.size(i.dims)>0){I=8;let x=i.dims;throw x.length===1?x[0]===p?I=1:x[0]===3*p+2&&(I=3):x.length===2&&x[0]===p&&x[1]===v&&(I=5),I===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,b=u;if(n&&we.size(n.dims)>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(f!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=n.dims[2]}else{if(f!==n.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');b=n.dims[1]*n.dims[3],T=!0}}let E=!1;if(i&&we.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&we.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:v,maxSequenceLength:y,inputHiddenSize:0,hiddenSize:u,vHiddenSize:b,headSize:k,vHeadSize:Math.floor(b/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:I,scale:r.scale,broadcastResPosBias:E,passPastInKv:T,qkvFormat:w}},M0=e=>jt({...e}),Cc=jt({perm:[0,2,1,3]}),gM=(e,r,t,s,n,o,i)=>{let a=[s,n,o],l=we.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:o}],p=d=>{let u=it("qkv_with_bias",r.dataType,a),f=ke("qkv",r.dataType,a),_=ke("bias",t.dataType,a),y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${_M(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=we.size(o);return{outputs:[{dims:o,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},g0=(e,r)=>{cM(e.inputs),e.compute(fM(e.inputs,r))},M0=e=>jt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Gr,gM,w0,Sc,MM,Qo,b0,y0=Ve(()=>{gt(),Ct(),mr(),Cu(),$u(),St(),cn(),Gr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,gM=(e,r)=>{let t=e[0],s=Gr(e,1),n=Gr(e,2),o=Gr(e,3),i=Gr(e,4),a=Gr(e,5),l=Gr(e,6),c=Gr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,y=0,k=Math.floor(u/r.numHeads);if(l&&c&&we.size(l.dims)&&we.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],y=l.dims[2]}else if(l&&we.size(l.dims)||c&&we.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&we.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(o&&we.size(o.dims)>0){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let v=_+f,I=0;if(i&&we.size(i.dims)>0){I=8;let x=i.dims;throw x.length===1?x[0]===p?I=1:x[0]===3*p+2&&(I=3):x.length===2&&x[0]===p&&x[1]===v&&(I=5),I===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,b=u;if(n&&we.size(n.dims)>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(f!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=n.dims[2]}else{if(f!==n.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');b=n.dims[1]*n.dims[3],T=!0}}let E=!1;if(i&&we.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&we.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:v,maxSequenceLength:y,inputHiddenSize:0,hiddenSize:u,vHiddenSize:b,headSize:k,vHeadSize:Math.floor(b/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:I,scale:r.scale,broadcastResPosBias:E,passPastInKv:T,qkvFormat:w}},w0=e=>jt({...e}),Sc=jt({perm:[0,2,1,3]}),MM=(e,r,t,s,n,o,i)=>{let a=[s,n,o],l=we.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:o}],p=d=>{let u=it("qkv_with_bias",r.dataType,a),f=ke("qkv",r.dataType,a),_=ke("bias",t.dataType,a),y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${d.registerUniforms(y).declareVariables(f,_,u)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; - }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Qo=(e,r,t,s,n,o,i,a)=>{let l=o;if(i&&we.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=gM(e,o,i,r,s,t*n,a),l=l.reshape([r,s,t,n]),t===1||s===1?l:e.compute(es(l,Cc.perm),{inputs:[l],outputs:[-1]})[0]}else return o.dims.length===3&&(l=o.reshape([r,s,t,n])),t===1||s===1?l:e.compute(es(l,Cc.perm),{inputs:[l],outputs:[-1]})[0]},w0=(e,r)=>{let t=fM(e.inputs,r),s=e.inputs[0],n=Gr(e.inputs,1),o=Gr(e.inputs,2),i=Gr(e.inputs,3),a=Gr(e.inputs,4),l=Gr(e.inputs,5),c=Gr(e.inputs,6),p=Gr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if(n?.dims.length===5)throw new Error("Packed KV is not implemented");let d=n&&o&&n.dims.length===4&&o.dims.length===4,u=Qo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return Zo(e,u,n,o,a,void 0,c,p,l,t);if(!n||!o)throw new Error("key and value must be provided");let f=Qo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,n,i,t.hiddenSize),_=Qo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,o,i,2*t.hiddenSize);Zo(e,u,f,_,a,void 0,c,p,l,t)}}),MM,wM,bM,yM,uu,y0,v0,x0=Ve(()=>{gt(),Ct(),mr(),St(),MM=e=>{if(!e||e.length<1)throw new Error("too few inputs")},wM=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>t.push(Number(n))),s=t.length),jt({numOutputs:s,axis:r.axis,splitSizes:t})},bM=e=>` + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Qo=(e,r,t,s,n,o,i,a)=>{let l=o;if(i&&we.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=MM(e,o,i,r,s,t*n,a),l=l.reshape([r,s,t,n]),t===1||s===1?l:e.compute(es(l,Sc.perm),{inputs:[l],outputs:[-1]})[0]}else return o.dims.length===3&&(l=o.reshape([r,s,t,n])),t===1||s===1?l:e.compute(es(l,Sc.perm),{inputs:[l],outputs:[-1]})[0]},b0=(e,r)=>{let t=gM(e.inputs,r),s=e.inputs[0],n=Gr(e.inputs,1),o=Gr(e.inputs,2),i=Gr(e.inputs,3),a=Gr(e.inputs,4),l=Gr(e.inputs,5),c=Gr(e.inputs,6),p=Gr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if(n?.dims.length===5)throw new Error("Packed KV is not implemented");let d=n&&o&&n.dims.length===4&&o.dims.length===4,u=Qo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return Zo(e,u,n,o,a,void 0,c,p,l,t);if(!n||!o)throw new Error("key and value must be provided");let f=Qo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,n,i,t.hiddenSize),_=Qo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,o,i,2*t.hiddenSize);Zo(e,u,f,_,a,void 0,c,p,l,t)}}),wM,bM,yM,vM,du,v0,x0,T0=Ve(()=>{gt(),Ct(),mr(),St(),wM=e=>{if(!e||e.length<1)throw new Error("too few inputs")},bM=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>t.push(Number(n))),s=t.length),jt({numOutputs:s,axis:r.axis,splitSizes:t})},yM=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${lt("uniforms.size_in_split_axis","i",e)}) { @@ -1755,14 +1755,14 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return ${e}u; -}`,yM=e=>{let r=e.length,t=[];for(let s=0;s{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=we.size(t),n=e[0].dataType,o=we.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=ke("input",n,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let _=0;_` + }`},du=(e,r)=>{let t=e[0].dims,s=we.size(t),n=e[0].dataType,o=we.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=ke("input",n,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let _=0;_` ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} - ${bM(l.length)} - ${yM(i)} + ${yM(l.length)} + ${vM(i)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} @@ -1775,7 +1775,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${a.indicesSet("indices",o,"index")}; } writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},y0=(e,r)=>{MM(e.inputs);let t=e.inputs.length===1?r:wM(e.inputs,r);e.compute(uu(e.inputs,t),{inputs:[0]})},v0=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return jt({axis:r,numOutputs:s,splitSizes:t})}}),vM,fi,T0,E0=Ve(()=>{gt(),Ct(),mr(),St(),vM=(e,r)=>{let[t,s,n,o]=e,{numHeads:i,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!we.areEqual(s.dims,[])&&!we.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!we.areEqual(n.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=n.dims[0],d=we.sizeFromDimension(t.dims,1)/c,u=a===0?n.dims[1]*2:d/i;if(a>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==n.dims[1]&&a/2!==n.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${n.dims[1]}`);if(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},fi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:n,scale:o}=r,i=e[0].dims[0],a=we.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=a/l,p=e[2].dims[1],d=n===0?p*2:c/s,u=new Array(i,l,c/d,d-p),f=we.computeStrides(u),_=[{type:1,data:o},{type:12,data:u},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],y=k=>{let w=ke("input",e[0].dataType,e[0].dims.length),v=ke("position_ids",e[1].dataType,e[1].dims.length),I=ke("cos_cache",e[2].dataType,e[2].dims.length),T=ke("sin_cache",e[3].dataType,e[3].dims.length),b=it("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},v0=(e,r)=>{wM(e.inputs);let t=e.inputs.length===1?r:bM(e.inputs,r);e.compute(du(e.inputs,t),{inputs:[0]})},x0=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return jt({axis:r,numOutputs:s,splitSizes:t})}}),xM,fi,E0,P0=Ve(()=>{gt(),Ct(),mr(),St(),xM=(e,r)=>{let[t,s,n,o]=e,{numHeads:i,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!we.areEqual(s.dims,[])&&!we.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!we.areEqual(n.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=n.dims[0],d=we.sizeFromDimension(t.dims,1)/c,u=a===0?n.dims[1]*2:d/i;if(a>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==n.dims[1]&&a/2!==n.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${n.dims[1]}`);if(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},fi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:n,scale:o}=r,i=e[0].dims[0],a=we.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=a/l,p=e[2].dims[1],d=n===0?p*2:c/s,u=new Array(i,l,c/d,d-p),f=we.computeStrides(u),_=[{type:1,data:o},{type:12,data:u},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],y=k=>{let w=ke("input",e[0].dataType,e[0].dims.length),v=ke("position_ids",e[1].dataType,e[1].dims.length),I=ke("cos_cache",e[2].dataType,e[2].dims.length),T=ke("sin_cache",e[3].dataType,e[3].dims.length),b=it("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` ${k.declareVariables(w,v,I,T,b)} ${k.mainStart(co)} @@ -1801,7 +1801,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${b.setByOffset("k",w.getByOffset("k"))} } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:jt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(u)/co)},programUniforms:_})}},T0=(e,r)=>{vM(e.inputs,r),e.compute(fi(e.inputs,r))}}),xM,TM,Sc,EM,P0,LT=Ve(()=>{mr(),gt(),Iu(),b0(),x0(),cn(),E0(),St(),xM=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let y=o&&o.dims.length!==0,k=i&&i.dims.length!==0;if(y&&o.dims.length===4&&o.dims[0]===l&&o.dims[1]!==r.kvNumHeads&&o.dims[2]===r.kvNumHeads&&o.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(y&&k){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=o.dims[2]}else if(y||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let v=0,I=!1,T=r.kvNumHeads?_*r.kvNumHeads:p;if(n&&n.dims.length>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(d!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=n.dims[2]}else{if(d!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=n.dims[1]*n.dims[3],I=!0}}let b=e.length>4?e[5]:void 0;if(b&&b.dims.length!==1&&b.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:T,headSize:_,vHeadSize:Math.floor(T/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:I,qkvFormat:w}},TM=jt({perm:[0,2,1,3]}),Sc=(e,r,t)=>{let s=r,n=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,n,t.headSize]),s=e.compute(es(s,TM.perm),{inputs:[s],outputs:[-1]})[0]),s},EM=(e,r,t,s)=>{let n=7,o=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],c=p=>{let d=ke("seq_lens",t.dataType,t.dims),u=ke("total_seq_lens",s.dataType,s.dims),f=it("pos_ids",n,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + }`};return{name:"RotaryEmbedding",shaderCache:{hint:jt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(u)/co)},programUniforms:_})}},E0=(e,r)=>{xM(e.inputs,r),e.compute(fi(e.inputs,r))}}),TM,EM,Ic,PM,C0,LT=Ve(()=>{mr(),gt(),$u(),y0(),T0(),cn(),P0(),St(),TM=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let y=o&&o.dims.length!==0,k=i&&i.dims.length!==0;if(y&&o.dims.length===4&&o.dims[0]===l&&o.dims[1]!==r.kvNumHeads&&o.dims[2]===r.kvNumHeads&&o.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(y&&k){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=o.dims[2]}else if(y||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let v=0,I=!1,T=r.kvNumHeads?_*r.kvNumHeads:p;if(n&&n.dims.length>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(d!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=n.dims[2]}else{if(d!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=n.dims[1]*n.dims[3],I=!0}}let b=e.length>4?e[5]:void 0;if(b&&b.dims.length!==1&&b.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:T,headSize:_,vHeadSize:Math.floor(T/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:I,qkvFormat:w}},EM=jt({perm:[0,2,1,3]}),Ic=(e,r,t)=>{let s=r,n=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,n,t.headSize]),s=e.compute(es(s,EM.perm),{inputs:[s],outputs:[-1]})[0]),s},PM=(e,r,t,s)=>{let n=7,o=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],c=p=>{let d=ke("seq_lens",t.dataType,t.dims),u=ke("total_seq_lens",s.dataType,s.dims),f=it("pos_ids",n,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` ${p.registerUniforms(_).declareVariables(d,u,f)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1832,7 +1832,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${f.setByOffset("global_idx","seqlen")} }; } - `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:c}},P0=(e,r)=>{let t=xM(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],n=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=jt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,f,_]=!n&&!o?e.compute(uu([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,n,o],y,k;if(r.doRotary){let T=e.compute(EM(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],b=e.inputs[7],E=e.inputs[8],x=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),S=[u,T,b,E],O=[-1];y=e.compute(fi(S,x),{inputs:S,outputs:O})[0],S.splice(0,1,f);let F=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(fi(S,F),{inputs:S,outputs:O})[0]}let w=Qo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?y:u,void 0,0),v=Sc(e,r.doRotary?k:f,t),I=Sc(e,_,t);Zo(e,w,v,I,void 0,void 0,i,a,void 0,t,l,c)}}),Ic,PM,CM,C0,zT=Ve(()=>{gt(),Ct(),cn(),St(),Ic=(e,r,t,s,n,o,i,a)=>{let l=ur(o),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=n*i,u=64;d===1&&(u=256);let f=[n,i,o/l],_=[n,i,2],y=["rank","type","type"],k=[];k.push(...ct(f,_));let w=v=>{let I=ke("x",r.dataType,3,l),T=ke("scale",t.dataType,t.dims),b=ke("bias",s.dataType,s.dims),E=it("output",1,3,2),x=[I,T,b,E];return` + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:c}},C0=(e,r)=>{let t=TM(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],n=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=jt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,f,_]=!n&&!o?e.compute(du([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,n,o],y,k;if(r.doRotary){let T=e.compute(PM(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],b=e.inputs[7],E=e.inputs[8],x=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),S=[u,T,b,E],O=[-1];y=e.compute(fi(S,x),{inputs:S,outputs:O})[0],S.splice(0,1,f);let F=jt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(fi(S,F),{inputs:S,outputs:O})[0]}let w=Qo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?y:u,void 0,0),v=Ic(e,r.doRotary?k:f,t),I=Ic(e,_,t);Zo(e,w,v,I,void 0,void 0,i,a,void 0,t,l,c)}}),$c,CM,SM,S0,zT=Ve(()=>{gt(),Ct(),cn(),St(),$c=(e,r,t,s,n,o,i,a)=>{let l=ur(o),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=n*i,u=64;d===1&&(u=256);let f=[n,i,o/l],_=[n,i,2],y=["rank","type","type"],k=[];k.push(...ct(f,_));let w=v=>{let I=ke("x",r.dataType,3,l),T=ke("scale",t.dataType,t.dims),b=ke("bias",s.dataType,s.dims),E=it("output",1,3,2),x=[I,T,b,E];return` var workgroup_shared : array<${p}, ${u}>; const workgroup_size = ${u}u; ${v.declareVariables(...x)} @@ -1866,7 +1866,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } - }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},PM=(e,r,t)=>{let s=r[0].dims,n=s,o=2,i=s[0],a=s[1],l=we.sizeFromDimension(s,o),c=ur(l),p=we.size(n)/c,d=Ic(e,r[0],r[1],r[2],i,l,a,t.epsilon),u=[i,a,l/c],f=[i,a],_=["type","none"],y=k=>{let w=ke("x",r[0].dataType,u.length,c),v=ke("scale_shift",1,f.length,2),I=it("output",r[0].dataType,u.length,c),T=[w,v,I];return` + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},CM=(e,r,t)=>{let s=r[0].dims,n=s,o=2,i=s[0],a=s[1],l=we.sizeFromDimension(s,o),c=ur(l),p=we.size(n)/c,d=$c(e,r[0],r[1],r[2],i,l,a,t.epsilon),u=[i,a,l/c],f=[i,a],_=["type","none"],y=k=>{let w=ke("x",r[0].dataType,u.length,c),v=ke("scale_shift",1,f.length,2),I=it("output",r[0].dataType,u.length,c),T=[w,v,I];return` ${k.registerUniform("output_size","u32").declareVariables(...T)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1876,7 +1876,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let scale_shift = ${v.getByIndices("vec2(batch, channel)")}; let value = ${w.getByOffset("global_idx")} * ${I.type.value}(scale_shift.x) + ${I.type.value}(scale_shift.y); ${I.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ct(u,f,u)]}),getShaderSource:y},{inputs:[r[0],d]})},CM=(e,r,t)=>{let s=r[0].dims,n=s,o=s[0],i=s[s.length-1],a=we.sizeFromDimension(s,1)/i,l=ur(i),c=we.size(n)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],u=!1,f=[0,s.length-1];for(let w=0;ws[f[v]])),y=Ic(e,_,r[1],r[2],o,a,i,t.epsilon),k=w=>{let v=Ar(r[0].dataType),I=l===1?"vec2f":`mat${l}x2f`,T=x=>{let S=x===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${v}(${O}(scale.${S}))`;case 2:return`vec2<${v}>(${O}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${v}>(${O}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},b=ke("input",r[0].dataType,r[0].dims,l),E=it("output",r[0].dataType,n,l);return` + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ct(u,f,u)]}),getShaderSource:y},{inputs:[r[0],d]})},SM=(e,r,t)=>{let s=r[0].dims,n=s,o=s[0],i=s[s.length-1],a=we.sizeFromDimension(s,1)/i,l=ur(i),c=we.size(n)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],u=!1,f=[0,s.length-1];for(let w=0;ws[f[v]])),y=$c(e,_,r[1],r[2],o,a,i,t.epsilon),k=w=>{let v=Ar(r[0].dataType),I=l===1?"vec2f":`mat${l}x2f`,T=x=>{let S=x===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${v}(${O}(scale.${S}))`;case 2:return`vec2<${v}>(${O}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${v}>(${O}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},b=ke("input",r[0].dataType,r[0].dims,l),E=it("output",r[0].dataType,n,l);return` @group(0) @binding(0) var input : array<${b.type.storage}>; @group(0) @binding(1) var scale_input : array<${I}>; @group(0) @binding(2) var output : array<${E.type.storage}>; @@ -1890,15 +1890,15 @@ fn calculateOutputIndex(index: u32) -> u32 { 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:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],y]})},C0=(e,r)=>{r.format==="NHWC"?CM(e,e.inputs,r):PM(e,e.inputs,r)}}),SM,IM,S0,BT=Ve(()=>{gt(),Ct(),St(),SM=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},IM=(e,r,t)=>{let s=r.simplified,n=e[0].dims,o=e[1],i=!s&&e[2],a=n,l=we.normalizeAxis(r.axis,n.length),c=we.sizeToDimension(n,l),p=we.sizeFromDimension(n,l),d=we.size(o.dims),u=i?we.size(i.dims):0;if(d!==p||i&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],y]})},S0=(e,r)=>{r.format==="NHWC"?SM(e,e.inputs,r):CM(e,e.inputs,r)}}),IM,$M,I0,BT=Ve(()=>{gt(),Ct(),St(),IM=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},$M=(e,r,t)=>{let s=r.simplified,n=e[0].dims,o=e[1],i=!s&&e[2],a=n,l=we.normalizeAxis(r.axis,n.length),c=we.sizeToDimension(n,l),p=we.sizeFromDimension(n,l),d=we.size(o.dims),u=i?we.size(i.dims):0;if(d!==p||i&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. Size of scale and bias (if provided) must match this. Got scale size of ${d} and bias size of ${u}`);let f=[];for(let b=0;b1,v=t>2,I=b=>{let E=Ar(e[0].dataType),x=[ke("x",e[0].dataType,e[0].dims,_),ke("scale",o.dataType,o.dims,_)];i&&x.push(ke("bias",i.dataType,i.dims,_)),x.push(it("output",e[0].dataType,a,_)),w&&x.push(it("mean_data_output",1,f)),v&&x.push(it("inv_std_output",1,f));let S=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${b.registerUniforms(S).declareVariables(...x)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${tu("f32",_)}; - var mean_square_vector = ${tu("f32",_)}; + var mean_vector = ${ru("f32",_)}; + var mean_square_vector = ${ru("f32",_)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${io(E,_,"x[h + offset]")}; @@ -1918,7 +1918,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${w?"mean_data_output[global_idx] = mean":""}; ${v?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},T=[{dims:a,dataType:e[0].dataType}];return w&&T.push({dims:f,dataType:1}),v&&T.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:y},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:k}),getShaderSource:I}},S0=(e,r)=>{SM(e.inputs),e.compute(IM(e.inputs,r,e.outputCount))}}),$M,I0,RT=Ve(()=>{Ct(),Ou(),Du(),$M=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.")},I0=e=>{$M(e.inputs);let r=lo.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(Fu(e.inputs,{activation:""},r));else{let n=r[r.length-2],o=we.size(e.inputs[0].dims.slice(0,-2)),i=we.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&n===1&&i===1){let a=e.inputs[0].reshape([1,o,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,o,t],p=[a,l];e.compute(_i(p,{activation:""},r,c),{inputs:p})}else e.compute(_i(e.inputs,{activation:""},r))}}}),kM,AM,FM,$0,k0,NT=Ve(()=>{gt(),Ct(),mr(),St(),kM=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((r.k+r.blockSize-1)/r.blockSize),o=r.blockSize/8*r.bits,i=e[1];if(!we.areEqual(i.dims,[r.n,n,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(we.size(a)!==r.n*n)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*n:r.n*Math.floor((n+1)/2);if(we.size(l)!==c)throw new Error("zeroPoints input size error.")}},AM=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=ur(r.k),u=ur(c),f=ur(i),_=a.concat([n,i]),y=n>1&&i/f%2===0?2:1,k=we.size(_)/f/y,w=64,v=[],I=[l,n,o/d],T=we.convertShape(e[1].dims).slice();T.splice(-1,1,c/u),v.push(...ct(I)),v.push(...ct(T)),v.push(...ct(e[2].dims)),e.length===4&&v.push(...ct(we.convertShape(e[3].dims)));let b=[l,n,i/f];v.push(...ct(b));let E=x=>{let S=I.length,O=ke("a",e[0].dataType,S,d),F=ke("b",12,T.length,u),H=ke("scales",e[2].dataType,e[2].dims.length),W=[O,F,H],B=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;B&&W.push(B);let Y=b.length,X=it("output",e[0].dataType,Y,f),J=Ar(e[0].dataType),re=(()=>{switch(d){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ne=()=>{let oe=` + }`},T=[{dims:a,dataType:e[0].dataType}];return w&&T.push({dims:f,dataType:1}),v&&T.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:y},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:k}),getShaderSource:I}},I0=(e,r)=>{IM(e.inputs),e.compute($M(e.inputs,r,e.outputCount))}}),kM,$0,RT=Ve(()=>{Ct(),Du(),Lu(),kM=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.")},$0=e=>{kM(e.inputs);let r=lo.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(Ou(e.inputs,{activation:""},r));else{let n=r[r.length-2],o=we.size(e.inputs[0].dims.slice(0,-2)),i=we.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&n===1&&i===1){let a=e.inputs[0].reshape([1,o,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,o,t],p=[a,l];e.compute(_i(p,{activation:""},r,c),{inputs:p})}else e.compute(_i(e.inputs,{activation:""},r))}}}),AM,FM,OM,k0,A0,NT=Ve(()=>{gt(),Ct(),mr(),St(),AM=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let n=Math.floor((r.k+r.blockSize-1)/r.blockSize),o=r.blockSize/8*r.bits,i=e[1];if(!we.areEqual(i.dims,[r.n,n,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(we.size(a)!==r.n*n)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*n:r.n*Math.floor((n+1)/2);if(we.size(l)!==c)throw new Error("zeroPoints input size error.")}},FM=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=ur(r.k),u=ur(c),f=ur(i),_=a.concat([n,i]),y=n>1&&i/f%2===0?2:1,k=we.size(_)/f/y,w=64,v=[],I=[l,n,o/d],T=we.convertShape(e[1].dims).slice();T.splice(-1,1,c/u),v.push(...ct(I)),v.push(...ct(T)),v.push(...ct(e[2].dims)),e.length===4&&v.push(...ct(we.convertShape(e[3].dims)));let b=[l,n,i/f];v.push(...ct(b));let E=x=>{let S=I.length,O=ke("a",e[0].dataType,S,d),F=ke("b",12,T.length,u),H=ke("scales",e[2].dataType,e[2].dims.length),W=[O,F,H],B=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;B&&W.push(B);let Y=b.length,X=it("output",e[0].dataType,Y,f),J=Ar(e[0].dataType),re=(()=>{switch(d){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ne=()=>{let oe=` // reuse a data var input_offset = ${O.indicesToOffset(`${O.type.indices}(batch, row, word_offset)`)}; var a_data: ${re}; @@ -1995,7 +1995,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${f};${y};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:v}),getShaderSource:E}},FM=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=ur(r.k),u=ur(c),f=a.concat([n,i]),_=128,y=i%8===0?8:i%4===0?4:1,k=_/y,w=k*u*8,v=w/d,I=w/r.blockSize,T=we.size(f)/y,b=[],E=[l,n,o/d],x=we.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),b.push(...ct(E)),b.push(...ct(x)),b.push(...ct(e[2].dims)),e.length===4&&b.push(...ct(we.convertShape(e[3].dims)));let S=[l,n,i];b.push(...ct(S));let O=F=>{let H=E.length,W=ke("a",e[0].dataType,H,d),B=ke("b",12,x.length,u),Y=ke("scales",e[2].dataType,e[2].dims.length),X=[W,B,Y],J=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;J&&X.push(J);let re=S.length,ne=it("output",e[0].dataType,re),le=Ar(e[0].dataType),pe=()=>{switch(d){case 1:return` + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${f};${y};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:v}),getShaderSource:E}},OM=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=ur(r.k),u=ur(c),f=a.concat([n,i]),_=128,y=i%8===0?8:i%4===0?4:1,k=_/y,w=k*u*8,v=w/d,I=w/r.blockSize,T=we.size(f)/y,b=[],E=[l,n,o/d],x=we.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),b.push(...ct(E)),b.push(...ct(x)),b.push(...ct(e[2].dims)),e.length===4&&b.push(...ct(we.convertShape(e[3].dims)));let S=[l,n,i];b.push(...ct(S));let O=F=>{let H=E.length,W=ke("a",e[0].dataType,H,d),B=ke("b",12,x.length,u),Y=ke("scales",e[2].dataType,e[2].dims.length),X=[W,B,Y],J=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;J&&X.push(J);let re=S.length,ne=it("output",e[0].dataType,re),le=Ar(e[0].dataType),pe=()=>{switch(d){case 1:return` let a_data0 = vec4<${le}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${le}>(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<${le}>(sub_a[word_offset], sub_a[word_offset + 1]); @@ -2069,7 +2069,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,"output_value")} } } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${k};${y}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:T},programUniforms:b}),getShaderSource:O}},$0=(e,r)=>{kM(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(FM(e.inputs,r)):e.compute(AM(e.inputs,r))},k0=e=>jt(e)}),OM,DM,LM,zM,BM,RM,NM,jM,A0,jT=Ve(()=>{gt(),Ct(),St(),OM=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},DM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${k};${y}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:T},programUniforms:b}),getShaderSource:O}},k0=(e,r)=>{AM(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(OM(e.inputs,r)):e.compute(FM(e.inputs,r))},A0=e=>jt(e)}),DM,LM,zM,BM,RM,NM,jM,VM,F0,jT=Ve(()=>{gt(),Ct(),St(),DM=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},LM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { break; @@ -2086,7 +2086,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${s} value = x[offset]; } - `},LM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + `},zM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { k = -k; @@ -2104,7 +2104,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${s} value = x[offset]; - `},zM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + `},BM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { k = 0; @@ -2118,7 +2118,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${s} value = x[offset]; - `},BM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` + `},RM=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { k += i32(${lt("uniforms.x_shape",n,r)}]); @@ -2132,7 +2132,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${s} value = x[offset]; - `},RM=(e,r,t)=>{switch(t.mode){case 0:return DM(e,r,t.pads.length);case 1:return LM(e,r,t.pads.length);case 2:return zM(e,r,t.pads.length);case 3:return BM(e,r,t.pads.length);default:throw new Error("Invalid mode")}},NM=(e,r)=>{let t=we.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,n=we.size(t),o=[{type:12,data:n},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&o.push({type:i?e[2].dataType:1,data:r.value}),o.push(...ct(e[0].dims,t));let a=["rank"],l=c=>{let p=it("output",e[0].dataType,t.length),d=ke("x",e[0].dataType,s.length),u=d.type.value,f=RM(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?u:"f32"}),` + `},NM=(e,r,t)=>{switch(t.mode){case 0:return LM(e,r,t.pads.length);case 1:return zM(e,r,t.pads.length);case 2:return BM(e,r,t.pads.length);case 3:return RM(e,r,t.pads.length);default:throw new Error("Invalid mode")}},jM=(e,r)=>{let t=we.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,n=we.size(t),o=[{type:12,data:n},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&o.push({type:i?e[2].dataType:1,data:r.value}),o.push(...ct(e[0].dims,t));let a=["rank"],l=c=>{let p=it("output",e[0].dataType,t.length),d=ke("x",e[0].dataType,s.length),u=d.type.value,f=NM(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?u:"f32"}),` ${c.registerUniforms(_).declareVariables(d,p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -2142,7 +2142,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var value = ${u}(0); ${f} output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(t)/64)},programUniforms:o}),getShaderSource:l}},jM=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,n=e[0].dims.length,o=new Int32Array(2*n).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;lo[Number(l)]=Number(a));let i=[];return o.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},A0=(e,r)=>{OM(e.inputs);let t=jM(e.inputs,r);e.compute(NM(e.inputs,t),{inputs:[0]})}}),Vo,$c,kc,Ac,Fc,VM,UM,Oc,Dc,F0,O0,Lc,D0,L0,zc,z0,B0,R0,N0,VT=Ve(()=>{Es(),gt(),Ct(),St(),Vo=e=>{if(Jt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},$c=(e,r,t)=>{let s=r.format==="NHWC",n=e.dims.slice();s&&n.splice(1,0,n.pop());let o=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=o?r.dilations.slice():[],c=r.pads.slice();mi.adjustPoolAttributes(t,n,i,a,l,c);let p=mi.computePoolOutputShape(t,n,a,l,i,c,r.autoPad),d=Object.assign({},r);o?Object.assign(d,{kernelShape:i,strides:a,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},kc=(e,r)=>{let t=r.format==="NHWC",s=we.size(e),n=we.size(r.kernelShape),o=[{type:12,data:s},{type:12,data:n}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);o.push({type:12,data:a},{type:12,data:l},{type:12,data:c},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],y=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];u=!!(y+k),o.push({type:12,data:f},{type:12,data:_},{type:12,data:y},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,i,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=we.computeStrides(r.kernelShape);o.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[o,i,!!l,!1,!1]}},Ac=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u=n.format==="NHWC",f=r.type.value,_=it("output",r.type.tensor,s);if(n.kernelShape.length<=2){let y="",k="",w="",v=t-(u?2:1);if(p?y=` + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(t)/64)},programUniforms:o}),getShaderSource:l}},VM=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,n=e[0].dims.length,o=new Int32Array(2*n).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;lo[Number(l)]=Number(a));let i=[];return o.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},F0=(e,r)=>{DM(e.inputs);let t=VM(e.inputs,r);e.compute(jM(e.inputs,t),{inputs:[0]})}}),Vo,kc,Ac,Fc,Oc,UM,WM,Dc,Lc,O0,D0,zc,L0,z0,Bc,B0,R0,N0,j0,VT=Ve(()=>{Es(),gt(),Ct(),St(),Vo=e=>{if(Jt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},kc=(e,r,t)=>{let s=r.format==="NHWC",n=e.dims.slice();s&&n.splice(1,0,n.pop());let o=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=o?r.dilations.slice():[],c=r.pads.slice();mi.adjustPoolAttributes(t,n,i,a,l,c);let p=mi.computePoolOutputShape(t,n,a,l,i,c,r.autoPad),d=Object.assign({},r);o?Object.assign(d,{kernelShape:i,strides:a,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},Ac=(e,r)=>{let t=r.format==="NHWC",s=we.size(e),n=we.size(r.kernelShape),o=[{type:12,data:s},{type:12,data:n}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);o.push({type:12,data:a},{type:12,data:l},{type:12,data:c},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],y=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];u=!!(y+k),o.push({type:12,data:f},{type:12,data:_},{type:12,data:y},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,i,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=we.computeStrides(r.kernelShape);o.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[o,i,!!l,!1,!1]}},Fc=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u=n.format==="NHWC",f=r.type.value,_=it("output",r.type.tensor,s);if(n.kernelShape.length<=2){let y="",k="",w="",v=t-(u?2:1);if(p?y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${v}] < 0 || xIndices[${v}] @@ -2231,9 +2231,9 @@ fn calculateOutputIndex(index: u32) -> u32 { ${i} output[global_idx] = value; - }`}},Fc=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,VM=e=>`${Fc(e)};${e.countIncludePad}`,UM=e=>`${Fc(e)};${e.storageOrder};${e.dilations}`,Oc=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}),Dc=(e,r,t,s)=>{let[n,o]=$c(r,s,t),i=ke("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",c="";n.countIncludePad?c+=`value /= ${a}(uniforms.kernelSize);`:c+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,f,_]=kc(o,n);p.push(...ct(r.dims,o));let y=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:k=>Ac(k,i,r.dims.length,o.length,n,l,c,0,d,u,f,_)}},F0=e=>{let r=e.count_include_pad!==0,t=Oc(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:VM(s)}},O0=(e,r)=>{Vo(e.inputs),e.compute(Dc("AveragePool",e.inputs[0],!1,r))},Lc={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},D0=e=>{let r=e.format;return{format:r,...Lc,cacheKey:r}},L0=(e,r)=>{Vo(e.inputs),e.compute(Dc("GlobalAveragePool",e.inputs[0],!0,r))},zc=(e,r,t,s)=>{let[n,o]=$c(r,s,t),i=` + }`}},Oc=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,UM=e=>`${Oc(e)};${e.countIncludePad}`,WM=e=>`${Oc(e)};${e.storageOrder};${e.dilations}`,Dc=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}),Lc=(e,r,t,s)=>{let[n,o]=kc(r,s,t),i=ke("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",c="";n.countIncludePad?c+=`value /= ${a}(uniforms.kernelSize);`:c+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,f,_]=Ac(o,n);p.push(...ct(r.dims,o));let y=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:k=>Fc(k,i,r.dims.length,o.length,n,l,c,0,d,u,f,_)}},O0=e=>{let r=e.count_include_pad!==0,t=Dc(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:UM(s)}},D0=(e,r)=>{Vo(e.inputs),e.compute(Lc("AveragePool",e.inputs[0],!1,r))},zc={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},L0=e=>{let r=e.format;return{format:r,...zc,cacheKey:r}},z0=(e,r)=>{Vo(e.inputs),e.compute(Lc("GlobalAveragePool",e.inputs[0],!0,r))},Bc=(e,r,t,s)=>{let[n,o]=kc(r,s,t),i=` value = max(x_val, value); - `,a="",l=ke("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,f,_]=kc(o,n);return p.push(...ct(r.dims,o)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:y=>Ac(y,l,r.dims.length,o.length,n,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},z0=(e,r)=>{Vo(e.inputs),e.compute(zc("MaxPool",e.inputs[0],!1,r))},B0=e=>{let r=e.storage_order,t=e.dilations,s=Oc(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:r,dilations:t,...s,cacheKey:""};return{...n,cacheKey:UM(n)}},R0=e=>{let r=e.format;return{format:r,...Lc,cacheKey:r}},N0=(e,r)=>{Vo(e.inputs),e.compute(zc("GlobalMaxPool",e.inputs[0],!0,r))}}),WM,GM,j0,V0,UT=Ve(()=>{gt(),Ct(),mr(),St(),WM=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((n,o)=>o===r.axis||n===e[0].dims[o]).reduce((n,o)=>n&&o,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},GM=(e,r)=>{let t=we.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,n=s===3,o=e[0].dims,i=e[1].dataType,a=we.size(o),l=s===3||s===2,c=l?[Math.ceil(we.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(we.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,y=ur(a),k=f&&(!l||y===4),w=k?y:1,v=k&&!l?y:1,I=ke("input",l?12:s,c.length,v),T=ke("scale",i,p.length),b=d?ke("zero_point",l?12:s,u.length):void 0,E=it("output",i,o.length,w),x=[I,T];b&&x.push(b);let S=[c,p];d&&S.push(u);let O=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...ct(...S,o)],F=H=>{let W=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + `,a="",l=ke("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,f,_]=Ac(o,n);return p.push(...ct(r.dims,o)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:y=>Fc(y,l,r.dims.length,o.length,n,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},B0=(e,r)=>{Vo(e.inputs),e.compute(Bc("MaxPool",e.inputs[0],!1,r))},R0=e=>{let r=e.storage_order,t=e.dilations,s=Dc(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:r,dilations:t,...s,cacheKey:""};return{...n,cacheKey:WM(n)}},N0=e=>{let r=e.format;return{format:r,...zc,cacheKey:r}},j0=(e,r)=>{Vo(e.inputs),e.compute(Bc("GlobalMaxPool",e.inputs[0],!0,r))}}),GM,KM,V0,U0,UT=Ve(()=>{gt(),Ct(),mr(),St(),GM=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((n,o)=>o===r.axis||n===e[0].dims[o]).reduce((n,o)=>n&&o,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},KM=(e,r)=>{let t=we.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,n=s===3,o=e[0].dims,i=e[1].dataType,a=we.size(o),l=s===3||s===2,c=l?[Math.ceil(we.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(we.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,y=ur(a),k=f&&(!l||y===4),w=k?y:1,v=k&&!l?y:1,I=ke("input",l?12:s,c.length,v),T=ke("scale",i,p.length),b=d?ke("zero_point",l?12:s,u.length):void 0,E=it("output",i,o.length,w),x=[I,T];b&&x.push(b);let S=[c,p];d&&S.push(u);let O=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...ct(...S,o)],F=H=>{let W=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${H.registerUniforms(W).declareVariables(...x,E)} ${H.mainStart()} ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -2271,12 +2271,12 @@ fn calculateOutputIndex(index: u32) -> u32 { let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${b.getByIndices("scale_indices")};`:`let zero_point_value = ${l?n?"i32":"u32":I.type.value}(0);`}; // Compute and write output ${E.setByOffset("global_idx",`${E.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getShaderSource:F,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:O})}},j0=(e,r)=>{WM(e.inputs,r),e.compute(GM(e.inputs,r))},V0=e=>jt({axis:e.axis,blockSize:e.blockSize})}),KM,HM,U0,WT=Ve(()=>{Es(),gt(),St(),KM=(e,r,t)=>{let s=e===r,n=er&&t>0;if(s||n||o)throw new Error("Range these inputs' contents are invalid.")},HM=(e,r,t,s)=>{let n=Math.abs(Math.ceil((r-e)/t)),o=[n],i=n,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ct(o)],l=c=>{let p=it("output",s,o.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getShaderSource:F,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:O})}},V0=(e,r)=>{GM(e.inputs,r),e.compute(KM(e.inputs,r))},U0=e=>jt({axis:e.axis,blockSize:e.blockSize})}),HM,qM,W0,WT=Ve(()=>{Es(),gt(),St(),HM=(e,r,t)=>{let s=e===r,n=er&&t>0;if(s||n||o)throw new Error("Range these inputs' contents are invalid.")},qM=(e,r,t,s)=>{let n=Math.abs(Math.ceil((r-e)/t)),o=[n],i=n,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ct(o)],l=c=>{let p=it("output",s,o.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` ${c.registerUniforms(u).declareVariables(p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},U0=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Jt.webgpu.validateInputContent&&KM(r,t,s),e.compute(HM(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),qM,Bc,Rc,QM,W0,G0,GT=Ve(()=>{gt(),Ct(),mr(),St(),qM=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let n=`{ + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},W0=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Jt.webgpu.validateInputContent&&HM(r,t,s),e.compute(qM(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),QM,Rc,Nc,XM,G0,K0,GT=Ve(()=>{gt(),Ct(),mr(),St(),QM=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let n=`{ var oldValue = 0; loop { let newValueF32 =`,o=`; @@ -2289,7 +2289,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` ${n}bitcast<${s}>(oldValue) + (${t})${o}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` - ${n}max(bitcast(oldValue), (${t}))${o}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${n}min(bitcast<${s}>(oldValue), (${t}))${o}`;case"mul":return`${n}(bitcast<${s}>(oldValue) * (${t}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Bc=(e,r)=>`${e===1?` + ${n}max(bitcast(oldValue), (${t}))${o}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${n}min(bitcast<${s}>(oldValue), (${t}))${o}`;case"mul":return`${n}(bitcast<${s}>(oldValue) * (${t}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Rc=(e,r)=>`${e===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; @@ -2306,10 +2306,10 @@ fn calculateOutputIndex(index: u32) -> u32 { index += i32(dim_value); } } - data_offset += u32((u32(index) * element_count_dim));`,Rc=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + data_offset += u32((u32(index) * element_count_dim));`,Nc=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; - ${qM(e.reduction,"output[data_offset + i]","value",r)} - }`,QM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t,o=1,i=Math.ceil(we.size(s)/o),a=s[s.length-1],l=we.sizeFromDimension(t,a),c=we.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ct(e[1].dims,e[2].dims,n)],d=u=>{let f=ke("indices",e[1].dataType,e[1].dims.length),_=ke("updates",e[2].dataType,e[2].dims.length,o),y=r.reduction!=="none"&&r.reduction!==""?wb("output",e[0].dataType,n.length):it("output",e[0].dataType,n.length,o);return` + ${QM(e.reduction,"output[data_offset + i]","value",r)} + }`,XM=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t,o=1,i=Math.ceil(we.size(s)/o),a=s[s.length-1],l=we.sizeFromDimension(t,a),c=we.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ct(e[1].dims,e[2].dims,n)],d=u=>{let f=ke("indices",e[1].dataType,e[1].dims.length),_=ke("updates",e[2].dataType,e[2].dims.length,o),y=r.reduction!=="none"&&r.reduction!==""?bb("output",e[0].dataType,n.length):it("output",e[0].dataType,n.length,o);return` ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,y)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -2339,9 +2339,9 @@ fn calculateOutputIndex(index: u32) -> u32 { 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); - ${Bc(t.length,!1)} + ${Rc(t.length,!1)} } - ${Rc(r,y.type.value,!1)} + ${Nc(r,y.type.value,!1)} } return; } @@ -2351,11 +2351,11 @@ fn calculateOutputIndex(index: u32) -> u32 { var indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); - ${Bc(t.length,!0)} + ${Rc(t.length,!0)} } - ${Rc(r,y.type.value,!0)} - }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},W0=e=>jt({reduction:e.reduction}),G0=(e,r)=>{e.compute(QM(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),XM,JM,YM,Nc,ZM,ew,tw,rw,sw,nw,ow,aw,jc,iw,lw,cw,uw,dw,K0,H0,KT=Ve(()=>{gt(),Ct(),mr(),St(),XM=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and - one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},JM=(e,r,t)=>{r.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((n,o)=>s[n]=e[o]),s},YM=(e,r,t,s,n,o)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>o.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");XM(s,r),r.axes.length>0&&JM(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>n.push(Number(p))),n.length!==0&&n.length!==c&&t>=18&&n.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(n.length!==0&&n.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof n<"u"&&s.length>0&&n.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Nc=(e,r,t,s)=>` + ${Nc(r,y.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},G0=e=>jt({reduction:e.reduction}),K0=(e,r)=>{e.compute(XM(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),JM,YM,ZM,jc,ew,tw,rw,sw,nw,ow,aw,iw,Vc,lw,cw,uw,dw,pw,H0,q0,KT=Ve(()=>{gt(),Ct(),mr(),St(),JM=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},YM=(e,r,t)=>{r.every(n=>n>=0&&n{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((n,o)=>s[n]=e[o]),s},ZM=(e,r,t,s,n,o)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>o.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");JM(s,r),r.axes.length>0&&YM(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>n.push(Number(p))),n.length!==0&&n.length!==c&&t>=18&&n.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(n.length!==0&&n.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof n<"u"&&s.length>0&&n.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},jc=(e,r,t,s)=>` // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). @@ -2363,12 +2363,12 @@ fn calculateOutputIndex(index: u32) -> u32 { let whole = ${s}(big / (${t})); let fract = ${s}(big % (${t})) / ${s}(${t}); return whole + fract; -`,ZM=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, +`,ew=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` if (xScale < 1.0 || floor(xScale) != xScale) { return ${r}(xResized) / ${r}(xScale); } else { - ${Nc("xResized","lengthOriginal","lengthResized",r)} + ${jc("xResized","lengthOriginal","lengthResized",r)} } `;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; @@ -2377,7 +2377,7 @@ fn calculateOutputIndex(index: u32) -> u32 { }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { - ${Nc("xResized","lengthOriginal - 1","lengthResized - 1",r)} + ${jc("xResized","lengthOriginal - 1","lengthResized - 1",r)} }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${r}(roiStart) * ${r}(lengthOriginal - 1) + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / @@ -2388,7 +2388,7 @@ fn calculateOutputIndex(index: u32) -> u32 { const adjustment = ${r}(lengthResized) / outputWidth; const center = ${r}(lengthOriginal) / 2; const offset = center * (1 - adjustment); - return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ew=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",tw=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),n=e.length===0?s:e.slice();return r.length>0?(r.forEach((o,i)=>{s[o]=n[i],s[i+t]=n[r.length+i]}),s):n},rw=(e,r,t,s)=>{let n=[];if(t.length>0)if(s.length>0){if(e.forEach(o=>n.push(o)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((o,i)=>n[o]=t[i])}else t.forEach(o=>n.push(o));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((o,i)=>Math.round(o*r[i]))}return n},sw=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(o=>r[o]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(o=>r[o]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let n=e.slice();return t.axes.length>0?(t.axes.forEach(o=>r[o]=s),t.axes.forEach(o=>n[o]=Math.round(e[o]*r[o]))):(r.fill(s,0,r.length),n.forEach((o,i)=>n[i]=Math.round(o*r[i]))),n},nw=(e,r,t,s,n)=>` + return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",tw=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",rw=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),n=e.length===0?s:e.slice();return r.length>0?(r.forEach((o,i)=>{s[o]=n[i],s[i+t]=n[r.length+i]}),s):n},sw=(e,r,t,s)=>{let n=[];if(t.length>0)if(s.length>0){if(e.forEach(o=>n.push(o)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((o,i)=>n[o]=t[i])}else t.forEach(o=>n.push(o));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((o,i)=>Math.round(o*r[i]))}return n},nw=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(o=>r[o]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(o=>r[o]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let n=e.slice();return t.axes.length>0?(t.axes.forEach(o=>r[o]=s),t.axes.forEach(o=>n[o]=Math.round(e[o]*r[o]))):(r.fill(s,0,r.length),n.forEach((o,i)=>n[i]=Math.round(o*r[i]))),n},ow=(e,r,t,s,n)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { var original_indices: array<${e.type.value}, ${t.length}>; for (var i:u32 = 0; i < ${t.length}; i++) { @@ -2406,7 +2406,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return original_indices; - }`,ow=(e,r,t,s,n,o,i)=>` + }`,aw=(e,r,t,s,n,o,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${s.length}; i++) { @@ -2437,7 +2437,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")} } return input_indices; - }`,aw=(e,r)=>` + }`,iw=(e,r)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${r.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; @@ -2446,15 +2446,15 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return true; - }`,jc=(e,r,t,s)=>e.rank>s?` + }`,Vc=(e,r,t,s)=>e.rank>s?` ${e.indicesSet("input_indices",r,"channel")}; ${e.indicesSet("input_indices",t,"batch")}; -`:"",iw=(e,r,t,s,n)=>{let[o,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` +`:"",lw=(e,r,t,s,n)=>{let[o,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; - ${jc(e,l,o,2)} + ${Vc(e,l,o,2)} return ${e.getByIndices("input_indices")}; } @@ -2490,7 +2490,7 @@ fn calculateOutputIndex(index: u32) -> u32 { dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); - }`},lw=(e,r,t,s,n,o,i,a,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],f=e.type.value,_=y=>{let k=y===d?"row":"col";return` + }`},cw=(e,r,t,s,n,o,i,a,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],f=e.type.value,_=y=>{let k=y===d?"row":"col";return` fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { var output_index = ${r.indicesGet("output_indices",y)}; var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[y]}, @@ -2538,13 +2538,13 @@ fn calculateOutputIndex(index: u32) -> u32 { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } - `},cw=(e,r,t,s,n)=>{let[o,i,a,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + `},uw=(e,r,t,s,n)=>{let[o,i,a,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; - ${jc(e,c,o,3)} + ${Vc(e,c,o,3)} return ${e.getByIndices("input_indices")}; } @@ -2597,18 +2597,18 @@ fn calculateOutputIndex(index: u32) -> u32 { } 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); - }`},uw=(e,r,t,s,n,o)=>{let i=e.dims,a=tw(o,r.axes,i.length),l=rw(i,s,n,r.axes),c=s.slice();s.length===0&&(c=i.map((v,I)=>v===0?1:l[I]/v),r.keepAspectRatioPolicy!=="stretch"&&(l=sw(i,c,r)));let p=it("output",e.dataType,l.length),d=ke("input",e.dataType,i.length),u=we.size(l),f=i.length===l.length&&i.every((v,I)=>v===l[I]),_=r.coordinateTransformMode==="tf_crop_and_resize",y=r.extrapolationValue,k=d.type.value,w=v=>` + }`},dw=(e,r,t,s,n,o)=>{let i=e.dims,a=rw(o,r.axes,i.length),l=sw(i,s,n,r.axes),c=s.slice();s.length===0&&(c=i.map((v,I)=>v===0?1:l[I]/v),r.keepAspectRatioPolicy!=="stretch"&&(l=nw(i,c,r)));let p=it("output",e.dataType,l.length),d=ke("input",e.dataType,i.length),u=we.size(l),f=i.length===l.length&&i.every((v,I)=>v===l[I]),_=r.coordinateTransformMode==="tf_crop_and_resize",y=r.extrapolationValue,k=d.type.value,w=v=>` ${f?"":` - ${ZM(r.coordinateTransformMode,k)}; + ${ew(r.coordinateTransformMode,k)}; ${(()=>{switch(r.mode){case"nearest":return` - ${aw(d,i)}; - ${ew(r.nearestMode,t,k)}; - ${ow(d,p,i,l,c.length,a.length,_)}; + ${iw(d,i)}; + ${tw(r.nearestMode,t,k)}; + ${aw(d,p,i,l,c.length,a.length,_)}; `;case"linear":return` - ${nw(p,i,l,c.length,a.length)}; - ${(()=>{if(i.length===2||i.length===4)return`${iw(d,p,i,_,y)}`;if(i.length===3||i.length===5)return`${cw(d,p,i,_,y)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + ${ow(p,i,l,c.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${lw(d,p,i,_,y)}`;if(i.length===3||i.length===5)return`${uw(d,p,i,_,y)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` - ${(()=>{if(i.length===2||i.length===4)return`${lw(d,p,i,l,c,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + ${(()=>{if(i.length===2||i.length===4)return`${cw(d,p,i,l,c,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${v.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} @@ -2624,7 +2624,7 @@ fn calculateOutputIndex(index: u32) -> u32 { output[global_idx] = ${r.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; `} - }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${n.length>0?n:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:a},...ct(i,l)]})}},dw=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},K0=(e,r)=>{let t=[],s=[],n=[],o=dw(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");YM(e.inputs,r,o,t,s,n),e.compute(uw(e.inputs[0],r,o,t,s,n),{inputs:[0]})},H0=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,o=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return jt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:o,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:c})}}),pw,mw,q0,HT=Ve(()=>{gt(),Ct(),St(),pw=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=r.dims[r.dims.length-1],o=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},mw=(e,r,t,s)=>{let n=r.simplified,o=e[0].dims,i=we.size(o),a=o,l=i,c=o.slice(-1)[0],p=s?o.slice(0,-1).concat(1):[],d=!n&&e.length>3,u=e.length>4,f=s&&t>1,_=s&&t>2,y=t>3,k=64,w=ur(c),v=[{type:12,data:l},{type:12,data:w},{type:12,data:c},{type:1,data:r.epsilon}],I=b=>{let E=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[ke("x",e[0].dataType,e[0].dims,w),ke("skip",e[1].dataType,e[1].dims,w),ke("gamma",e[2].dataType,e[2].dims,w)];d&&x.push(ke("beta",e[3].dataType,e[3].dims,w)),u&&x.push(ke("bias",e[4].dataType,e[4].dims,w)),x.push(it("output",e[0].dataType,a,w)),f&&x.push(it("mean_output",1,p)),_&&x.push(it("inv_std_output",1,p)),y&&x.push(it("input_skip_bias_sum",e[0].dataType,a,w));let S=Ar(e[0].dataType),O=Ar(1,w);return` + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${n.length>0?n:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:a},...ct(i,l)]})}},pw=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},H0=(e,r)=>{let t=[],s=[],n=[],o=pw(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");ZM(e.inputs,r,o,t,s,n),e.compute(dw(e.inputs[0],r,o,t,s,n),{inputs:[0]})},q0=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,o=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return jt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:o,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:c})}}),mw,hw,Q0,HT=Ve(()=>{gt(),Ct(),St(),mw=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let n=r.dims[r.dims.length-1],o=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==n)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},hw=(e,r,t,s)=>{let n=r.simplified,o=e[0].dims,i=we.size(o),a=o,l=i,c=o.slice(-1)[0],p=s?o.slice(0,-1).concat(1):[],d=!n&&e.length>3,u=e.length>4,f=s&&t>1,_=s&&t>2,y=t>3,k=64,w=ur(c),v=[{type:12,data:l},{type:12,data:w},{type:12,data:c},{type:1,data:r.epsilon}],I=b=>{let E=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[ke("x",e[0].dataType,e[0].dims,w),ke("skip",e[1].dataType,e[1].dims,w),ke("gamma",e[2].dataType,e[2].dims,w)];d&&x.push(ke("beta",e[3].dataType,e[3].dims,w)),u&&x.push(ke("bias",e[4].dataType,e[4].dims,w)),x.push(it("output",e[0].dataType,a,w)),f&&x.push(it("mean_output",1,p)),_&&x.push(it("inv_std_output",1,p)),y&&x.push(it("input_skip_bias_sum",e[0].dataType,a,w));let S=Ar(e[0].dataType),O=Ar(1,w);return` ${b.registerUniforms(E).declareVariables(...x)} var sum_shared : array<${O}, ${k}>; @@ -2676,7 +2676,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${S}(inv_std_dev) * gamma[offset1d + i] ${d?"+ beta[offset1d + i]":""}; } - }`},T=[{dims:a,dataType:e[0].dataType}];return t>1&&T.push({dims:p,dataType:1}),t>2&&T.push({dims:p,dataType:1}),t>3&&T.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${y}`,inputDependencies:e.map((b,E)=>"type")},getShaderSource:I,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:v})}},q0=(e,r)=>{pw(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(mw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),hw,Uo,_w,Vc,fw,gw,Q0,X0,qT=Ve(()=>{gt(),Ct(),mr(),St(),hw=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Uo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},_w=(e,r)=>{if(e.length>1){let t=Uo(e,1),s=Uo(e,2),n=Uo(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),jt({starts:t,ends:s,axes:n})}else return r},Vc=(e,r,t,s,n)=>{let o=e;return e<0&&(o+=t[s[r]]),n[r]<0?Math.max(0,Math.min(o,t[s[r]]-1)):Math.max(0,Math.min(o,t[s[r]]))},fw=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + }`},T=[{dims:a,dataType:e[0].dataType}];return t>1&&T.push({dims:p,dataType:1}),t>2&&T.push({dims:p,dataType:1}),t>3&&T.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${y}`,inputDependencies:e.map((b,E)=>"type")},getShaderSource:I,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:v})}},Q0=(e,r)=>{mw(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(hw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),_w,Uo,fw,Uc,gw,Mw,X0,J0,qT=Ve(()=>{gt(),Ct(),mr(),St(),_w=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},Uo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},fw=(e,r)=>{if(e.length>1){let t=Uo(e,1),s=Uo(e,2),n=Uo(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),jt({starts:t,ends:s,axes:n})}else return r},Uc=(e,r,t,s,n)=>{let o=e;return e<0&&(o+=t[s[r]]),n[r]<0?Math.max(0,Math.min(o,t[s[r]]-1)):Math.max(0,Math.min(o,t[s[r]]))},gw=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${t.length}; i >= 0; i--) { @@ -2694,15 +2694,15 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; - }`,gw=(e,r)=>{let t=e[0].dims,s=we.size(t),n=r.axes.length>0?we.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],o=Uo(e,4);o.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(n.length).fill(1));let i=r.starts.map((w,v)=>Vc(w,v,t,n,o)),a=r.ends.map((w,v)=>Vc(w,v,t,n,o));if(n.length!==i.length||n.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==t.length)for(let w=0;wMath.sign(w));o.forEach((w,v,I)=>{if(w<0){let T=(a[v]-i[v])/w,b=i[v],E=b+T*o[v];i[v]=E,a[v]=b,I[v]=-w}});let c=t.slice(0);n.forEach((w,v)=>{c[w]=Math.ceil((a[w]-i[w])/o[w])});let p={dims:c,dataType:e[0].dataType},d=it("output",e[0].dataType,c.length),u=ke("input",e[0].dataType,e[0].dims.length),f=we.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:o.length}],y=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:o},...ct(e[0].dims,c)],k=w=>` + }`,Mw=(e,r)=>{let t=e[0].dims,s=we.size(t),n=r.axes.length>0?we.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],o=Uo(e,4);o.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(n.length).fill(1));let i=r.starts.map((w,v)=>Uc(w,v,t,n,o)),a=r.ends.map((w,v)=>Uc(w,v,t,n,o));if(n.length!==i.length||n.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==t.length)for(let w=0;wMath.sign(w));o.forEach((w,v,I)=>{if(w<0){let T=(a[v]-i[v])/w,b=i[v],E=b+T*o[v];i[v]=E,a[v]=b,I[v]=-w}});let c=t.slice(0);n.forEach((w,v)=>{c[w]=Math.ceil((a[w]-i[w])/o[w])});let p={dims:c,dataType:e[0].dataType},d=it("output",e[0].dataType,c.length),u=ke("input",e[0].dataType,e[0].dims.length),f=we.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:o.length}],y=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:o},...ct(e[0].dims,c)],k=w=>` ${w.registerUniforms(_).declareVariables(u,d)} - ${fw(u,d,t)} + ${gw(u,d,t)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${d.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:y})}},Q0=(e,r)=>{hw(e.inputs,r);let t=_w(e.inputs,r);e.compute(gw(e.inputs,t),{inputs:[0]})},X0=e=>{let r=e.starts,t=e.ends,s=e.axes;return jt({starts:r,ends:t,axes:s})}}),Mw,ww,J0,Y0,QT=Ve(()=>{gt(),Ct(),mr(),cn(),St(),Mw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ww=(e,r)=>{let t=e.inputs[0],s=t.dims,n=we.size(s),o=s.length,i=we.normalizeAxis(r.axis,o),a=iS),c[i]=o-1,c[o-1]=i,l=e.compute(es(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[o-1],u=n/d,f=ur(d),_=d/f,y=64;u===1&&(y=256);let k=(x,S)=>S===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:S===2?`max(${x}.x, ${x}.y)`:S===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,w=ke("x",l.dataType,l.dims,f),v=it("result",l.dataType,l.dims,f),I=w.type.value,T=Ar(l.dataType)==="f32"?`var threadMax = ${I}(-3.402823e+38f);`:`var threadMax = ${I}(-65504.0h);`,b=x=>` + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:y})}},X0=(e,r)=>{_w(e.inputs,r);let t=fw(e.inputs,r);e.compute(Mw(e.inputs,t),{inputs:[0]})},J0=e=>{let r=e.starts,t=e.ends,s=e.axes;return jt({starts:r,ends:t,axes:s})}}),ww,bw,Y0,Z0,QT=Ve(()=>{gt(),Ct(),mr(),cn(),St(),ww=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},bw=(e,r)=>{let t=e.inputs[0],s=t.dims,n=we.size(s),o=s.length,i=we.normalizeAxis(r.axis,o),a=iS),c[i]=o-1,c[o-1]=i,l=e.compute(es(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[o-1],u=n/d,f=ur(d),_=d/f,y=64;u===1&&(y=256);let k=(x,S)=>S===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:S===2?`max(${x}.x, ${x}.y)`:S===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,w=ke("x",l.dataType,l.dims,f),v=it("result",l.dataType,l.dims,f),I=w.type.value,T=Ar(l.dataType)==="f32"?`var threadMax = ${I}(-3.402823e+38f);`:`var threadMax = ${I}(-65504.0h);`,b=x=>` var rowMaxShared : ${I}; var rowSumShared : ${I}; var threadShared : array<${I}, ${y}>; @@ -2774,7 +2774,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } - }`,E=e.compute({name:"Softmax",shaderCache:{hint:`${f};${y}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:b},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(es(E,c),{inputs:[E]})},J0=(e,r)=>{Mw(e.inputs),ww(e,r)},Y0=e=>jt({axis:e.axis})}),Uc,bw,yw,vw,Z0,XT=Ve(()=>{gt(),Ct(),St(),Uc=e=>Array.from(e.getBigInt64Array(),Number),bw=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(Uc(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")},yw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Uc(e[1]),n=yw(t,s),o=we.size(n),i=e[0].dataType,a=ke("input",i,t.length),l=it("output",i,n.length),c=p=>` + }`,E=e.compute({name:"Softmax",shaderCache:{hint:`${f};${y}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:b},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(es(E,c),{inputs:[E]})},Y0=(e,r)=>{ww(e.inputs),bw(e,r)},Z0=e=>jt({axis:e.axis})}),Wc,yw,vw,xw,ev,XT=Ve(()=>{gt(),Ct(),St(),Wc=e=>Array.from(e.getBigInt64Array(),Number),yw=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Wc(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")},vw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Wc(e[1]),n=vw(t,s),o=we.size(n),i=e[0].dataType,a=ke("input",i,t.length),l=it("output",i,n.length),c=p=>` const inputShape = ${a.indices(...t)}; ${p.registerUniform("output_size","u32").declareVariables(a,l)} ${p.mainStart()} @@ -2788,7 +2788,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${a.indicesSet("input_indices","i","input_dim_value")} } ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...ct(e[0].dims,n)]}),getShaderSource:c}},Z0=e=>{bw(e.inputs),e.compute(vw(e.inputs),{inputs:[0]})}}),xw,Tw,ev,JT=Ve(()=>{gt(),Ct(),St(),xw=(e,r,t,s,n)=>{let o=it("output_data",n,t.length,4),i=ke("a_data",r[1].dataType,r[1].dims.length,4),a=ke("b_data",r[2].dataType,r[2].dims.length,4),l=ke("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,f)=>`select(${u}, ${d}, ${f})`;if(!s)c=o.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,f,_="")=>{let y=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,w=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...ct(e[0].dims,n)]}),getShaderSource:c}},ev=e=>{yw(e.inputs),e.compute(xw(e.inputs),{inputs:[0]})}}),Tw,Ew,tv,JT=Ve(()=>{gt(),Ct(),St(),Tw=(e,r,t,s,n)=>{let o=it("output_data",n,t.length,4),i=ke("a_data",r[1].dataType,r[1].dims.length,4),a=ke("b_data",r[2].dataType,r[2].dims.length,4),l=ke("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,f)=>`select(${u}, ${d}, ${f})`;if(!s)c=o.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,f,_="")=>{let y=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,w=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` let output_indices${f} = ${o.offsetToIndices(`global_idx * 4u + ${f}u`)}; let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,o)}; let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,o)}; @@ -2816,10 +2816,10 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${c} - }`},Tw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,n=e[1].dataType,o=!(we.areEqual(r,t)&&we.areEqual(t,s)),i=r,a=we.size(r);if(o){let c=lo.calcShape(lo.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=we.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>xw(c,e,i,o,n),getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ct(s,r,t,i)]})}},ev=e=>{e.compute(Tw(e.inputs))}}),tv,YT=Ve(()=>{pT(),Iu(),mT(),hT(),_T(),fT(),gT(),vT(),TT(),ET(),PT(),CT(),ST(),IT(),$T(),kT(),AT(),FT(),OT(),DT(),LT(),zT(),BT(),RT(),NT(),b0(),jT(),VT(),UT(),WT(),GT(),Su(),KT(),E0(),HT(),qT(),QT(),x0(),XT(),cn(),$u(),JT(),tv=new Map([["Abs",[qb]],["Acos",[Qb]],["Acosh",[Xb]],["Add",[$y]],["ArgMax",[Wb,su]],["ArgMin",[Ub,su]],["Asin",[Jb]],["Asinh",[Yb]],["Atan",[Zb]],["Atanh",[ey]],["Attention",[Gb]],["AveragePool",[O0,F0]],["BatchNormalization",[Kb]],["BiasAdd",[Hb]],["BiasSplitGelu",[Iy]],["Cast",[ry,ty]],["Ceil",[ny]],["Clip",[sy]],["Concat",[Ny,jy]],["Conv",[cu,lu]],["ConvTranspose",[Jy,Xy]],["Cos",[oy]],["Cosh",[ay]],["CumSum",[Yy,Zy]],["DepthToSpace",[e0,t0]],["DequantizeLinear",[j0,V0]],["Div",[ky]],["Einsum",[r0,s0]],["Elu",[iy,qo]],["Equal",[Ay]],["Erf",[ly]],["Exp",[cy]],["Expand",[n0]],["FastGelu",[o0]],["Floor",[uy]],["FusedConv",[cu,lu]],["Gather",[i0,a0]],["GatherElements",[m0,p0]],["GatherBlockQuantized",[u0,d0]],["GatherND",[l0,c0]],["Gelu",[dy]],["Gemm",[_0,h0]],["GlobalAveragePool",[L0,D0]],["GlobalMaxPool",[N0,R0]],["Greater",[Ly]],["GreaterOrEqual",[By]],["GridSample",[f0,g0]],["GroupQueryAttention",[P0]],["HardSigmoid",[wy,My]],["InstanceNormalization",[C0]],["LayerNormalization",[S0]],["LeakyRelu",[py,qo]],["Less",[zy]],["LessOrEqual",[Ry]],["Log",[Cy]],["MatMul",[I0]],["MatMulNBits",[$0,k0]],["MaxPool",[z0,B0]],["Mul",[Fy]],["MultiHeadAttention",[w0,M0]],["Neg",[hy]],["Not",[my]],["Pad",[A0]],["Pow",[Oy]],["QuickGelu",[Sy,qo]],["Range",[U0]],["Reciprocal",[_y]],["ReduceMin",[Bb]],["ReduceMean",[Fb]],["ReduceMax",[zb]],["ReduceSum",[Nb]],["ReduceProd",[Rb]],["ReduceL1",[Ob]],["ReduceL2",[Db]],["ReduceLogSum",[Vb]],["ReduceLogSumExp",[Lb]],["ReduceSumSquare",[jb]],["Relu",[fy]],["Resize",[K0,H0]],["RotaryEmbedding",[T0]],["ScatterND",[G0,W0]],["Sigmoid",[gy]],["Sin",[by]],["Sinh",[yy]],["Slice",[Q0,X0]],["SkipLayerNormalization",[q0]],["Split",[y0,v0]],["Sqrt",[vy]],["Softmax",[J0,Y0]],["Sub",[Dy]],["Tan",[xy]],["Tanh",[Ty]],["ThresholdedRelu",[Py,qo]],["Tile",[Z0]],["Transpose",[yb,vb]],["Where",[ev]]])}),rv,ZT=Ve(()=>{Es(),Hs(),St(),rv=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,n){Ts(e.programInfo.name);let o=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let c of r)a.push({binding:a.length,resource:{buffer:c.buffer}});for(let c of t)a.push({binding:a.length,resource:{buffer:c.buffer}});n&&a.push({binding:a.length,resource:n});let l=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),us(e.programInfo.name)}dispose(){}build(e,r){Ts(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let n=bb(r,this.backend.device.limits),o=e.getShaderSource(n),i=`${s.join(` + }`},Ew=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,n=e[1].dataType,o=!(we.areEqual(r,t)&&we.areEqual(t,s)),i=r,a=we.size(r);if(o){let c=lo.calcShape(lo.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=we.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Tw(c,e,i,o,n),getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ct(s,r,t,i)]})}},tv=e=>{e.compute(Ew(e.inputs))}}),rv,YT=Ve(()=>{pT(),$u(),mT(),hT(),_T(),fT(),gT(),vT(),TT(),ET(),PT(),CT(),ST(),IT(),$T(),kT(),AT(),FT(),OT(),DT(),LT(),zT(),BT(),RT(),NT(),y0(),jT(),VT(),UT(),WT(),GT(),Iu(),KT(),P0(),HT(),qT(),QT(),T0(),XT(),cn(),ku(),JT(),rv=new Map([["Abs",[Qb]],["Acos",[Xb]],["Acosh",[Jb]],["Add",[ky]],["ArgMax",[Gb,nu]],["ArgMin",[Wb,nu]],["Asin",[Yb]],["Asinh",[Zb]],["Atan",[ey]],["Atanh",[ty]],["Attention",[Kb]],["AveragePool",[D0,O0]],["BatchNormalization",[Hb]],["BiasAdd",[qb]],["BiasSplitGelu",[$y]],["Cast",[sy,ry]],["Ceil",[oy]],["Clip",[ny]],["Concat",[jy,Vy]],["Conv",[uu,cu]],["ConvTranspose",[Yy,Jy]],["Cos",[ay]],["Cosh",[iy]],["CumSum",[Zy,e0]],["DepthToSpace",[t0,r0]],["DequantizeLinear",[V0,U0]],["Div",[Ay]],["Einsum",[s0,n0]],["Elu",[ly,qo]],["Equal",[Fy]],["Erf",[cy]],["Exp",[uy]],["Expand",[o0]],["FastGelu",[a0]],["Floor",[dy]],["FusedConv",[uu,cu]],["Gather",[l0,i0]],["GatherElements",[h0,m0]],["GatherBlockQuantized",[d0,p0]],["GatherND",[c0,u0]],["Gelu",[py]],["Gemm",[f0,_0]],["GlobalAveragePool",[z0,L0]],["GlobalMaxPool",[j0,N0]],["Greater",[zy]],["GreaterOrEqual",[Ry]],["GridSample",[g0,M0]],["GroupQueryAttention",[C0]],["HardSigmoid",[by,wy]],["InstanceNormalization",[S0]],["LayerNormalization",[I0]],["LeakyRelu",[my,qo]],["Less",[By]],["LessOrEqual",[Ny]],["Log",[Sy]],["MatMul",[$0]],["MatMulNBits",[k0,A0]],["MaxPool",[B0,R0]],["Mul",[Oy]],["MultiHeadAttention",[b0,w0]],["Neg",[_y]],["Not",[hy]],["Pad",[F0]],["Pow",[Dy]],["QuickGelu",[Iy,qo]],["Range",[W0]],["Reciprocal",[fy]],["ReduceMin",[Rb]],["ReduceMean",[Ob]],["ReduceMax",[Bb]],["ReduceSum",[jb]],["ReduceProd",[Nb]],["ReduceL1",[Db]],["ReduceL2",[Lb]],["ReduceLogSum",[Ub]],["ReduceLogSumExp",[zb]],["ReduceSumSquare",[Vb]],["Relu",[gy]],["Resize",[H0,q0]],["RotaryEmbedding",[E0]],["ScatterND",[K0,G0]],["Sigmoid",[My]],["Sin",[yy]],["Sinh",[vy]],["Slice",[X0,J0]],["SkipLayerNormalization",[Q0]],["Split",[v0,x0]],["Sqrt",[xy]],["Softmax",[Y0,Z0]],["Sub",[Ly]],["Tan",[Ty]],["Tanh",[Ey]],["ThresholdedRelu",[Cy,qo]],["Tile",[ev]],["Transpose",[vb,xb]],["Where",[tv]]])}),sv,ZT=Ve(()=>{Es(),Hs(),St(),sv=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,n){Ts(e.programInfo.name);let o=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let c of r)a.push({binding:a.length,resource:{buffer:c.buffer}});for(let c of t)a.push({binding:a.length,resource:{buffer:c.buffer}});n&&a.push({binding:a.length,resource:n});let l=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),us(e.programInfo.name)}dispose(){}build(e,r){Ts(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let n=yb(r,this.backend.device.limits),o=e.getShaderSource(n),i=`${s.join(` `)} ${n.additionalImplementations} -${o}`,a=t.createShaderModule({code:i,label:e.name});Dt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return us(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:n.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,n=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=n&&t<=n&&s<=n)return[r,t,s];let o=r*t*s,i=Math.ceil(Math.sqrt(o));if(i>n){if(i=Math.ceil(Math.cbrt(o)),i>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),sv={};uo(sv,{WebGpuBackend:()=>nv});var Ew,Pw,Cw,nv,e1=Ve(()=>{Es(),gt(),Hs(),_b(),uT(),YT(),ZT(),Ew=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{let s=e.name;return e.shaderCache?.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${Ew(r,e.shaderCache?.inputDependencies??new Array(r.length).fill("dims"))}`,s},Cw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},nv=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},n=o=>r.features.has(o)&&t.push(o)&&!0;n("chromium-experimental-timestamp-query-inside-passes")||n("timestamp-query"),n("shader-f16"),n("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Cw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Mb(this),this.programManager=new rv(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Tu(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ts(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=u);let _=Number(u-this.queryTimeBase),y=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(y))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(k=>({dims:k.dims,dataType:Ks(k.dataType)})),outputsMetadata:d.map(k=>({dims:k.dims,dataType:Ks(k.dataType)})),kernelId:o,kernelType:a,kernelName:l,programName:c,startTime:_,endTime:y});else{let k="";p.forEach((v,I)=>{k+=`input[${I}]: [${v.dims}] | ${Ks(v.dataType)}, `});let w="";d.forEach((v,I)=>{w+=`output[${I}]: [${v.dims}] | ${Ks(v.dataType)}, `}),console.log(`[profiling] kernel "${o}|${a}|${l}|${c}" ${k}${w}execution time: ${y-_} ns`)}Yo("GPU",`${c}::${u}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),us()}run(e,r,t,s,n,o){Ts(e.name);let i=[];for(let v=0;vI):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let v=0;v=o)throw new Error(`Invalid output index: ${p[v]}`);if(p[v]===-3)continue;let I=p[v]===-1,T=p[v]===-2,b=I||T?n(a[v].dataType,a[v].dims):s(p[v],a[v].dataType,a[v].dims);if(d.push(b),b.data===0)continue;let E=this.gpuDataManager.get(b.data);if(!E)throw new Error(`no GPU data for output: ${b.data}`);if(I&&this.temporaryData.push(E),T){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(E)}u.push(E)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return us(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(c){let v=0,I=[];c.forEach(x=>{let S=typeof x.data=="number"?[x.data]:x.data;if(S.length===0)return;let O=x.type===10?2:4,F,H;x.type===10?(H=S.length>4?16:S.length>2?8:S.length*O,F=S.length>4?16:O*S.length):(H=S.length<=2?S.length*O:16,F=16),v=Math.ceil(v/H)*H,I.push(v);let W=x.type===10?8:4;v+=S.length>4?Math.ceil(S.length/W)*F:S.length*O});let T=16;v=Math.ceil(v/T)*T;let b=new ArrayBuffer(v);c.forEach((x,S)=>{let O=I[S],F=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(b,O,F.length).set(F);else if(x.type===12)new Uint32Array(b,O,F.length).set(F);else if(x.type===10)new Uint16Array(b,O,F.length).set(F);else if(x.type===1)new Float32Array(b,O,F.length).set(F);else throw new Error(`Unsupported uniform type: ${Ks(x.type)}`)});let E=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(E.buffer,0,b,0,v),this.gpuDataManager.release(E.id),f={offset:0,size:v,buffer:E.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),y=_[1]===1&&_[2]===1,k=Pw(e,r,y),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(k,w),Dt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),c&&w.uniformVariablesInfo){if(c.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${c.length} in program "${w.programInfo.name}".`);for(let v=0;v`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(w,i,u,_,f),us(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let n=tv.get(e);if(!n)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:s,kernelEntry:n[0],attributes:[n[1],t]};this.kernels.set(r,o)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let n=s.kernelType,o=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Dt("info",()=>`[WebGPU] Start to run kernel "[${n}] ${o}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${n}] ${o}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${n}] ${o}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let n=this.sessionExternalDataMapping.get(e);n||(n=new Map,this.sessionExternalDataMapping.set(e,n));let o=n.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,o);return n.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await eu(this,e,r);return Eu(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Dt("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(){Dt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),ov={};uo(ov,{init:()=>av});var ni,Sw,av,t1=Ve(()=>{gt(),Hs(),Ct(),cT(),ni=class iv{constructor(r,t,s,n){this.module=r,this.dataType=t,this.data=s,this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(we.size(r)!==we.size(this.dims))throw new Error("Invalid new shape");return new iv(this.module,this.dataType,this.data,r)}},Sw=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,n=t/e.PTR_SIZE,o=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*n++,o));let i=Number(e.getValue(s*n++,o));this.outputCount=Number(e.getValue(s*n++,o)),this.customDataOffset=Number(e.getValue(s*n++,"*")),this.customDataSize=Number(e.getValue(s*n++,o));let a=[];for(let l=0;ltypeof i=="number"?this.inputs[i]:i)??this.inputs,s=r?.outputs??[],n=(i,a,l)=>new ni(this.module,a,this.output(i,l),l),o=(i,a)=>{let l=Sn(i,a);if(!l)throw new Error(`Unsupported data type: ${i}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ni(this.module,i,c,a)};return this.backend.run(e,t,s,n,o,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,n=s===4?"i32":"i64",o=this.module.stackAlloc((1+r.length)*s);this.module.setValue(o,r.length,n);for(let i=0;i{let n=r.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=(e1(),Jo(sv)).WebGpuBackend,i=new o;await i.initialize(t,s),n("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,c,p=!1)=>{if(p)Dt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(c)}`),i.memcpy(Number(a),Number(l));else{Dt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(c));i.upload(Number(l),d)}},async(a,l,c)=>{Dt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${c}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(a,l,c)=>i.createKernel(a,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,c,p)=>{Dt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${a}, contextDataOffset=${l}`);let d=new Sw(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let o=new gb(t);n("webnn",[o,()=>o.reserveTensorId(),i=>o.releaseTensorId(i),async(i,a,l,c,p)=>o.ensureTensor(i,a,l,c,p),(i,a)=>{o.uploadTensor(i,a)},async(i,a)=>o.downloadTensor(i,a)])}}}),Iw,Lu,zu,on,$w,Wc,gi,Bu,Ru,Gc,Nu,ju,Vu,lv=Ve(()=>{aT(),iT(),gt(),Fn(),wu(),db(),Iw=(e,r)=>{Qt()._OrtInit(e,r)!==0&&Gt("Can't initialize onnxruntime.")},Lu=async e=>{Iw(e.wasm.numThreads,pi(e.logLevel))},zu=async(e,r)=>{Qt().asyncInit?.();{let t=(t1(),Jo(ov)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:o}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",Qt(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Qt(),e)}}},on=new Map,$w=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,n,n+s)!==0&&Gt("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(r.getValue(n,o)),Number(r.getValue(n+s,o))]}finally{r.stackRestore(t)}},Wc=(e,r)=>{let t=Qt(),s=t.stackSave(),n=0;try{let o=t.PTR_SIZE,i=t.stackAlloc(2*o);t._OrtGetInputOutputMetadata(e,r,i,i+o)!==0&&Gt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));n=Number(t.getValue(i+o,"*"));let l=t.HEAP32[n/4];if(l===0)return[a,0];let c=t.HEAPU32[n/4+1],p=[];for(let d=0;d{let r=Qt(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},Bu=async(e,r)=>{let t,s,n=Qt();Array.isArray(e)?[t,s]=e:e.buffer===n.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=gi(e);let o=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await ub(r),r?.externalData&&n.mountExternalData){let T=[];for(let b of r.externalData){let E=typeof b=="string"?b:b.path;T.push(xu(typeof b=="string"?b:b.data).then(x=>{n.mountExternalData(E,x)}))}await Promise.all(T)}for(let T of r?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let b=T,E=b?.context,x=b?.gpuDevice,S=b?.deviceType,O=b?.powerPreference;E?n.currentContext=E:x?n.currentContext=await n.webnnCreateMLContext(x):n.currentContext=await n.webnnCreateMLContext({deviceType:S,powerPreference:O})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(t,s,i),n.webgpuOnCreateSession?.(o),o===0&&Gt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,u]=$w(o),f=!!r?.enableGraphCapture,_=[],y=[],k=[],w=[],v=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor")&&(a=n._OrtCreateBinding(o),a===0&&Gt("Can't create IO binding."),I={handle:a,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(T=>Yc(T))}),on.set(o,[o,c,p,I,f,!1]),[o,_,y,k,w]}catch(d){throw c.forEach(u=>n._OrtFree(u)),p.forEach(u=>n._OrtFree(u)),a!==0&&n._OrtReleaseBinding(a)!==0&&Gt("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Gt("Can't release session."),d}finally{n._free(t),i!==0&&n._OrtReleaseSessionOptions(i)!==0&&Gt("Can't release session options."),l.forEach(d=>n._free(d)),n.unmountExternalData?.()}},Ru=e=>{let r=Qt(),t=on.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,o,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Gt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Gt("Can't release IO binding.")),r.jsepOnReleaseSession?.(e),r.webnnOnReleaseSession?.(e),r.webgpuOnReleaseSession?.(e),n.forEach(l=>r._OrtFree(l)),o.forEach(l=>r._OrtFree(l)),r._OrtReleaseSession(s)!==0&&Gt("Can't release session."),on.delete(e)},Gc=async(e,r,t,s,n,o,i=!1)=>{if(!e){r.push(0);return}let a=Qt(),l=a.PTR_SIZE,c=e[0],p=e[1],d=e[3],u=d,f,_;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;_=Sn(no(c),p);{let v=a.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=v(s,o,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=Sn(no(c),p);let v=a.webnnRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=v(s,w,no(c),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let v=0;va.setValue(k+I*l,v,l===4?"i32":"i64"));let w=a._OrtCreateTensor(no(c),f,_,k,p.length,Yc(u));w===0&&Gt(`Can't create tensor for input/output. session=${s}, index=${o}.`),r.push(w)}finally{a.stackRestore(y)}},Nu=async(e,r,t,s,n,o)=>{let i=Qt(),a=i.PTR_SIZE,l=on.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],d=l[2],u=l[3],f=l[4],_=l[5],y=r.length,k=s.length,w=0,v=[],I=[],T=[],b=[],E=i.stackSave(),x=i.stackAlloc(y*a),S=i.stackAlloc(y*a),O=i.stackAlloc(k*a),F=i.stackAlloc(k*a);try{[w,v]=cb(o);for(let B=0;BAe*Ie,1);ne=Ks(oe);let he=u?.outputPreferredLocations[s[B]];if(ne==="string"){if(he==="gpu-buffer"||he==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ae=[];for(let Ie=0;Ie0){let Ae=i.jsepGetBuffer;if(!Ae)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ie=Ae(le),je=Sn(oe,te);if(je===void 0||!yu(ne))throw new Error(`Unsupported data type: ${ne}`);re=!0,W.push([ne,D,{gpuBuffer:Ie,download:i.jsepCreateDownloader(Ie,je,ne),dispose:()=>{i._OrtReleaseTensor(Y)!==0&&Gt("Can't release tensor.")}},"gpu-buffer"])}else if(he==="ml-tensor"&&te>0){let Ae=i.webnnEnsureTensor,Ie=i.webnnIsInt64Supported;if(!Ae||!Ie)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Sn(oe,te)===void 0||!vu(ne))throw new Error(`Unsupported data type: ${ne}`);if(ne==="int64"&&!Ie(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let je=await Ae(e,le,oe,D,!1);re=!0,W.push([ne,D,{mlTensor:je,download:i.webnnCreateMLTensorDownloader(le,ne),dispose:()=>{i.webnnReleaseTensorId(le),i._OrtReleaseTensor(Y)}},"ml-tensor"])}else{let Ae=bu(ne),Ie=new Ae(te);new Uint8Array(Ie.buffer,Ie.byteOffset,Ie.byteLength).set(i.HEAPU8.subarray(le,le+Ie.byteLength)),W.push([ne,D,Ie,"cpu"])}}finally{i.stackRestore(X),ne==="string"&&le&&i._free(le),re||i._OrtReleaseTensor(Y),i.webnnOnRunEnd?.(c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Gt("Can't clear bound outputs."),on.set(e,[c,p,d,u,f,!1])),W}finally{i.stackRestore(E),I.forEach(H=>i._OrtReleaseTensor(H)),T.forEach(H=>i._OrtReleaseTensor(H)),b.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),v.forEach(H=>i._free(H))}},ju=e=>{let r=Qt(),t=on.get(e);if(!t)throw new Error("invalid session id");let s=t[0],n=r._OrtEndProfiling(s);n===0&&Gt("Can't get an profile file name."),r._OrtFree(n)},Vu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),an,as,ro,Wo,Go,oi,Kc,ai,Tn,En,kw,cv,uv,dv,pv,mv,hv,_v,fv=Ve(()=>{Es(),lv(),Fn(),gu(),an=()=>!!Jt.wasm.proxy&&typeof document<"u",ro=!1,Wo=!1,Go=!1,ai=new Map,Tn=(e,r)=>{let t=ai.get(e);t?t.push(r):ai.set(e,[r])},En=()=>{if(ro||!Wo||Go||!as)throw new Error("worker not ready")},kw=e=>{switch(e.data.type){case"init-wasm":ro=!1,e.data.err?(Go=!0,Kc[1](e.data.err)):(Wo=!0,Kc[0]()),oi&&(URL.revokeObjectURL(oi),oi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=ai.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},cv=async()=>{if(!Wo){if(ro)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(ro=!0,an())return new Promise((e,r)=>{as?.terminate(),ib().then(([t,s])=>{try{as=s,as.onerror=o=>r(o),as.onmessage=kw,Kc=[e,r];let n={type:"init-wasm",in:Jt};!n.in.wasm.wasmPaths&&(t||Jc)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href}),as.postMessage(n),oi=t}catch(n){r(n)}},r)});try{await Mu(Jt.wasm),await Lu(Jt),Wo=!0}catch(e){throw Go=!0,e}finally{ro=!1}}},uv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Jt}};as.postMessage(s)});await zu(Jt,e)},dv=async e=>an()?(En(),new Promise((r,t)=>{Tn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};as.postMessage(s,[e.buffer])})):gi(e),pv=async(e,r)=>{if(an()){if(r?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return En(),new Promise((t,s)=>{Tn("create",[t,s]);let n={type:"create",in:{model:e,options:{...r}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),as.postMessage(n,o)})}else return Bu(e,r)},mv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("release",[r,t]);let s={type:"release",in:e};as.postMessage(s)});Ru(e)},hv=async(e,r,t,s,n,o)=>{if(an()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return En(),new Promise((i,a)=>{Tn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:o}};as.postMessage(c,Vu(l))})}else return Nu(e,r,t,s,n,o)},_v=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};as.postMessage(s)});ju(e)}}),Hc,Aw,gv,r1=Ve(()=>{Es(),fv(),gt(),fu(),db(),Hc=(e,r)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Aw=e=>{switch(e[3]){case"cpu":return new ys(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!yu(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:n}=e[2];return ys.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let r=e[0];if(!vu(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:n}=e[2];return ys.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},gv=class{async fetchModelAndCopyToWasmMemory(e){return dv(await xu(e))}async loadModel(e,r){Ts();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await pv(t,r),us()}async dispose(){return mv(this.sessionId)}async run(e,r,t){Ts();let s=[],n=[];Object.entries(e).forEach(d=>{let u=d[0],f=d[1],_=this.inputNames.indexOf(u);if(_===-1)throw new Error(`invalid input '${u}'`);s.push(f),n.push(_)});let o=[],i=[];Object.entries(r).forEach(d=>{let u=d[0],f=d[1],_=this.outputNames.indexOf(u);if(_===-1)throw new Error(`invalid output '${u}'`);o.push(f),i.push(_)});let a=s.map((d,u)=>Hc(d,()=>`input "${this.inputNames[n[u]]}"`)),l=o.map((d,u)=>d?Hc(d,()=>`output "${this.outputNames[i[u]]}"`):null),c=await hv(this.sessionId,n,a,i,l,t),p={};for(let d=0;dpu,initializeFlags:()=>du,wasmBackend:()=>wv});var du,pu,wv,s1=Ve(()=>{Es(),fv(),r1(),du=()=>{(typeof Jt.wasm.initTimeout!="number"||Jt.wasm.initTimeout<0)&&(Jt.wasm.initTimeout=0);let e=Jt.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.`),Jt.wasm.simd=!1),typeof Jt.wasm.proxy!="boolean"&&(Jt.wasm.proxy=!1),typeof Jt.wasm.trace!="boolean"&&(Jt.wasm.trace=!1),typeof Jt.wasm.numThreads!="number"||!Number.isInteger(Jt.wasm.numThreads)||Jt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Jt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Ux("node:os").cpus().length:navigator.hardwareConcurrency;Jt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},pu=class{async init(e){du(),await cv(),await uv(e)}async createInferenceSessionHandler(e,r){let t=new gv;return await t.loadModel(e,r),t}},wv=new pu});Es();Es();Es();var n1="1.22.0-dev.20250409-89f8206ba4",o1=tb;{let e=(s1(),Jo(Mv)).wasmBackend;In("webgpu",e,5),In("webnn",e,5),In("cpu",e,10),In("wasm",e,10)}Object.defineProperty(Jt.versions,"web",{value:n1,enumerable:!0});var a1=Object.freeze({__proto__:null,get InferenceSession(){return _u},get TRACE(){return Yo},get TRACE_FUNC_BEGIN(){return Ts},get TRACE_FUNC_END(){return us},get Tensor(){return ys},default:o1,get env(){return Jt},get registerBackend(){return In}}),qc={},i1={"onnxruntime-common":(e=>{e.exports=Rx}),"onnxruntime-web":(e=>{e.exports=a1}),"?2ce3":(()=>{}),"?7992":(()=>{}),"?5af5":(()=>{}),"?2b25":(()=>{}),"?db59":(()=>{}),"?383f":(()=>{}),"?fa4b":(()=>{}),"./node_modules/@huggingface/jinja/dist/index.js":((e,r,t)=>{t.r(r),t.d(r,{Environment:()=>ot,Interpreter:()=>gr,Template:()=>Ss,parse:()=>Ae,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),n=class{constructor(C,q){this.value=C,this.type=q}};function o(C){return/\w/.test(C)}function i(C){return/[0-9]/.test(C)}function a(C){return/\s/.test(C)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["~",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],c=new Map([["n",` +${o}`,a=t.createShaderModule({code:i,label:e.name});Dt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return us(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:n.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,n=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=n&&t<=n&&s<=n)return[r,t,s];let o=r*t*s,i=Math.ceil(Math.sqrt(o));if(i>n){if(i=Math.ceil(Math.cbrt(o)),i>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),nv={};uo(nv,{WebGpuBackend:()=>ov});var Pw,Cw,Sw,ov,e1=Ve(()=>{Es(),gt(),Hs(),fb(),uT(),YT(),ZT(),Pw=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{let s=e.name;return e.shaderCache?.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${Pw(r,e.shaderCache?.inputDependencies??new Array(r.length).fill("dims"))}`,s},Sw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ov=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},n=o=>r.features.has(o)&&t.push(o)&&!0;n("chromium-experimental-timestamp-query-inside-passes")||n("timestamp-query"),n("shader-f16"),n("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Sw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=wb(this),this.programManager=new sv(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Eu(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Ts(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=u);let _=Number(u-this.queryTimeBase),y=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(y))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(k=>({dims:k.dims,dataType:Ks(k.dataType)})),outputsMetadata:d.map(k=>({dims:k.dims,dataType:Ks(k.dataType)})),kernelId:o,kernelType:a,kernelName:l,programName:c,startTime:_,endTime:y});else{let k="";p.forEach((v,I)=>{k+=`input[${I}]: [${v.dims}] | ${Ks(v.dataType)}, `});let w="";d.forEach((v,I)=>{w+=`output[${I}]: [${v.dims}] | ${Ks(v.dataType)}, `}),console.log(`[profiling] kernel "${o}|${a}|${l}|${c}" ${k}${w}execution time: ${y-_} ns`)}Yo("GPU",`${c}::${u}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),us()}run(e,r,t,s,n,o){Ts(e.name);let i=[];for(let v=0;vI):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let v=0;v=o)throw new Error(`Invalid output index: ${p[v]}`);if(p[v]===-3)continue;let I=p[v]===-1,T=p[v]===-2,b=I||T?n(a[v].dataType,a[v].dims):s(p[v],a[v].dataType,a[v].dims);if(d.push(b),b.data===0)continue;let E=this.gpuDataManager.get(b.data);if(!E)throw new Error(`no GPU data for output: ${b.data}`);if(I&&this.temporaryData.push(E),T){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(E)}u.push(E)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return us(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(c){let v=0,I=[];c.forEach(x=>{let S=typeof x.data=="number"?[x.data]:x.data;if(S.length===0)return;let O=x.type===10?2:4,F,H;x.type===10?(H=S.length>4?16:S.length>2?8:S.length*O,F=S.length>4?16:O*S.length):(H=S.length<=2?S.length*O:16,F=16),v=Math.ceil(v/H)*H,I.push(v);let W=x.type===10?8:4;v+=S.length>4?Math.ceil(S.length/W)*F:S.length*O});let T=16;v=Math.ceil(v/T)*T;let b=new ArrayBuffer(v);c.forEach((x,S)=>{let O=I[S],F=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(b,O,F.length).set(F);else if(x.type===12)new Uint32Array(b,O,F.length).set(F);else if(x.type===10)new Uint16Array(b,O,F.length).set(F);else if(x.type===1)new Float32Array(b,O,F.length).set(F);else throw new Error(`Unsupported uniform type: ${Ks(x.type)}`)});let E=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(E.buffer,0,b,0,v),this.gpuDataManager.release(E.id),f={offset:0,size:v,buffer:E.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),y=_[1]===1&&_[2]===1,k=Cw(e,r,y),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(k,w),Dt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),c&&w.uniformVariablesInfo){if(c.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${c.length} in program "${w.programInfo.name}".`);for(let v=0;v`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(w,i,u,_,f),us(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let n=rv.get(e);if(!n)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:s,kernelEntry:n[0],attributes:[n[1],t]};this.kernels.set(r,o)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let n=s.kernelType,o=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Dt("info",()=>`[WebGPU] Start to run kernel "[${n}] ${o}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${n}] ${o}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${n}] ${o}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let n=this.sessionExternalDataMapping.get(e);n||(n=new Map,this.sessionExternalDataMapping.set(e,n));let o=n.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,o);return n.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await tu(this,e,r);return Pu(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Dt("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(){Dt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),av={};uo(av,{init:()=>iv});var ni,Iw,iv,t1=Ve(()=>{gt(),Hs(),Ct(),cT(),ni=class lv{constructor(r,t,s,n){this.module=r,this.dataType=t,this.data=s,this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=we.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(we.size(r)!==we.size(this.dims))throw new Error("Invalid new shape");return new lv(this.module,this.dataType,this.data,r)}},Iw=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,n=t/e.PTR_SIZE,o=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*n++,o));let i=Number(e.getValue(s*n++,o));this.outputCount=Number(e.getValue(s*n++,o)),this.customDataOffset=Number(e.getValue(s*n++,"*")),this.customDataSize=Number(e.getValue(s*n++,o));let a=[];for(let l=0;ltypeof i=="number"?this.inputs[i]:i)??this.inputs,s=r?.outputs??[],n=(i,a,l)=>new ni(this.module,a,this.output(i,l),l),o=(i,a)=>{let l=Sn(i,a);if(!l)throw new Error(`Unsupported data type: ${i}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ni(this.module,i,c,a)};return this.backend.run(e,t,s,n,o,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,n=s===4?"i32":"i64",o=this.module.stackAlloc((1+r.length)*s);this.module.setValue(o,r.length,n);for(let i=0;i{let n=r.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=(e1(),Jo(nv)).WebGpuBackend,i=new o;await i.initialize(t,s),n("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,c,p=!1)=>{if(p)Dt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(c)}`),i.memcpy(Number(a),Number(l));else{Dt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(c));i.upload(Number(l),d)}},async(a,l,c)=>{Dt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${c}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(a,l,c)=>i.createKernel(a,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,c,p)=>{Dt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${a}, contextDataOffset=${l}`);let d=new Iw(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let o=new Mb(t);n("webnn",[o,()=>o.reserveTensorId(),i=>o.releaseTensorId(i),async(i,a,l,c,p)=>o.ensureTensor(i,a,l,c,p),(i,a)=>{o.uploadTensor(i,a)},async(i,a)=>o.downloadTensor(i,a)])}}}),$w,zu,Bu,on,kw,Gc,gi,Ru,Nu,Kc,ju,Vu,Uu,cv=Ve(()=>{aT(),iT(),gt(),Fn(),bu(),pb(),$w=(e,r)=>{Qt()._OrtInit(e,r)!==0&&Gt("Can't initialize onnxruntime.")},zu=async e=>{$w(e.wasm.numThreads,pi(e.logLevel))},Bu=async(e,r)=>{Qt().asyncInit?.();{let t=(t1(),Jo(av)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:o}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",Qt(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Qt(),e)}}},on=new Map,kw=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,n,n+s)!==0&&Gt("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(r.getValue(n,o)),Number(r.getValue(n+s,o))]}finally{r.stackRestore(t)}},Gc=(e,r)=>{let t=Qt(),s=t.stackSave(),n=0;try{let o=t.PTR_SIZE,i=t.stackAlloc(2*o);t._OrtGetInputOutputMetadata(e,r,i,i+o)!==0&&Gt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));n=Number(t.getValue(i+o,"*"));let l=t.HEAP32[n/4];if(l===0)return[a,0];let c=t.HEAPU32[n/4+1],p=[];for(let d=0;d{let r=Qt(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},Ru=async(e,r)=>{let t,s,n=Qt();Array.isArray(e)?[t,s]=e:e.buffer===n.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=gi(e);let o=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await db(r),r?.externalData&&n.mountExternalData){let T=[];for(let b of r.externalData){let E=typeof b=="string"?b:b.path;T.push(Tu(typeof b=="string"?b:b.data).then(x=>{n.mountExternalData(E,x)}))}await Promise.all(T)}for(let T of r?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let b=T,E=b?.context,x=b?.gpuDevice,S=b?.deviceType,O=b?.powerPreference;E?n.currentContext=E:x?n.currentContext=await n.webnnCreateMLContext(x):n.currentContext=await n.webnnCreateMLContext({deviceType:S,powerPreference:O})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(t,s,i),n.webgpuOnCreateSession?.(o),o===0&&Gt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,u]=kw(o),f=!!r?.enableGraphCapture,_=[],y=[],k=[],w=[],v=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor")&&(a=n._OrtCreateBinding(o),a===0&&Gt("Can't create IO binding."),I={handle:a,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(T=>Zc(T))}),on.set(o,[o,c,p,I,f,!1]),[o,_,y,k,w]}catch(d){throw c.forEach(u=>n._OrtFree(u)),p.forEach(u=>n._OrtFree(u)),a!==0&&n._OrtReleaseBinding(a)!==0&&Gt("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Gt("Can't release session."),d}finally{n._free(t),i!==0&&n._OrtReleaseSessionOptions(i)!==0&&Gt("Can't release session options."),l.forEach(d=>n._free(d)),n.unmountExternalData?.()}},Nu=e=>{let r=Qt(),t=on.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,o,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Gt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Gt("Can't release IO binding.")),r.jsepOnReleaseSession?.(e),r.webnnOnReleaseSession?.(e),r.webgpuOnReleaseSession?.(e),n.forEach(l=>r._OrtFree(l)),o.forEach(l=>r._OrtFree(l)),r._OrtReleaseSession(s)!==0&&Gt("Can't release session."),on.delete(e)},Kc=async(e,r,t,s,n,o,i=!1)=>{if(!e){r.push(0);return}let a=Qt(),l=a.PTR_SIZE,c=e[0],p=e[1],d=e[3],u=d,f,_;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;_=Sn(no(c),p);{let v=a.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=v(s,o,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=Sn(no(c),p);let v=a.webnnRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=v(s,w,no(c),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let v=0;va.setValue(k+I*l,v,l===4?"i32":"i64"));let w=a._OrtCreateTensor(no(c),f,_,k,p.length,Zc(u));w===0&&Gt(`Can't create tensor for input/output. session=${s}, index=${o}.`),r.push(w)}finally{a.stackRestore(y)}},ju=async(e,r,t,s,n,o)=>{let i=Qt(),a=i.PTR_SIZE,l=on.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],d=l[2],u=l[3],f=l[4],_=l[5],y=r.length,k=s.length,w=0,v=[],I=[],T=[],b=[],E=i.stackSave(),x=i.stackAlloc(y*a),S=i.stackAlloc(y*a),O=i.stackAlloc(k*a),F=i.stackAlloc(k*a);try{[w,v]=ub(o);for(let B=0;BAe*Ie,1);ne=Ks(oe);let he=u?.outputPreferredLocations[s[B]];if(ne==="string"){if(he==="gpu-buffer"||he==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ae=[];for(let Ie=0;Ie0){let Ae=i.jsepGetBuffer;if(!Ae)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ie=Ae(le),je=Sn(oe,te);if(je===void 0||!vu(ne))throw new Error(`Unsupported data type: ${ne}`);re=!0,W.push([ne,D,{gpuBuffer:Ie,download:i.jsepCreateDownloader(Ie,je,ne),dispose:()=>{i._OrtReleaseTensor(Y)!==0&&Gt("Can't release tensor.")}},"gpu-buffer"])}else if(he==="ml-tensor"&&te>0){let Ae=i.webnnEnsureTensor,Ie=i.webnnIsInt64Supported;if(!Ae||!Ie)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Sn(oe,te)===void 0||!xu(ne))throw new Error(`Unsupported data type: ${ne}`);if(ne==="int64"&&!Ie(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let je=await Ae(e,le,oe,D,!1);re=!0,W.push([ne,D,{mlTensor:je,download:i.webnnCreateMLTensorDownloader(le,ne),dispose:()=>{i.webnnReleaseTensorId(le),i._OrtReleaseTensor(Y)}},"ml-tensor"])}else{let Ae=yu(ne),Ie=new Ae(te);new Uint8Array(Ie.buffer,Ie.byteOffset,Ie.byteLength).set(i.HEAPU8.subarray(le,le+Ie.byteLength)),W.push([ne,D,Ie,"cpu"])}}finally{i.stackRestore(X),ne==="string"&&le&&i._free(le),re||i._OrtReleaseTensor(Y),i.webnnOnRunEnd?.(c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Gt("Can't clear bound outputs."),on.set(e,[c,p,d,u,f,!1])),W}finally{i.stackRestore(E),I.forEach(H=>i._OrtReleaseTensor(H)),T.forEach(H=>i._OrtReleaseTensor(H)),b.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),v.forEach(H=>i._free(H))}},Vu=e=>{let r=Qt(),t=on.get(e);if(!t)throw new Error("invalid session id");let s=t[0],n=r._OrtEndProfiling(s);n===0&&Gt("Can't get an profile file name."),r._OrtFree(n)},Uu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),an,as,ro,Wo,Go,oi,Hc,ai,Tn,En,Aw,uv,dv,pv,mv,hv,_v,fv,gv=Ve(()=>{Es(),cv(),Fn(),Mu(),an=()=>!!Jt.wasm.proxy&&typeof document<"u",ro=!1,Wo=!1,Go=!1,ai=new Map,Tn=(e,r)=>{let t=ai.get(e);t?t.push(r):ai.set(e,[r])},En=()=>{if(ro||!Wo||Go||!as)throw new Error("worker not ready")},Aw=e=>{switch(e.data.type){case"init-wasm":ro=!1,e.data.err?(Go=!0,Hc[1](e.data.err)):(Wo=!0,Hc[0]()),oi&&(URL.revokeObjectURL(oi),oi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=ai.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},uv=async()=>{if(!Wo){if(ro)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(ro=!0,an())return new Promise((e,r)=>{as?.terminate(),lb().then(([t,s])=>{try{as=s,as.onerror=o=>r(o),as.onmessage=Aw,Hc=[e,r];let n={type:"init-wasm",in:Jt};!n.in.wasm.wasmPaths&&(t||Yc)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href}),as.postMessage(n),oi=t}catch(n){r(n)}},r)});try{await wu(Jt.wasm),await zu(Jt),Wo=!0}catch(e){throw Go=!0,e}finally{ro=!1}}},dv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Jt}};as.postMessage(s)});await Bu(Jt,e)},pv=async e=>an()?(En(),new Promise((r,t)=>{Tn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};as.postMessage(s,[e.buffer])})):gi(e),mv=async(e,r)=>{if(an()){if(r?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return En(),new Promise((t,s)=>{Tn("create",[t,s]);let n={type:"create",in:{model:e,options:{...r}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),as.postMessage(n,o)})}else return Ru(e,r)},hv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("release",[r,t]);let s={type:"release",in:e};as.postMessage(s)});Nu(e)},_v=async(e,r,t,s,n,o)=>{if(an()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return En(),new Promise((i,a)=>{Tn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:o}};as.postMessage(c,Uu(l))})}else return ju(e,r,t,s,n,o)},fv=async e=>{if(an())return En(),new Promise((r,t)=>{Tn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};as.postMessage(s)});Vu(e)}}),qc,Fw,Mv,r1=Ve(()=>{Es(),gv(),gt(),gu(),pb(),qc=(e,r)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Fw=e=>{switch(e[3]){case"cpu":return new ys(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!vu(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:n}=e[2];return ys.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let r=e[0];if(!xu(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:n}=e[2];return ys.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},Mv=class{async fetchModelAndCopyToWasmMemory(e){return pv(await Tu(e))}async loadModel(e,r){Ts();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await mv(t,r),us()}async dispose(){return hv(this.sessionId)}async run(e,r,t){Ts();let s=[],n=[];Object.entries(e).forEach(d=>{let u=d[0],f=d[1],_=this.inputNames.indexOf(u);if(_===-1)throw new Error(`invalid input '${u}'`);s.push(f),n.push(_)});let o=[],i=[];Object.entries(r).forEach(d=>{let u=d[0],f=d[1],_=this.outputNames.indexOf(u);if(_===-1)throw new Error(`invalid output '${u}'`);o.push(f),i.push(_)});let a=s.map((d,u)=>qc(d,()=>`input "${this.inputNames[n[u]]}"`)),l=o.map((d,u)=>d?qc(d,()=>`output "${this.outputNames[i[u]]}"`):null),c=await _v(this.sessionId,n,a,i,l,t),p={};for(let d=0;dmu,initializeFlags:()=>pu,wasmBackend:()=>bv});var pu,mu,bv,s1=Ve(()=>{Es(),gv(),r1(),pu=()=>{(typeof Jt.wasm.initTimeout!="number"||Jt.wasm.initTimeout<0)&&(Jt.wasm.initTimeout=0);let e=Jt.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.`),Jt.wasm.simd=!1),typeof Jt.wasm.proxy!="boolean"&&(Jt.wasm.proxy=!1),typeof Jt.wasm.trace!="boolean"&&(Jt.wasm.trace=!1),typeof Jt.wasm.numThreads!="number"||!Number.isInteger(Jt.wasm.numThreads)||Jt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Jt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Ux("node:os").cpus().length:navigator.hardwareConcurrency;Jt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},mu=class{async init(e){pu(),await uv(),await dv(e)}async createInferenceSessionHandler(e,r){let t=new Mv;return await t.loadModel(e,r),t}},bv=new mu});Es();Es();Es();var n1="1.22.0-dev.20250409-89f8206ba4",o1=rb;{let e=(s1(),Jo(wv)).wasmBackend;In("webgpu",e,5),In("webnn",e,5),In("cpu",e,10),In("wasm",e,10)}Object.defineProperty(Jt.versions,"web",{value:n1,enumerable:!0});var a1=Object.freeze({__proto__:null,get InferenceSession(){return fu},get TRACE(){return Yo},get TRACE_FUNC_BEGIN(){return Ts},get TRACE_FUNC_END(){return us},get Tensor(){return ys},default:o1,get env(){return Jt},get registerBackend(){return In}}),Qc={},i1={"onnxruntime-common":(e=>{e.exports=Rx}),"onnxruntime-web":(e=>{e.exports=a1}),"?2ce3":(()=>{}),"?7992":(()=>{}),"?5af5":(()=>{}),"?2b25":(()=>{}),"?db59":(()=>{}),"?383f":(()=>{}),"?fa4b":(()=>{}),"./node_modules/@huggingface/jinja/dist/index.js":((e,r,t)=>{t.r(r),t.d(r,{Environment:()=>ot,Interpreter:()=>gr,Template:()=>Ss,parse:()=>Ae,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),n=class{constructor(C,q){this.value=C,this.type=q}};function o(C){return/\w/.test(C)}function i(C){return/[0-9]/.test(C)}function a(C){return/\s/.test(C)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["~",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],c=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(C,q={}){return C.endsWith(` `)&&(C=C.slice(0,-1)),q.lstrip_blocks&&(C=C.replace(/^[ \t]*({[#%-])/gm,"$1")),q.trim_blocks&&(C=C.replace(/([#%-]})\n/g,"$1")),C.replace(/{%\s*(end)?generation\s*%}/gs,"")}function d(C,q={}){const R=[],G=p(C,q);let Z=0,ce=0;const ye=He=>{let Mt="";for(;He(G[Z]);){if(G[Z]==="\\"){if(++Z,Z>=G.length)throw new SyntaxError("Unexpected end of input");const qe=G[Z++],Tt=c.get(qe);if(Tt===void 0)throw new SyntaxError(`Unexpected escaped character: ${qe}`);Mt+=Tt;continue}if(Mt+=G[Z++],Z>=G.length)throw new SyntaxError("Unexpected end of input")}return Mt},et=()=>{const He=R.at(-1);He&&He.type===s.Text&&(He.value=He.value.trimEnd(),He.value===""&&R.pop())},ut=()=>{for(;Z0){R.push(new n(qe,s.Text));continue}}if(G[Z]==="{"&&G[Z+1]==="#"){Z+=2;const qe=G[Z]==="-";qe&&++Z;let Tt="";for(;G[Z]!=="#"||G[Z+1]!=="}";){if(Z+2>=G.length)throw new SyntaxError("Missing end of comment tag");Tt+=G[Z++]}const kt=Tt.endsWith("-");kt&&(Tt=Tt.slice(0,-1)),qe&&et(),R.push(new n(Tt,s.Comment)),Z+=2,kt&&ut();continue}if(G.slice(Z,Z+3)==="{%-"){et(),R.push(new n("{%",s.OpenStatement)),Z+=3;continue}if(G.slice(Z,Z+3)==="{{-"){et(),R.push(new n("{{",s.OpenExpression)),ce=0,Z+=3;continue}if(ye(a),G.slice(Z,Z+3)==="-%}"){R.push(new n("%}",s.CloseStatement)),Z+=3,ut();continue}if(G.slice(Z,Z+3)==="-}}"){R.push(new n("}}",s.CloseExpression)),Z+=3,ut();continue}const Mt=G[Z];if(Mt==="-"||Mt==="+"){const qe=R.at(-1)?.type;if(qe===s.Text||qe===void 0)throw new SyntaxError(`Unexpected character: ${Mt}`);switch(qe){case s.Identifier:case s.NumericLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++Z;const Tt=ye(i);R.push(new n(`${Mt}${Tt}`,Tt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[qe,Tt]of l){if(qe==="}}"&&ce>0)continue;if(G.slice(Z,Z+qe.length)===qe){R.push(new n(qe,Tt)),Tt===s.OpenExpression?ce=0:Tt===s.OpenCurlyBracket?++ce:Tt===s.CloseCurlyBracket&&--ce,Z+=qe.length;continue e}}if(Mt==="'"||Mt==='"'){++Z;const qe=ye(Tt=>Tt!==Mt);R.push(new n(qe,s.StringLiteral)),++Z;continue}if(i(Mt)){let qe=ye(i);if(G[Z]==="."&&i(G[Z+1])){++Z;const Tt=ye(i);qe=`${qe}.${Tt}`}R.push(new n(qe,s.NumericLiteral));continue}if(o(Mt)){const qe=ye(o);R.push(new n(qe,s.Identifier));continue}throw new SyntaxError(`Unexpected character: ${Mt}`)}return R}var u=class{type="Statement"},f=class extends u{constructor(C){super(),this.body=C}type="Program"},_=class extends u{constructor(C,q,R){super(),this.test=C,this.body=q,this.alternate=R}type="If"},y=class extends u{constructor(C,q,R,G){super(),this.loopvar=C,this.iterable=q,this.body=R,this.defaultBlock=G}type="For"},k=class extends u{type="Break"},w=class extends u{type="Continue"},v=class extends u{constructor(C,q,R){super(),this.assignee=C,this.value=q,this.body=R}type="Set"},I=class extends u{constructor(C,q,R){super(),this.name=C,this.args=q,this.body=R}type="Macro"},T=class extends u{constructor(C){super(),this.value=C}type="Comment"},b=class extends u{type="Expression"},E=class extends b{constructor(C,q,R){super(),this.object=C,this.property=q,this.computed=R}type="MemberExpression"},x=class extends b{constructor(C,q){super(),this.callee=C,this.args=q}type="CallExpression"},S=class extends b{constructor(C){super(),this.value=C}type="Identifier"},O=class extends b{constructor(C){super(),this.value=C}type="Literal"},F=class extends O{type="IntegerLiteral"},H=class extends O{type="FloatLiteral"},W=class extends O{type="StringLiteral"},B=class extends O{type="ArrayLiteral"},Y=class extends O{type="TupleLiteral"},X=class extends O{type="ObjectLiteral"},J=class extends b{constructor(C,q,R){super(),this.operator=C,this.left=q,this.right=R}type="BinaryExpression"},re=class extends b{constructor(C,q){super(),this.operand=C,this.filter=q}type="FilterExpression"},ne=class extends u{constructor(C,q){super(),this.filter=C,this.body=q}type="FilterStatement"},le=class extends b{constructor(C,q){super(),this.lhs=C,this.test=q}type="SelectExpression"},pe=class extends b{constructor(C,q,R){super(),this.operand=C,this.negate=q,this.test=R}type="TestExpression"},oe=class extends b{constructor(C,q){super(),this.operator=C,this.argument=q}type="UnaryExpression"},K=class extends b{constructor(C=void 0,q=void 0,R=void 0){super(),this.start=C,this.stop=q,this.step=R}type="SliceExpression"},N=class extends b{constructor(C,q){super(),this.key=C,this.value=q}type="KeywordArgumentExpression"},D=class extends b{constructor(C){super(),this.argument=C}type="SpreadExpression"},te=class extends u{constructor(C,q,R){super(),this.call=C,this.callerArgs=q,this.body=R}type="CallStatement"},he=class extends b{constructor(C,q,R){super(),this.condition=C,this.trueExpr=q,this.falseExpr=R}type="Ternary"};function Ae(C){const q=new f([]);let R=0;function G(ze,Ue){const nt=C[R++];if(!nt||nt.type!==ze)throw new Error(`Parser Error: ${Ue}. ${nt.type} !== ${ze}.`);return nt}function Z(ze){if(!ut(ze))throw new SyntaxError(`Expected ${ze}`);++R}function ce(){switch(C[R].type){case s.Comment:return new T(C[R++].value);case s.Text:return He();case s.OpenStatement:return Mt();case s.OpenExpression:return qe();default:throw new SyntaxError(`Unexpected token type: ${C[R].type}`)}}function ye(...ze){return R+ze.length<=C.length&&ze.every((Ue,nt)=>Ue===C[R+nt].type)}function et(...ze){return C[R]?.type===s.OpenStatement&&C[R+1]?.type===s.Identifier&&ze.includes(C[R+1]?.value)}function ut(...ze){return R+ze.length<=C.length&&ze.every((Ue,nt)=>C[R+nt].type==="Identifier"&&Ue===C[R+nt].value)}function He(){return new W(G(s.Text,"Expected text token").value)}function Mt(){if(G(s.OpenStatement,"Expected opening statement token"),C[R].type!==s.Identifier)throw new SyntaxError(`Unknown statement, got ${C[R].type}`);const ze=C[R].value;let Ue;switch(ze){case"set":++R,Ue=Tt();break;case"if":++R,Ue=kt(),G(s.OpenStatement,"Expected {% token"),Z("endif"),G(s.CloseStatement,"Expected %} token");break;case"macro":++R,Ue=Mr(),G(s.OpenStatement,"Expected {% token"),Z("endmacro"),G(s.CloseStatement,"Expected %} token");break;case"for":++R,Ue=ar(),G(s.OpenStatement,"Expected {% token"),Z("endfor"),G(s.CloseStatement,"Expected %} token");break;case"call":{++R;let nt=null;ye(s.OpenParen)&&(nt=Hr());const Kt=Nr();if(Kt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Ns=Hr();G(s.CloseStatement,"Expected closing statement token");const Os=[];for(;!et("endcall");)Os.push(ce());G(s.OpenStatement,"Expected '{%'"),Z("endcall"),G(s.CloseStatement,"Expected closing statement token");const js=new x(Kt,Ns);Ue=new te(js,nt,Os);break}case"break":++R,G(s.CloseStatement,"Expected closing statement token"),Ue=new k;break;case"continue":++R,G(s.CloseStatement,"Expected closing statement token"),Ue=new w;break;case"filter":{++R;let nt=Nr();nt instanceof S&&ye(s.OpenParen)&&(nt=ir(nt)),G(s.CloseStatement,"Expected closing statement token");const Kt=[];for(;!et("endfilter");)Kt.push(ce());G(s.OpenStatement,"Expected '{%'"),Z("endfilter"),G(s.CloseStatement,"Expected '%}'"),Ue=new ne(nt,Kt);break}default:throw new SyntaxError(`Unknown statement type: ${ze}`)}return Ue}function qe(){G(s.OpenExpression,"Expected opening expression token");const ze=Tr();return G(s.CloseExpression,"Expected closing expression token"),ze}function Tt(){const ze=dr();let Ue=null;const nt=[];if(ye(s.Equals))++R,Ue=dr();else{for(G(s.CloseStatement,"Expected %} token");!et("endset");)nt.push(ce());G(s.OpenStatement,"Expected {% token"),Z("endset")}return G(s.CloseStatement,"Expected closing statement token"),new v(ze,Ue,nt)}function kt(){const ze=Tr();G(s.CloseStatement,"Expected closing statement token");const Ue=[],nt=[];for(;!et("elif","else","endif");)Ue.push(ce());if(et("elif")){++R,++R;const Kt=kt();nt.push(Kt)}else if(et("else"))for(++R,++R,G(s.CloseStatement,"Expected closing statement token");!et("endif");)nt.push(ce());return new _(ze,Ue,nt)}function Mr(){const ze=Nr();if(ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ue=Hr();G(s.CloseStatement,"Expected closing statement token");const nt=[];for(;!et("endmacro");)nt.push(ce());return new I(ze,Ue,nt)}function dr(ze=!1){const Ue=ze?Nr:Tr,nt=[Ue()],Kt=ye(s.Comma);for(;Kt&&(++R,nt.push(Ue()),!!ye(s.Comma)););return Kt?new Y(nt):nt[0]}function ar(){const ze=dr(!0);if(!(ze instanceof S||ze instanceof Y))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ze.type} instead`);if(!ut("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++R;const Ue=Tr();G(s.CloseStatement,"Expected closing statement token");const nt=[];for(;!et("endfor","else");)nt.push(ce());const Kt=[];if(et("else"))for(++R,++R,G(s.CloseStatement,"Expected closing statement token");!et("endfor");)Kt.push(ce());return new y(ze,Ue,nt,Kt)}function Tr(){return Is()}function Is(){const ze=Dr();if(ut("if")){++R;const Ue=Dr();if(ut("else")){++R;const nt=Is();return new he(Ue,ze,nt)}else return new le(ze,Ue)}return ze}function Dr(){let ze=$s();for(;ut("or");){const Ue=C[R];++R;const nt=$s();ze=new J(Ue,ze,nt)}return ze}function $s(){let ze=Lr();for(;ut("and");){const Ue=C[R];++R;const nt=Lr();ze=new J(Ue,ze,nt)}return ze}function Lr(){let ze;for(;ut("not");){const Ue=C[R];++R;const nt=Lr();ze=new oe(Ue,nt)}return ze??zr()}function zr(){let ze=ts();for(;;){let Ue;if(ut("not","in"))Ue=new n("not in",s.Identifier),R+=2;else if(ut("in"))Ue=C[R++];else if(ye(s.ComparisonBinaryOperator))Ue=C[R++];else break;const nt=ts();ze=new J(Ue,ze,nt)}return ze}function ts(){let ze=As();for(;ye(s.AdditiveBinaryOperator);){const Ue=C[R];++R;const nt=As();ze=new J(Ue,ze,nt)}return ze}function wr(){const ze=ks(Nr());return ye(s.OpenParen)?ir(ze):ze}function ir(ze){let Ue=new x(ze,Hr());return Ue=ks(Ue),ye(s.OpenParen)&&(Ue=ir(Ue)),Ue}function Hr(){G(s.OpenParen,"Expected opening parenthesis for arguments list");const ze=rs();return G(s.CloseParen,"Expected closing parenthesis for arguments list"),ze}function rs(){const ze=[];for(;!ye(s.CloseParen);){let Ue;if(C[R].type===s.MultiplicativeBinaryOperator&&C[R].value==="*"){++R;const nt=Tr();Ue=new D(nt)}else if(Ue=Tr(),ye(s.Equals)){if(++R,!(Ue instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const nt=Tr();Ue=new N(Ue,nt)}ze.push(Ue),ye(s.Comma)&&++R}return ze}function Rs(){const ze=[];let Ue=!1;for(;!ye(s.CloseSquareBracket);)ye(s.Colon)?(ze.push(void 0),++R,Ue=!0):(ze.push(Tr()),ye(s.Colon)&&(++R,Ue=!0));if(ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ue){if(ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new K(...ze)}return ze[0]}function ks(ze){for(;ye(s.Dot)||ye(s.OpenSquareBracket);){const Ue=C[R];++R;let nt;const Kt=Ue.type===s.OpenSquareBracket;if(Kt)nt=Rs(),G(s.CloseSquareBracket,"Expected closing square bracket");else if(nt=Nr(),nt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ze=new E(ze,nt,Kt)}return ze}function As(){let ze=Fs();for(;ye(s.MultiplicativeBinaryOperator);){const Ue=C[R++],nt=Fs();ze=new J(Ue,ze,nt)}return ze}function Fs(){let ze=ss();for(;ut("is");){++R;const Ue=ut("not");Ue&&++R;const nt=Nr();if(!(nt instanceof S))throw new SyntaxError("Expected identifier for the test");ze=new pe(ze,Ue,nt)}return ze}function ss(){let ze=wr();for(;ye(s.Pipe);){++R;let Ue=Nr();if(!(Ue instanceof S))throw new SyntaxError("Expected identifier for the filter");ye(s.OpenParen)&&(Ue=ir(Ue)),ze=new re(ze,Ue)}return ze}function Nr(){const ze=C[R++];switch(ze.type){case s.NumericLiteral:{const Ue=ze.value;return Ue.includes(".")?new H(Number(Ue)):new F(Number(Ue))}case s.StringLiteral:{let Ue=ze.value;for(;ye(s.StringLiteral);)Ue+=C[R++].value;return new W(Ue)}case s.Identifier:return new S(ze.value);case s.OpenParen:{const Ue=dr();return G(s.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),Ue}case s.OpenSquareBracket:{const Ue=[];for(;!ye(s.CloseSquareBracket);)Ue.push(Tr()),ye(s.Comma)&&++R;return++R,new B(Ue)}case s.OpenCurlyBracket:{const Ue=new Map;for(;!ye(s.CloseCurlyBracket);){const nt=Tr();G(s.Colon,"Expected colon between key and value in object literal");const Kt=Tr();Ue.set(nt,Kt),ye(s.Comma)&&++R}return++R,new X(Ue)}default:throw new SyntaxError(`Unexpected token: ${ze.type}`)}}for(;R=0?(q=(q??=0)<0?Math.max(C.length+q,0):Math.min(q,C.length),R=(R??=C.length)<0?Math.max(C.length+R,0):Math.min(R,C.length)):(q=(q??=C.length-1)<0?Math.max(C.length+q,-1):Math.min(q,C.length-1),R=(R??=-1)<-1?Math.max(C.length+R,-1):Math.min(R,C.length-1));const ce=[];for(let ye=q;Z*yeq.toUpperCase())}function Q(C){return z(new Date,C)}function z(C,q){const R=new Intl.DateTimeFormat(void 0,{month:"long"}),G=new Intl.DateTimeFormat(void 0,{month:"short"}),Z=ce=>ce<10?"0"+ce:ce.toString();return q.replace(/%[YmdbBHM%]/g,ce=>{switch(ce){case"%Y":return C.getFullYear().toString();case"%m":return Z(C.getMonth()+1);case"%d":return Z(C.getDate());case"%b":return G.format(C);case"%B":return R.format(C);case"%H":return Z(C.getHours());case"%M":return Z(C.getMinutes());case"%%":return"%";default:return ce}})}function de(C){return C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(C,q,R,G){if(G===0)return C;let Z=G==null||G<0?1/0:G;const ce=q.length===0?new RegExp("(?=)","gu"):new RegExp(de(q),"gu");return C.replaceAll(ce,ye=>Z>0?(--Z,R):ye)}var ve=class extends Error{},xe=class extends Error{},Ce=class{type="RuntimeValue";value;builtins=new Map;constructor(C=void 0){this.value=C}__bool__(){return new Ee(!!this.value)}toString(){return String(this.value)}},ge=class extends Ce{type="IntegerValue"},De=class extends Ce{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},fe=class extends Ce{type="StringValue";builtins=new Map([["upper",new Ze(()=>new fe(this.value.toUpperCase()))],["lower",new Ze(()=>new fe(this.value.toLowerCase()))],["strip",new Ze(()=>new fe(this.value.trim()))],["title",new Ze(()=>new fe(Te(this.value)))],["capitalize",new Ze(()=>new fe(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ge(this.value.length)],["rstrip",new Ze(()=>new fe(this.value.trimEnd()))],["lstrip",new Ze(()=>new fe(this.value.trimStart()))],["startswith",new Ze(C=>{if(C.length===0)throw new Error("startswith() requires at least one argument");const q=C[0];if(q instanceof fe)return new Ee(this.value.startsWith(q.value));if(q instanceof Re){for(const R of q.value){if(!(R instanceof fe))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(R.value))return new Ee(!0)}return new Ee(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ze(C=>{if(C.length===0)throw new Error("endswith() requires at least one argument");const q=C[0];if(q instanceof fe)return new Ee(this.value.endsWith(q.value));if(q instanceof Re){for(const R of q.value){if(!(R instanceof fe))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(R.value))return new Ee(!0)}return new Ee(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ze(C=>{const q=C[0]??new Ne;if(!(q instanceof fe||q instanceof Ne))throw new Error("sep argument must be a string or null");const R=C[1]??new ge(-1);if(!(R instanceof ge))throw new Error("maxsplit argument must be a number");let G=[];if(q instanceof Ne){const Z=this.value.trimStart();for(const{0:ce,index:ye}of Z.matchAll(/\S+/g)){if(R.value!==-1&&G.length>=R.value&&ye!==void 0){G.push(ce+Z.slice(ye+ce.length));break}G.push(ce)}}else{if(q.value==="")throw new Error("empty separator");G=this.value.split(q.value),R.value!==-1&&G.length>R.value&&G.push(G.splice(R.value).join(q.value))}return new Re(G.map(Z=>new fe(Z)))})],["replace",new Ze(C=>{if(C.length<2)throw new Error("replace() requires at least two arguments");const q=C[0],R=C[1];if(!(q instanceof fe&&R instanceof fe))throw new Error("replace() arguments must be strings");let G;if(C.length>2?C[2].type==="KeywordArgumentsValue"?G=C[2].value.get("count")??new Ne:G=C[2]:G=new Ne,!(G instanceof ge||G instanceof Ne))throw new Error("replace() count argument must be a number or null");return new fe(be(this.value,q.value,R.value,G.value))})]])},Ee=class extends Ce{type="BooleanValue"};function We(C,q,R,G=!0){const Z=R??0;switch(C.type){case"NullValue":return"null";case"UndefinedValue":return G?"null":"undefined";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(C.value);case"ArrayValue":case"ObjectValue":{const ce=q?" ".repeat(q):"",ye=` `+ce.repeat(Z),et=ye+ce;if(C.type==="ArrayValue"){const ut=C.value.map(He=>We(He,q,Z+1,G));return q?`[${et}${ut.join(`,${et}`)}${ye}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(C.value.entries()).map(([He,Mt])=>{const qe=`"${He}": ${We(Mt,q,Z+1,G)}`;return q?`${et}${qe}`:qe});return q?`{${ut.join(",")}${ye}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${C.type}`)}}var Fe=class extends Ce{type="ObjectValue";__bool__(){return new Ee(this.value.size>0)}builtins=new Map([["get",new Ze(([C,q])=>{if(!(C instanceof fe))throw new Error(`Object key must be a string: got ${C.type}`);return this.value.get(C.value)??q??new Ne})],["items",new Ze(()=>this.items())],["keys",new Ze(()=>this.keys())],["values",new Ze(()=>this.values())],["dictsort",new Ze(C=>{let q=new Map;const R=C.filter(et=>et instanceof tt?(q=et.value,!1):!0),G=R.at(0)??q.get("case_sensitive")??new Ee(!1);if(!(G instanceof Ee))throw new Error("case_sensitive must be a boolean");const Z=R.at(1)??q.get("by")??new fe("key");if(!(Z instanceof fe))throw new Error("by must be a string");if(!["key","value"].includes(Z.value))throw new Error("by must be either 'key' or 'value'");const ce=R.at(2)??q.get("reverse")??new Ee(!1);if(!(ce instanceof Ee))throw new Error("reverse must be a boolean");const ye=Array.from(this.value.entries()).map(([et,ut])=>new Re([new fe(et),ut])).sort((et,ut)=>{const He=Z.value==="key"?0:1,Mt=et.value[He],qe=ut.value[He],Tt=It(Mt,qe,G.value);return ce.value?-Tt:Tt});return new Re(ye)})]]);items(){return new Re(Array.from(this.value.entries()).map(([C,q])=>new Re([new fe(C),q])))}keys(){return new Re(Array.from(this.value.keys()).map(C=>new fe(C)))}values(){return new Re(Array.from(this.value.values()))}toString(){return We(this,null,0,!1)}},tt=class extends Fe{type="KeywordArgumentsValue"},Re=class extends Ce{type="ArrayValue";builtins=new Map([["length",new ge(this.value.length)]]);__bool__(){return new Ee(this.value.length>0)}toString(){return We(this,null,0,!1)}},rt=class extends Re{type="TupleValue"},Ze=class extends Ce{type="FunctionValue"},Ne=class extends Ce{type="NullValue"},Oe=class extends Ce{type="UndefinedValue"},ot=class{constructor(C){this.parent=C}variables=new Map([["namespace",new Ze(C=>{if(C.length===0)return new Fe(new Map);if(C.length!==1||!(C[0]instanceof Fe))throw new Error("`namespace` expects either zero arguments or a single object argument");return C[0]})]]);tests=new Map([["boolean",C=>C.type==="BooleanValue"],["callable",C=>C instanceof Ze],["odd",C=>{if(!(C instanceof ge))throw new Error(`cannot odd on ${C.type}`);return C.value%2!==0}],["even",C=>{if(!(C instanceof ge))throw new Error(`cannot even on ${C.type}`);return C.value%2===0}],["false",C=>C.type==="BooleanValue"&&!C.value],["true",C=>C.type==="BooleanValue"&&C.value],["none",C=>C.type==="NullValue"],["string",C=>C.type==="StringValue"],["number",C=>C instanceof ge||C instanceof De],["integer",C=>C instanceof ge],["iterable",C=>C.type==="ArrayValue"||C.type==="StringValue"],["mapping",C=>C.type==="ObjectValue"],["lower",C=>{const q=C.value;return C.type==="StringValue"&&q===q.toLowerCase()}],["upper",C=>{const q=C.value;return C.type==="StringValue"&&q===q.toUpperCase()}],["none",C=>C.type==="NullValue"],["defined",C=>C.type!=="UndefinedValue"],["undefined",C=>C.type==="UndefinedValue"],["equalto",(C,q)=>C.value===q.value],["eq",(C,q)=>C.value===q.value]]);set(C,q){return this.declareVariable(C,Or(q))}declareVariable(C,q){if(this.variables.has(C))throw new SyntaxError(`Variable already declared: ${C}`);return this.variables.set(C,q),q}setVariable(C,q){return this.variables.set(C,q),q}resolve(C){if(this.variables.has(C))return this;if(this.parent)return this.parent.resolve(C);throw new Error(`Unknown variable: ${C}`)}lookupVariable(C){try{return this.resolve(C).variables.get(C)??new Oe}catch{return new Oe}}};function ht(C){C.set("false",!1),C.set("true",!0),C.set("none",null),C.set("raise_exception",q=>{throw new Error(q)}),C.set("range",Ie),C.set("strftime_now",Q),C.set("True",!0),C.set("False",!1),C.set("None",null)}function Rt(C,q){const R=q.split(".");let G=C;for(const Z of R)if(G instanceof Fe)G=G.value.get(Z)??new Oe;else if(G instanceof Re){const ce=parseInt(Z,10);if(!isNaN(ce)&&ce>=0&&cece instanceof ge||ce instanceof De||ce instanceof Ee,Z=ce=>ce instanceof Ee?ce.value?1:0:ce.value;if(G(C)&&G(q)){const ce=Z(C),ye=Z(q);return ceye?1:0}if(C.type!==q.type)throw new Error(`Cannot compare different types: ${C.type} and ${q.type}`);if(C.type==="StringValue"){let ce=C.value,ye=q.value;return R||(ce=ce.toLowerCase(),ye=ye.toLowerCase()),ceye?1:0}else throw new Error(`Cannot compare type: ${C.type}`)}var gr=class{global;constructor(C){this.global=C??new ot}run(C){return this.evaluate(C,this.global)}evaluateBinaryExpression(C,q){const R=this.evaluate(C.left,q);switch(C.operator.value){case"and":return R.__bool__().value?this.evaluate(C.right,q):R;case"or":return R.__bool__().value?R:this.evaluate(C.right,q)}const G=this.evaluate(C.right,q);switch(C.operator.value){case"==":return new Ee(R.value==G.value);case"!=":return new Ee(R.value!=G.value)}if(R instanceof Oe||G instanceof Oe){if(G instanceof Oe&&["in","not in"].includes(C.operator.value))return new Ee(C.operator.value==="not in");throw new Error(`Cannot perform operation ${C.operator.value} on undefined values`)}else{if(R instanceof Ne||G instanceof Ne)throw new Error("Cannot perform operation on null values");if(C.operator.value==="~")return new fe(R.value.toString()+G.value.toString());if((R instanceof ge||R instanceof De)&&(G instanceof ge||G instanceof De)){const Z=R.value,ce=G.value;switch(C.operator.value){case"+":case"-":case"*":{const ye=C.operator.value==="+"?Z+ce:C.operator.value==="-"?Z-ce:Z*ce;return R instanceof De||G instanceof De?new De(ye):new ge(ye)}case"/":return new De(Z/ce);case"%":{const ye=Z%ce;return R instanceof De||G instanceof De?new De(ye):new ge(ye)}case"<":return new Ee(Z":return new Ee(Z>ce);case">=":return new Ee(Z>=ce);case"<=":return new Ee(Z<=ce)}}else if(R instanceof Re&&G instanceof Re){if(C.operator.value==="+")return new Re(R.value.concat(G.value))}else if(G instanceof Re){const Z=G.value.find(ce=>ce.value===R.value)!==void 0;switch(C.operator.value){case"in":return new Ee(Z);case"not in":return new Ee(!Z)}}}if((R instanceof fe||G instanceof fe)&&C.operator.value==="+")return new fe(R.value.toString()+G.value.toString());if(R instanceof fe&&G instanceof fe)switch(C.operator.value){case"in":return new Ee(G.value.includes(R.value));case"not in":return new Ee(!G.value.includes(R.value))}if(R instanceof fe&&G instanceof Fe)switch(C.operator.value){case"in":return new Ee(G.value.has(R.value));case"not in":return new Ee(!G.value.has(R.value))}throw new SyntaxError(`Unknown operator "${C.operator.value}" between ${R.type} and ${G.type}`)}evaluateArguments(C,q){const R=[],G=new Map;for(const Z of C)if(Z.type==="SpreadExpression"){const ce=Z,ye=this.evaluate(ce.argument,q);if(!(ye instanceof Re))throw new Error(`Cannot unpack non-iterable type: ${ye.type}`);for(const et of ye.value)R.push(et)}else if(Z.type==="KeywordArgumentExpression"){const ce=Z;G.set(ce.key.value,this.evaluate(ce.value,q))}else{if(G.size>0)throw new Error("Positional arguments must come before keyword arguments");R.push(this.evaluate(Z,q))}return[R,G]}applyFilter(C,q,R){if(q.type==="Identifier"){const G=q;if(G.value==="tojson")return new fe(We(C));if(C instanceof Re)switch(G.value){case"list":return C;case"first":return C.value[0];case"last":return C.value[C.value.length-1];case"length":return new ge(C.value.length);case"reverse":return new Re(C.value.slice().reverse());case"sort":return new Re(C.value.slice().sort((Z,ce)=>It(Z,ce,!1)));case"join":return new fe(C.value.map(Z=>Z.value).join(""));case"string":return new fe(We(C,null,0,!1));case"unique":{const Z=new Set,ce=[];for(const ye of C.value)Z.has(ye.value)||(Z.add(ye.value),ce.push(ye));return new Re(ce)}default:throw new Error(`Unknown ArrayValue filter: ${G.value}`)}else if(C instanceof fe)switch(G.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const Z=C.builtins.get(G.value);if(Z instanceof Ze)return Z.value([],R);if(Z instanceof ge)return Z;throw new Error(`Unknown StringValue filter: ${G.value}`)}case"trim":return new fe(C.value.trim());case"indent":return new fe(C.value.split(` @@ -2829,7 +2829,7 @@ ${o}`,a=t.createShaderModule({code:i,label:e.name});Dt("verbose",()=>`[WebGPU] $ `))}case"replace":{const ce=C.builtins.get("replace");if(!(ce instanceof Ze))throw new Error("replace filter not available");const[ye,et]=this.evaluateArguments(G.args,R);return ce.value([...ye,new tt(et)],R)}}throw new Error(`Unknown StringValue filter: ${Z}`)}else if(C instanceof Fe){const ce=C.builtins.get(Z);if(ce&&ce instanceof Ze){const[ye,et]=this.evaluateArguments(G.args,R);return et.size>0&&ye.push(new tt(et)),ce.value(ye,R)}throw new Error(`Unknown ObjectValue filter: ${Z}`)}else throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`)}throw new Error(`Unknown filter: ${q.type}`)}evaluateFilterExpression(C,q){const R=this.evaluate(C.operand,q);return this.applyFilter(R,C.filter,q)}evaluateTestExpression(C,q){const R=this.evaluate(C.operand,q),G=q.tests.get(C.test.value);if(!G)throw new Error(`Unknown test: ${C.test.value}`);const Z=G(R);return new Ee(C.negate?!Z:Z)}evaluateSelectExpression(C,q){return this.evaluate(C.test,q).__bool__().value?this.evaluate(C.lhs,q):new Oe}evaluateUnaryExpression(C,q){const R=this.evaluate(C.argument,q);if(C.operator.value==="not")return new Ee(!R.value);throw new SyntaxError(`Unknown operator: ${C.operator.value}`)}evaluateTernaryExpression(C,q){return this.evaluate(C.condition,q).__bool__().value?this.evaluate(C.trueExpr,q):this.evaluate(C.falseExpr,q)}evalProgram(C,q){return this.evaluateBlock(C.body,q)}evaluateBlock(C,q){let R="";for(const G of C){const Z=this.evaluate(G,q);Z.type!=="NullValue"&&Z.type!=="UndefinedValue"&&(R+=Z.toString())}return new fe(R)}evaluateIdentifier(C,q){return q.lookupVariable(C.value)}evaluateCallExpression(C,q){const[R,G]=this.evaluateArguments(C.args,q);G.size>0&&R.push(new tt(G));const Z=this.evaluate(C.callee,q);if(Z.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Z.type}`);return Z.value(R,q)}evaluateSliceExpression(C,q,R){if(!(C instanceof Re||C instanceof fe))throw new Error("Slice object must be an array or string");const G=this.evaluate(q.start,R),Z=this.evaluate(q.stop,R),ce=this.evaluate(q.step,R);if(!(G instanceof ge||G instanceof Oe))throw new Error("Slice start must be numeric or undefined");if(!(Z instanceof ge||Z instanceof Oe))throw new Error("Slice stop must be numeric or undefined");if(!(ce instanceof ge||ce instanceof Oe))throw new Error("Slice step must be numeric or undefined");return C instanceof Re?new Re(je(C.value,G.value,Z.value,ce.value)):new fe(je(Array.from(C.value),G.value,Z.value,ce.value).join(""))}evaluateMemberExpression(C,q){const R=this.evaluate(C.object,q);let G;if(C.computed){if(C.property.type==="SliceExpression")return this.evaluateSliceExpression(R,C.property,q);G=this.evaluate(C.property,q)}else G=new fe(C.property.value);let Z;if(R instanceof Fe){if(!(G instanceof fe))throw new Error(`Cannot access property with non-string: got ${G.type}`);Z=R.value.get(G.value)??R.builtins.get(G.value)}else if(R instanceof Re||R instanceof fe)if(G instanceof ge)Z=R.value.at(G.value),R instanceof fe&&(Z=new fe(R.value.at(G.value)));else if(G instanceof fe)Z=R.builtins.get(G.value);else throw new Error(`Cannot access property with non-string/non-number: got ${G.type}`);else{if(!(G instanceof fe))throw new Error(`Cannot access property with non-string: got ${G.type}`);Z=R.builtins.get(G.value)}return Z instanceof Ce?Z:new Oe}evaluateSet(C,q){const R=C.value?this.evaluate(C.value,q):this.evaluateBlock(C.body,q);if(C.assignee.type==="Identifier"){const G=C.assignee.value;q.setVariable(G,R)}else if(C.assignee.type==="TupleLiteral"){const G=C.assignee;if(!(R instanceof Re))throw new Error(`Cannot unpack non-iterable type in set: ${R.type}`);const Z=R.value;if(Z.length!==G.value.length)throw new Error(`Too ${G.value.length>Z.length?"few":"many"} items to unpack in set`);for(let ce=0;cekt.setVariable(C.loopvar.value,qe);else if(C.loopvar.type==="TupleLiteral"){const kt=C.loopvar;if(qe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${qe.type}`);const Mr=qe;if(kt.value.length!==Mr.value.length)throw new Error(`Too ${kt.value.length>Mr.value.length?"few":"many"} items to unpack`);Tt=dr=>{for(let ar=0;ar0?ce[He-1]:new Oe],["nextitem",He{const Z=new ot(G);R=R.slice();let ce;R.at(-1)?.type==="KeywordArgumentsValue"&&(ce=R.pop());for(let ye=0;ye{const He=new ot(ut);if(C.callerArgs)for(let Mt=0;Mtthis.evaluate(R,q)));case"TupleLiteral":return new rt(C.value.map(R=>this.evaluate(R,q)));case"ObjectLiteral":{const R=new Map;for(const[G,Z]of C.value){const ce=this.evaluate(G,q);if(!(ce instanceof fe))throw new Error(`Object keys must be strings: got ${ce.type}`);R.set(ce.value,this.evaluate(Z,q))}return new Fe(R)}case"Identifier":return this.evaluateIdentifier(C,q);case"CallExpression":return this.evaluateCallExpression(C,q);case"MemberExpression":return this.evaluateMemberExpression(C,q);case"UnaryExpression":return this.evaluateUnaryExpression(C,q);case"BinaryExpression":return this.evaluateBinaryExpression(C,q);case"FilterExpression":return this.evaluateFilterExpression(C,q);case"FilterStatement":return this.evaluateFilterStatement(C,q);case"TestExpression":return this.evaluateTestExpression(C,q);case"SelectExpression":return this.evaluateSelectExpression(C,q);case"Ternary":return this.evaluateTernaryExpression(C,q);case"Comment":return new Ne;default:throw new SyntaxError(`Unknown node type: ${C.type}`)}}};function Or(C){switch(typeof C){case"number":return Number.isInteger(C)?new ge(C):new De(C);case"string":return new fe(C);case"boolean":return new Ee(C);case"undefined":return new Oe;case"object":return C===null?new Ne:Array.isArray(C)?new Re(C.map(Or)):new Fe(new Map(Object.entries(C).map(([q,R])=>[q,Or(R)])));case"function":return new Ze((q,R)=>{const G=C(...q.map(Z=>Z.value))??null;return Or(G)});default:throw new Error(`Cannot convert to runtime value: ${C}`)}}var zt=` `,Rr="{%- ",qs=" -%}";function Qs(C){switch(C.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return C.operator.value==="and"?1:C.operator.value==="in"||C.operator.value==="not in"?2:0}return 0}function Xs(C,q=" "){const R=typeof q=="number"?" ".repeat(q):q;return Sr(C.body,0,R).replace(/\n$/,"")}function or(...C){return Rr+C.join(" ")+qs}function Sr(C,q,R){return C.map(G=>Qr(G,q,R)).join(zt)}function Qr(C,q,R){const G=R.repeat(q);switch(C.type){case"Program":return Sr(C.body,q,R);case"If":return Bs(C,q,R);case"For":return ft(C,q,R);case"Set":return qt(C,q,R);case"Macro":return Ps(C,q,R);case"Break":return G+or("break");case"Continue":return G+or("continue");case"CallStatement":return Cs(C,q,R);case"FilterStatement":return Kr(C,q,R);case"Comment":return G+"{# "+C.value+" #}";default:return G+"{{- "+yt(C)+" -}}"}}function Bs(C,q,R){const G=R.repeat(q),Z=[];let ce=C;for(;ce&&(Z.push({test:ce.test,body:ce.body}),ce.alternate.length===1&&ce.alternate[0].type==="If");)ce=ce.alternate[0];let ye=G+or("if",yt(Z[0].test))+zt+Sr(Z[0].body,q+1,R);for(let et=1;et0&&(ye+=zt+G+or("else")+zt+Sr(ce.alternate,q+1,R)),ye+=zt+G+or("endif"),ye}function ft(C,q,R){const G=R.repeat(q);let Z="";if(C.iterable.type==="SelectExpression"){const ye=C.iterable;Z=`${yt(ye.lhs)} if ${yt(ye.test)}`}else Z=yt(C.iterable);let ce=G+or("for",yt(C.loopvar),"in",Z)+zt+Sr(C.body,q+1,R);return C.defaultBlock.length>0&&(ce+=zt+G+or("else")+zt+Sr(C.defaultBlock,q+1,R)),ce+=zt+G+or("endfor"),ce}function qt(C,q,R){const G=R.repeat(q),Z=yt(C.assignee),ce=C.value?yt(C.value):"",ye=G+or("set",`${Z}${C.value?" = "+ce:""}`);return C.body.length===0?ye:ye+zt+Sr(C.body,q+1,R)+zt+G+or("endset")}function Ps(C,q,R){const G=R.repeat(q),Z=C.args.map(yt).join(", ");return G+or("macro",`${C.name.value}(${Z})`)+zt+Sr(C.body,q+1,R)+zt+G+or("endmacro")}function Cs(C,q,R){const G=R.repeat(q),Z=C.callerArgs&&C.callerArgs.length>0?`(${C.callerArgs.map(yt).join(", ")})`:"",ce=yt(C.call);let ye=G+or(`call${Z}`,ce)+zt;return ye+=Sr(C.body,q+1,R)+zt,ye+=G+or("endcall"),ye}function Kr(C,q,R){const G=R.repeat(q),Z=C.filter.type==="Identifier"?C.filter.value:yt(C.filter);let ce=G+or("filter",Z)+zt;return ce+=Sr(C.body,q+1,R)+zt,ce+=G+or("endfilter"),ce}function yt(C,q=-1){switch(C.type){case"SpreadExpression":return`*${yt(C.argument)}`;case"Identifier":return C.value;case"IntegerLiteral":return`${C.value}`;case"FloatLiteral":return`${C.value}`;case"StringLiteral":return JSON.stringify(C.value);case"BinaryExpression":{const R=C,G=Qs(R),Z=yt(R.left,G),ce=yt(R.right,G+1),ye=`${Z} ${R.operator.value} ${ce}`;return G`${yt(G)}: ${yt(Z)}`).join(", ")}}`;case"SliceExpression":{const R=C,G=R.start?yt(R.start):"",Z=R.stop?yt(R.stop):"",ce=R.step?`:${yt(R.step)}`:"";return`${G}:${Z}${ce}`}case"KeywordArgumentExpression":{const R=C;return`${R.key.value}=${yt(R.value)}`}case"Ternary":{const R=C,G=`${yt(R.trueExpr)} if ${yt(R.condition,0)} else ${yt(R.falseExpr)}`;return q>-1?`(${G})`:G}default:throw new Error(`Unknown expression type: ${C.type}`)}}var Ss=class{parsed;constructor(C){const q=d(C,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ae(q)}render(C){const q=new ot;if(ht(q),C)for(const[Z,ce]of Object.entries(C))q.set(Z,ce);return new gr(q).run(this.parsed).value}format(C){return Xs(this.parsed,C?.indent||" ")}}}),"./src/backends/onnx.js":((e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>_,isONNXProxy:()=>E,isONNXTensor:()=>T,runInferenceSession:()=>I});var n=t("./src/env.js"),o=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),c=[];let p,d;const u=Symbol.for("onnxruntime");if(u in globalThis)d=globalThis[u];else if(n.apis.IS_NODE_ENV){switch(d=o??(s||(s=t.t(o,2))),process.platform){case"win32":c.push("dml");break;case"linux":process.arch==="x64"&&c.push("cuda");break}c.push("cpu"),p=["cpu"]}else d=i,n.apis.IS_WEBNN_AVAILABLE&&c.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),n.apis.IS_WEBGPU_AVAILABLE&&c.push("webgpu"),c.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(x=null){if(!x)return p;switch(x){case"auto":return c;case"gpu":return c.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(c.includes(x))return[l[x]??x];throw new Error(`Unsupported device: "${x}". Should be one of: ${c.join(", ")}.`)}let y=null;async function k(x,S,O){y&&await y;const F=f.create(x,S);y??=F;const H=await F;return H.config=O,H}let w=Promise.resolve();const v=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;async function I(x,S){const O=()=>x.run(S);return await(v?w=w.then(O):O())}function T(x){return x instanceof d.Tensor}const b=d?.env;b?.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!b.wasm.wasmPaths&&(b.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${n.env.version}/dist/`),b.wasm.proxy=!1),b?.webgpu&&(b.webgpu.powerPreference="high-performance");function E(){return b?.wasm?.proxy}n.env.backends.onnx=b}),"./src/base/feature_extraction_utils.js":((e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class i extends n.Callable{constructor(c){super(),this.config=c}static async from_pretrained(c,p={}){const d=await(0,o.getModelJSON)(c,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,c){if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${c} expects input to be a Float32Array or a Float64Array, but got ${l?.constructor?.name??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}}),"./src/base/image_processors_utils.js":((e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>T,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>I,post_process_object_detection:()=>u,post_process_panoptic_segmentation:()=>v,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function c(b,E,x=0,S=null){const O=b/E;let F=(0,o.bankers_round)(O)*E;return S!==null&&F>S&&(F=Math.floor(O)*E),FE&&K.push(D)}else{let D=(0,o.max)(oe.data)[1];if(D===B-1||(N=(0,o.softmax)(oe.data),N[D]he*J[(Ae+1)%2])),re.boxes.push(te),re.classes.push(D),re.scores.push(N[D])}}Y.push(re)}return Y}function f(b,E=null){const x=b.logits,S=x.dims[0];if(E!==null&&E.length!==S)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const O=[];for(let F=0;FJ[K]&&(J[K]=oe[K],re[K]=pe)}const ne=new Array(W.dims[0]);for(let pe=0;pepe!==void 0);O.push({segmentation:X,labels:le})}return O}function _(b,E,x,S){const O=[],F=[],H=[];for(let W=0;Wx&&(O.push(Y),F.push(re),H.push(X))}return[O,F,H]}function y(b,E,x,S=.5,O=.8){const F=[];let H=0,W=0;const B=E[x].data;for(let X=0;X=S&&++W;let Y=H>0&&W>0;return Y&&(Y=H/W>O),[Y,F]}function k(b,E,x,S,O,F=null,H=null){const[W,B]=H??b[0].dims,Y=new n.Tensor("int32",new Int32Array(W*B),[W,B]),X=[];if(H!==null)for(let pe=0;pere[N]&&(J[N]=pe,re[N]=K[N])}let ne=0;const le=Y.data;for(let pe=0;pe200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(b,E)/Math.min(b,E)}`);let F=Math.round(b/x)*x,H=Math.round(E/x)*x;if(F*H>O){const W=Math.sqrt(b*E/O);F=Math.floor(b/W/x)*x,H=Math.floor(E/W/x)*x}else if(F*HF?Y=Math.floor(F*B/O):F>O&&(B=Math.floor(O*Y/F)),await E.resize(Y,B,{resample:S}))}async crop_margin(E,x=200){const S=E.clone().grayscale(),O=(0,o.min)(S.data)[0],H=(0,o.max)(S.data)[0]-O;if(H===0)return E;const W=x/255;let B=S.width,Y=S.height,X=0,J=0;const re=S.data;for(let ne=0;nethis.preprocess(F)));return{pixel_values:(0,n.stack)(S.map(F=>F.pixel_values),0),original_sizes:S.map(F=>F.original_size),reshaped_input_sizes:S.map(F=>F.reshaped_input_size)}}static async from_pretrained(E,x={}){const S=await(0,a.getModelJSON)(E,l.IMAGE_PROCESSOR_NAME,!0,x);return new this(S)}}}),"./src/base/processing_utils.js":((e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class i extends n.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(l,c,p){super(),this.config=l,this.components=c,this.chat_template=p}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,c={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,chat_template:this.chat_template??void 0,...c})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...c){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...c);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,c={}){const[p,d,u]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(l,s.PROCESSOR_NAME,!0,c):{},Promise.all(this.classes.filter(f=>f in this).map(async f=>{const _=await this[f].from_pretrained(l,c);return[f.replace(/_class$/,""),_]})).then(Object.fromEntries),this.uses_chat_template_file?(0,o.getModelText)(l,s.CHAT_TEMPLATE_NAME,!0,c):null]);return new this(p,d,u)}}}),"./src/configs.js":((e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>p,PretrainedConfig:()=>c,getCacheShapes:()=>a});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js");async function o(d,u){return await(0,n.getModelJSON)(d,"config.json",!0,u)}function i(d){const u={};let f={};switch(d.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"mistral3":f=i(d.text_config);break;case"moondream1":f=i(d.phi_config);break;case"musicgen":f=i(d.decoder);break;case"multi_modality":f=i(d.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"llama4_text":case"nanochat":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads",u.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"ministral":case"ministral3":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const y=i(d.decoder),k="num_decoder_layers"in y,w=(0,s.pick)(d,["model_type","is_encoder_decoder"]);return k?(w.num_decoder_layers=y.num_decoder_layers,w.num_decoder_heads=y.num_decoder_heads,w.decoder_hidden_size=y.decoder_hidden_size,w.num_encoder_layers=y.num_encoder_layers,w.num_encoder_heads=y.num_encoder_heads,w.encoder_hidden_size=y.encoder_hidden_size):(w.num_layers=y.num_layers,w.num_heads=y.num_heads,w.hidden_size=y.hidden_size),w}const _={...f,...(0,s.pick)(d,["model_type","multi_query","is_encoder_decoder"])};for(const y in u)_[y]=d[u[y]];return _}function a(d,u){if(d.model_type==="lfm2"){const f=u?.prefix??"past_key_values",_=f==="present"?"present":"past",y={},{layer_types:k,num_attention_heads:w,num_key_value_heads:v,hidden_size:I,conv_L_cache:T}=d,b=I/w,E=u?.batch_size??1;for(let x=0;x{t.r(r),t.d(r,{apis:()=>w,env:()=>x});var s=t("?db59"),n=t("?383f"),o=t("?fa4b");const i="3.8.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),c=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,u=typeof process<"u",f=u&&process?.release?.name==="node",_=!S(s),y=!S(n),k=typeof globalThis.Deno<"u",w=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:c,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:y}),v=_&&y;let I="./";if(v){const O=Object(import.meta).url;O?I=n.dirname(n.dirname(o.fileURLToPath(O))):typeof __dirname<"u"&&(I=n.dirname(__dirname))}const T=v?n.join(I,"/.cache/"):null,b="/models/",E=v?n.join(I,b):b,x={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:E,useFS:_,useBrowserCache:c&&!k,useFSCache:_,cacheDir:T,useCustomCache:!1,customCache:null};function S(O){return Object.keys(O).length===0}}),"./src/generation/configuration_utils.js":((e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>n});var s=t("./src/utils/core.js");class n{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(i){Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}}),"./src/generation/logits_process.js":((e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>y,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>u,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>v,TopKLogitsWarper:()=>T,TopPLogitsWarper:()=>I,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var n=t("./src/utils/maths.js");class o extends s.Callable{_call(E,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(E,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(E){this.processors.push(E)}extend(E){this.processors.push(...E)}_call(E,x){let S=x;for(const O of this.processors)S=O(E,S);return S}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(E){super(),this.bos_token_id=E}_call(E,x){for(let S=0;S=1&&F[F.length-1]>=this.timestamp_begin,W=F.length<2||F[F.length-2]>=this.timestamp_begin;if(H&&(W?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),E[S].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(J+1).fill(-1/0)}const B=(0,n.log_softmax)(O),Y=Math.log(B.subarray(this.timestamp_begin).map(Math.exp).reduce((J,re)=>J+re)),X=(0,n.max)(B.subarray(0,this.timestamp_begin))[0];Y>X&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class u extends o{constructor(E){super(),this.no_repeat_ngram_size=E}getNgrams(E){const x=E.length,S=[];for(let F=0;F1 to use the classifier free guidance processor, got guidance scale ${E}.`);this.guidance_scale=E}_call(E,x){if(x.dims[0]!==2*E.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${x.dims[0]} for the logits and ${E.length} for the input ids.`);const S=E.length,O=x.slice([0,S],null),F=x.slice([S,x.dims[0]],null);for(let H=0;H1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${E}`);if(!Number.isInteger(S)||S<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${S}`);this.top_p=E,this.filter_value=x,this.min_tokens_to_keep=S}}class T extends i{constructor(E,{filter_value:x=-1/0,min_tokens_to_keep:S=1}={}){if(super(),!Number.isInteger(E)||E<0)throw new Error(`\`top_k\` must be a positive integer, but is ${E}`);this.top_k=Math.max(E,S),this.filter_value=x}}}),"./src/generation/logits_sampler.js":((e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,u){let f=d.dims.at(-1),_=d.data;if(u===-1)_=_.slice(-f);else{let y=u*f;_=_.slice(y,y+f)}return _}randomSelect(d){let u=0;for(let _=0;_1)return new c(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const u=(0,o.max)(d.data)[1];return[[BigInt(u),0]]}}class l extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,n.topk)(d,u),y=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(y);return[_.data[k],Math.log(y[k])]})}}class c extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,n.topk)(d,u),y=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[_.data[w],Math.log(y[w])])}}}),"./src/generation/stopping_criteria.js":((e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>n,StoppingCriteriaList:()=>o});var s=t("./src/utils/generic.js");class n extends s.Callable{_call(p,d){throw Error("StoppingCriteria needs to be subclassed")}}class o extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof o?p=p.criteria:p instanceof n&&(p=[p]),this.criteria.push(...p)}_call(p,d){const u=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let y=0;yd.length>=this.max_length)}}class a extends n{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(u=>{const f=u.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends n{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}}),"./src/generation/streamers.js":((e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var s=t("./src/utils/core.js"),n=t("./src/tokenizers.js"),o=t("./src/env.js");class i{put(d){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=o.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:y=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=u,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:y,...k,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const u=this.next_tokens_are_prompt;if(u&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];this.token_callback_function?.(f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let y;u||_.endsWith(` `)?(y=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,n.is_chinese_char)(_.charCodeAt(_.length-1))?(y=_.slice(this.print_len),this.print_len+=y.length):(y=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=y.length),this.on_finalized_text(y,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,u){d.length>0&&this.callback_function?.(d),u&&this.callback_function===a&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` -`)}}class c extends l{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:y=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:v=.02,skip_special_tokens:I=!0,decode_kwargs:T={}}={}){super(d,{skip_prompt:u,skip_special_tokens:I,callback_function:f,token_callback_function:_,decode_kwargs:T}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=y,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=v,this.waiting_for_timestamp=!1}put(d){if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const u=d[0];if(u.length===1){const f=Number(u[0])-this.timestamp_begin;if(f>=0){const _=f*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(_):this.on_chunk_start?.(_),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(u);return}}return super.put(d)}end(){super.end(),this.on_finalize?.()}}}),"./src/models.js":((e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Mo,ASTModel:()=>go,ASTPreTrainedModel:()=>fo,AlbertForMaskedLM:()=>Ke,AlbertForQuestionAnswering:()=>Ye,AlbertForSequenceClassification:()=>Je,AlbertModel:()=>Xe,AlbertPreTrainedModel:()=>$e,ArceeForCausalLM:()=>Gu,ArceeModel:()=>Wu,ArceePreTrainedModel:()=>yi,AutoModel:()=>Bv,AutoModelForAudioClassification:()=>sx,AutoModelForAudioFrameClassification:()=>ox,AutoModelForAudioTextToText:()=>hx,AutoModelForCTC:()=>rx,AutoModelForCausalLM:()=>Gv,AutoModelForDepthEstimation:()=>cx,AutoModelForDocumentQuestionAnswering:()=>ax,AutoModelForImageClassification:()=>Qv,AutoModelForImageFeatureExtraction:()=>px,AutoModelForImageMatting:()=>ix,AutoModelForImageSegmentation:()=>Xv,AutoModelForImageTextToText:()=>mx,AutoModelForImageToImage:()=>lx,AutoModelForMaskGeneration:()=>tx,AutoModelForMaskedLM:()=>Kv,AutoModelForNormalEstimation:()=>ux,AutoModelForObjectDetection:()=>Zv,AutoModelForPoseEstimation:()=>dx,AutoModelForQuestionAnswering:()=>Hv,AutoModelForSemanticSegmentation:()=>Jv,AutoModelForSeq2SeqLM:()=>jv,AutoModelForSequenceClassification:()=>Rv,AutoModelForSpeechSeq2Seq:()=>Vv,AutoModelForTextToSpectrogram:()=>Uv,AutoModelForTextToWaveform:()=>Wv,AutoModelForTokenClassification:()=>Nv,AutoModelForUniversalSegmentation:()=>Yv,AutoModelForVision2Seq:()=>qv,AutoModelForXVector:()=>nx,AutoModelForZeroShotObjectDetection:()=>ex,BartForConditionalGeneration:()=>Yt,BartForSequenceClassification:()=>hr,BartModel:()=>ds,BartPretrainedModel:()=>Er,BaseModelOutput:()=>be,BeitForImageClassification:()=>mp,BeitModel:()=>pp,BeitPreTrainedModel:()=>el,BertForMaskedLM:()=>Ce,BertForQuestionAnswering:()=>fe,BertForSequenceClassification:()=>ge,BertForTokenClassification:()=>De,BertModel:()=>xe,BertPreTrainedModel:()=>ve,BlenderbotForConditionalGeneration:()=>_r,BlenderbotModel:()=>Zt,BlenderbotPreTrainedModel:()=>vr,BlenderbotSmallForConditionalGeneration:()=>Js,BlenderbotSmallModel:()=>Ur,BlenderbotSmallPreTrainedModel:()=>lr,BloomForCausalLM:()=>Dd,BloomModel:()=>Od,BloomPreTrainedModel:()=>Vi,CLIPModel:()=>vo,CLIPPreTrainedModel:()=>Ls,CLIPSegForImageSegmentation:()=>Co,CLIPSegModel:()=>Po,CLIPSegPreTrainedModel:()=>fn,CLIPTextModel:()=>va,CLIPTextModelWithProjection:()=>xo,CLIPVisionModel:()=>xa,CLIPVisionModelWithProjection:()=>Ta,CamembertForMaskedLM:()=>ce,CamembertForQuestionAnswering:()=>ut,CamembertForSequenceClassification:()=>ye,CamembertForTokenClassification:()=>et,CamembertModel:()=>Z,CamembertPreTrainedModel:()=>G,CausalLMOutput:()=>rn,CausalLMOutputWithPast:()=>fx,ChineseCLIPModel:()=>Eo,ChineseCLIPPreTrainedModel:()=>Ea,ClapAudioModelWithProjection:()=>$h,ClapModel:()=>Sh,ClapPreTrainedModel:()=>Oa,ClapTextModelWithProjection:()=>Ih,CodeGenForCausalLM:()=>Be,CodeGenModel:()=>Pe,CodeGenPreTrainedModel:()=>ie,CohereForCausalLM:()=>md,CohereModel:()=>pd,CoherePreTrainedModel:()=>Ai,ConvBertForMaskedLM:()=>ft,ConvBertForQuestionAnswering:()=>Cs,ConvBertForSequenceClassification:()=>qt,ConvBertForTokenClassification:()=>Ps,ConvBertModel:()=>Bs,ConvBertPreTrainedModel:()=>Qr,ConvNextForImageClassification:()=>im,ConvNextModel:()=>am,ConvNextPreTrainedModel:()=>_l,ConvNextV2ForImageClassification:()=>cm,ConvNextV2Model:()=>lm,ConvNextV2PreTrainedModel:()=>fl,DFineForObjectDetection:()=>Pp,DFineModel:()=>Ep,DFinePreTrainedModel:()=>al,DINOv3ConvNextModel:()=>gm,DINOv3ConvNextPreTrainedModel:()=>fm,DINOv3ViTModel:()=>_m,DINOv3ViTPreTrainedModel:()=>hm,DPTForDepthEstimation:()=>Vp,DPTModel:()=>jp,DPTPreTrainedModel:()=>pl,DacDecoderModel:()=>M_,DacDecoderOutput:()=>__,DacEncoderModel:()=>g_,DacEncoderOutput:()=>h_,DacModel:()=>f_,DacPreTrainedModel:()=>ja,DebertaForMaskedLM:()=>qe,DebertaForQuestionAnswering:()=>Mr,DebertaForSequenceClassification:()=>Tt,DebertaForTokenClassification:()=>kt,DebertaModel:()=>Mt,DebertaPreTrainedModel:()=>He,DebertaV2ForMaskedLM:()=>Tr,DebertaV2ForQuestionAnswering:()=>$s,DebertaV2ForSequenceClassification:()=>Is,DebertaV2ForTokenClassification:()=>Dr,DebertaV2Model:()=>ar,DebertaV2PreTrainedModel:()=>dr,DecisionTransformerModel:()=>Jh,DecisionTransformerPreTrainedModel:()=>Xh,DeiTForImageClassification:()=>kp,DeiTModel:()=>$p,DeiTPreTrainedModel:()=>ll,DepthAnythingForDepthEstimation:()=>Wp,DepthAnythingPreTrainedModel:()=>Up,DepthProForDepthEstimation:()=>Qp,DepthProPreTrainedModel:()=>qp,DetrForObjectDetection:()=>_p,DetrForSegmentation:()=>tl,DetrModel:()=>hp,DetrObjectDetectionOutput:()=>rl,DetrPreTrainedModel:()=>Ca,DetrSegmentationOutput:()=>fp,Dinov2ForImageClassification:()=>dm,Dinov2Model:()=>um,Dinov2PreTrainedModel:()=>gl,Dinov2WithRegistersForImageClassification:()=>mm,Dinov2WithRegistersModel:()=>pm,Dinov2WithRegistersPreTrainedModel:()=>Ml,DistilBertForMaskedLM:()=>Hr,DistilBertForQuestionAnswering:()=>ir,DistilBertForSequenceClassification:()=>ts,DistilBertForTokenClassification:()=>wr,DistilBertModel:()=>zr,DistilBertPreTrainedModel:()=>Lr,DonutSwinModel:()=>om,DonutSwinPreTrainedModel:()=>nm,EdgeTamModel:()=>Sm,EfficientNetForImageClassification:()=>zh,EfficientNetModel:()=>Lh,EfficientNetPreTrainedModel:()=>Al,ElectraForMaskedLM:()=>Ss,ElectraForQuestionAnswering:()=>R,ElectraForSequenceClassification:()=>C,ElectraForTokenClassification:()=>q,ElectraModel:()=>yt,ElectraPreTrainedModel:()=>Kr,Ernie4_5ForCausalLM:()=>xh,Ernie4_5Model:()=>vh,Ernie4_5PreTrainedModel:()=>Cl,EsmForMaskedLM:()=>ks,EsmForSequenceClassification:()=>As,EsmForTokenClassification:()=>Fs,EsmModel:()=>Rs,EsmPreTrainedModel:()=>rs,ExaoneForCausalLM:()=>td,ExaoneModel:()=>ed,ExaonePreTrainedModel:()=>Pi,FalconForCausalLM:()=>Ch,FalconModel:()=>Ph,FalconPreTrainedModel:()=>Il,FastViTForImageClassification:()=>tp,FastViTModel:()=>ep,FastViTPreTrainedModel:()=>Qi,Florence2ForConditionalGeneration:()=>Ma,Florence2PreTrainedModel:()=>ga,GLPNForDepthEstimation:()=>sm,GLPNModel:()=>rm,GLPNPreTrainedModel:()=>hl,GPT2LMHeadModel:()=>So,GPT2Model:()=>Kn,GPT2PreTrainedModel:()=>Gn,GPTBigCodeForCausalLM:()=>V,GPTBigCodeModel:()=>L,GPTBigCodePreTrainedModel:()=>A,GPTJForCausalLM:()=>P,GPTJModel:()=>h,GPTJPreTrainedModel:()=>Xn,GPTNeoForCausalLM:()=>$o,GPTNeoModel:()=>qn,GPTNeoPreTrainedModel:()=>Mn,GPTNeoXForCausalLM:()=>Ao,GPTNeoXModel:()=>ko,GPTNeoXPreTrainedModel:()=>Qn,Gemma2ForCausalLM:()=>gd,Gemma2Model:()=>fd,Gemma2PreTrainedModel:()=>Oi,Gemma3ForCausalLM:()=>yd,Gemma3Model:()=>bd,Gemma3PreTrainedModel:()=>Li,Gemma3nForConditionalGeneration:()=>Nn,Gemma3nPreTrainedModel:()=>en,GemmaForCausalLM:()=>_d,GemmaModel:()=>hd,GemmaPreTrainedModel:()=>Fi,GlmForCausalLM:()=>Zu,GlmModel:()=>Yu,GlmPreTrainedModel:()=>Ei,GraniteForCausalLM:()=>cd,GraniteModel:()=>ld,GraniteMoeHybridForCausalLM:()=>dd,GraniteMoeHybridModel:()=>ud,GraniteMoeHybridPreTrainedModel:()=>ki,GranitePreTrainedModel:()=>$i,GroundingDinoForObjectDetection:()=>wm,GroundingDinoPreTrainedModel:()=>Mm,GroupViTModel:()=>Zd,GroupViTPreTrainedModel:()=>Yd,HeliumForCausalLM:()=>Ju,HeliumModel:()=>Xu,HeliumPreTrainedModel:()=>Ti,HieraForImageClassification:()=>Fp,HieraModel:()=>Ap,HieraPreTrainedModel:()=>cl,HubertForCTC:()=>th,HubertForSequenceClassification:()=>rh,HubertModel:()=>eh,HubertPreTrainedModel:()=>Ev,IJepaForImageClassification:()=>Ud,IJepaModel:()=>Vd,IJepaPreTrainedModel:()=>Ki,Idefics3ForConditionalGeneration:()=>jn,Idefics3PreTrainedModel:()=>ya,ImageMattingOutput:()=>Q_,JAISLMHeadModel:()=>gn,JAISModel:()=>Io,JAISPreTrainedModel:()=>Hn,JinaCLIPModel:()=>hn,JinaCLIPPreTrainedModel:()=>mn,JinaCLIPTextModel:()=>Jr,JinaCLIPVisionModel:()=>_n,Lfm2ForCausalLM:()=>Hu,Lfm2Model:()=>Ku,Lfm2PreTrainedModel:()=>vi,LiteWhisperForConditionalGeneration:()=>ha,Llama4ForCausalLM:()=>Vt,Llama4PreTrainedModel:()=>Ot,LlamaForCausalLM:()=>vt,LlamaModel:()=>at,LlamaPreTrainedModel:()=>Qe,LlavaForConditionalGeneration:()=>Rn,LlavaOnevisionForConditionalGeneration:()=>_a,LlavaPreTrainedModel:()=>bo,LlavaQwen2ForCausalLM:()=>yo,LongT5ForConditionalGeneration:()=>sr,LongT5Model:()=>Xt,LongT5PreTrainedModel:()=>br,M2M100ForConditionalGeneration:()=>Fm,M2M100Model:()=>Am,M2M100PreTrainedModel:()=>yl,MBartForCausalLM:()=>os,MBartForConditionalGeneration:()=>ps,MBartForSequenceClassification:()=>yr,MBartModel:()=>Xr,MBartPreTrainedModel:()=>Ir,MPNetForMaskedLM:()=>Os,MPNetForQuestionAnswering:()=>ue,MPNetForSequenceClassification:()=>js,MPNetForTokenClassification:()=>Dn,MPNetModel:()=>Ns,MPNetPreTrainedModel:()=>Kt,MT5ForConditionalGeneration:()=>ns,MT5Model:()=>qr,MT5PreTrainedModel:()=>Ht,MarianMTModel:()=>km,MarianModel:()=>$m,MarianPreTrainedModel:()=>bl,MaskFormerForInstanceSegmentation:()=>tm,MaskFormerModel:()=>em,MaskFormerPreTrainedModel:()=>ml,MaskedLMOutput:()=>$r,Metric3DForDepthEstimation:()=>Jp,Metric3DPreTrainedModel:()=>Xp,Metric3Dv2ForDepthEstimation:()=>Zp,Metric3Dv2PreTrainedModel:()=>Yp,MgpstrForSceneTextRecognition:()=>r_,MgpstrModelOutput:()=>e_,MgpstrPreTrainedModel:()=>t_,MimiDecoderModel:()=>m_,MimiDecoderOutput:()=>u_,MimiEncoderModel:()=>p_,MimiEncoderOutput:()=>c_,MimiModel:()=>d_,MimiPreTrainedModel:()=>Na,Ministral3ForCausalLM:()=>yh,Ministral3Model:()=>bh,Ministral3PreTrainedModel:()=>Pl,MinistralForCausalLM:()=>wh,MinistralModel:()=>Mh,MinistralPreTrainedModel:()=>El,Mistral3ForConditionalGeneration:()=>un,MistralForCausalLM:()=>gh,MistralModel:()=>fh,MistralPreTrainedModel:()=>Tl,MobileBertForMaskedLM:()=>ze,MobileBertForQuestionAnswering:()=>nt,MobileBertForSequenceClassification:()=>Ue,MobileBertModel:()=>Nr,MobileBertPreTrainedModel:()=>ss,MobileLLMForCausalLM:()=>sd,MobileLLMModel:()=>rd,MobileLLMPreTrainedModel:()=>Ci,MobileNetV1ForImageClassification:()=>Rh,MobileNetV1ForSemanticSegmentation:()=>Nh,MobileNetV1Model:()=>Bh,MobileNetV1PreTrainedModel:()=>La,MobileNetV2ForImageClassification:()=>Vh,MobileNetV2ForSemanticSegmentation:()=>Uh,MobileNetV2Model:()=>jh,MobileNetV2PreTrainedModel:()=>za,MobileNetV3ForImageClassification:()=>Gh,MobileNetV3ForSemanticSegmentation:()=>Kh,MobileNetV3Model:()=>Wh,MobileNetV3PreTrainedModel:()=>Ba,MobileNetV4ForImageClassification:()=>qh,MobileNetV4ForSemanticSegmentation:()=>Qh,MobileNetV4Model:()=>Hh,MobileNetV4PreTrainedModel:()=>Ra,MobileViTForImageClassification:()=>op,MobileViTModel:()=>np,MobileViTPreTrainedModel:()=>Xi,MobileViTV2ForImageClassification:()=>ip,MobileViTV2Model:()=>ap,MobileViTV2PreTrainedModel:()=>Ji,ModelOutput:()=>de,ModernBertDecoderForCausalLM:()=>gr,ModernBertDecoderModel:()=>It,ModernBertDecoderPreTrainedModel:()=>Rt,ModernBertForMaskedLM:()=>Oe,ModernBertForSequenceClassification:()=>ot,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>Ne,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>fa,MoonshineForConditionalGeneration:()=>zn,MoonshineModel:()=>bi,MoonshinePreTrainedModel:()=>wo,MptForCausalLM:()=>zd,MptModel:()=>Ld,MptPreTrainedModel:()=>Ui,MultiModalityCausalLM:()=>Zh,MultiModalityPreTrainedModel:()=>Yh,MusicgenForCausalLM:()=>Iv,MusicgenForConditionalGeneration:()=>Ol,MusicgenModel:()=>Sv,MusicgenPreTrainedModel:()=>Fl,NanoChatForCausalLM:()=>Pa,NanoChatModel:()=>Us,NanoChatPreTrainedModel:()=>xr,NeoBertForMaskedLM:()=>Fe,NeoBertForQuestionAnswering:()=>rt,NeoBertForSequenceClassification:()=>tt,NeoBertForTokenClassification:()=>Re,NeoBertModel:()=>We,NeoBertPreTrainedModel:()=>Ee,NomicBertModel:()=>zt,NomicBertPreTrainedModel:()=>Or,OPTForCausalLM:()=>Rd,OPTModel:()=>Bd,OPTPreTrainedModel:()=>Wi,Olmo2ForCausalLM:()=>id,Olmo2Model:()=>ad,Olmo2PreTrainedModel:()=>Ii,OlmoForCausalLM:()=>od,OlmoModel:()=>nd,OlmoPreTrainedModel:()=>Si,OpenELMForCausalLM:()=>xd,OpenELMModel:()=>vd,OpenELMPreTrainedModel:()=>zi,OwlViTForObjectDetection:()=>cp,OwlViTModel:()=>lp,OwlViTPreTrainedModel:()=>Yi,Owlv2ForObjectDetection:()=>dp,Owlv2Model:()=>up,Owlv2PreTrainedModel:()=>Zi,PaliGemmaForConditionalGeneration:()=>ba,PaliGemmaPreTrainedModel:()=>wa,ParakeetForCTC:()=>Rm,ParakeetPreTrainedModel:()=>Bm,PatchTSMixerForPrediction:()=>a_,PatchTSMixerModel:()=>o_,PatchTSMixerPreTrainedModel:()=>Ll,PatchTSTForPrediction:()=>n_,PatchTSTModel:()=>s_,PatchTSTPreTrainedModel:()=>Dl,Phi3ForCausalLM:()=>Fd,Phi3Model:()=>Ad,Phi3PreTrainedModel:()=>ji,Phi3VForCausalLM:()=>Un,Phi3VPreTrainedModel:()=>Vn,PhiForCausalLM:()=>kd,PhiModel:()=>$d,PhiPreTrainedModel:()=>Ni,PreTrainedModel:()=>z,PretrainedMixin:()=>Ut,PvtForImageClassification:()=>Hd,PvtModel:()=>Kd,PvtPreTrainedModel:()=>Hi,PyAnnoteForAudioFrameClassification:()=>jm,PyAnnoteModel:()=>Nm,PyAnnotePreTrainedModel:()=>vl,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>Ed,Qwen2Model:()=>Td,Qwen2PreTrainedModel:()=>Bi,Qwen2VLForConditionalGeneration:()=>Id,Qwen2VLPreTrainedModel:()=>Sd,Qwen3ForCausalLM:()=>Cd,Qwen3Model:()=>Pd,Qwen3PreTrainedModel:()=>Ri,RFDetrForObjectDetection:()=>xp,RFDetrModel:()=>vp,RFDetrObjectDetectionOutput:()=>Tp,RFDetrPreTrainedModel:()=>ol,RTDetrForObjectDetection:()=>Mp,RTDetrModel:()=>gp,RTDetrObjectDetectionOutput:()=>Fo,RTDetrPreTrainedModel:()=>sl,RTDetrV2ForObjectDetection:()=>bp,RTDetrV2Model:()=>wp,RTDetrV2ObjectDetectionOutput:()=>yp,RTDetrV2PreTrainedModel:()=>nl,ResNetForImageClassification:()=>Dp,ResNetModel:()=>Op,ResNetPreTrainedModel:()=>ul,RoFormerForMaskedLM:()=>Qs,RoFormerForQuestionAnswering:()=>Sr,RoFormerForSequenceClassification:()=>Xs,RoFormerForTokenClassification:()=>or,RoFormerModel:()=>qs,RoFormerPreTrainedModel:()=>Rr,RobertaForMaskedLM:()=>ra,RobertaForQuestionAnswering:()=>oa,RobertaForSequenceClassification:()=>sa,RobertaForTokenClassification:()=>na,RobertaModel:()=>po,RobertaPreTrainedModel:()=>Ds,Sam2ImageSegmentationOutput:()=>Pm,Sam2Model:()=>$a,Sam2PreTrainedModel:()=>Cm,Sam3TrackerModel:()=>Im,SamImageSegmentationOutput:()=>Em,SamModel:()=>Tm,SamPreTrainedModel:()=>xm,SapiensForDepthEstimation:()=>Kp,SapiensForNormalEstimation:()=>Hp,SapiensForSemanticSegmentation:()=>Gp,SapiensPreTrainedModel:()=>Ia,SegformerForImageClassification:()=>Ah,SegformerForSemanticSegmentation:()=>Fh,SegformerModel:()=>Cv,SegformerPreTrainedModel:()=>Da,Seq2SeqLMOutput:()=>_x,SequenceClassifierOutput:()=>xt,SiglipModel:()=>To,SiglipPreTrainedModel:()=>Wn,SiglipTextModel:()=>pn,SiglipVisionModel:()=>dt,SmolLM3ForCausalLM:()=>Qu,SmolLM3Model:()=>qu,SmolLM3PreTrainedModel:()=>xi,SmolVLMForConditionalGeneration:()=>dn,SnacDecoderModel:()=>y_,SnacEncoderModel:()=>b_,SnacModel:()=>w_,SnacPreTrainedModel:()=>Va,SpeechT5ForSpeechToText:()=>uh,SpeechT5ForTextToSpeech:()=>dh,SpeechT5HifiGan:()=>ph,SpeechT5Model:()=>Pv,SpeechT5PreTrainedModel:()=>Fa,SqueezeBertForMaskedLM:()=>ee,SqueezeBertForQuestionAnswering:()=>Me,SqueezeBertForSequenceClassification:()=>se,SqueezeBertModel:()=>U,SqueezeBertPreTrainedModel:()=>$,StableLmForCausalLM:()=>Dh,StableLmModel:()=>Oh,StableLmPreTrainedModel:()=>kl,Starcoder2ForCausalLM:()=>Eh,Starcoder2Model:()=>Th,Starcoder2PreTrainedModel:()=>Sl,StyleTextToSpeech2Model:()=>ch,StyleTextToSpeech2PreTrainedModel:()=>lh,SupertonicForConditionalGeneration:()=>xl,SupertonicPreTrainedModel:()=>mh,Swin2SRForImageSuperResolution:()=>Np,Swin2SRModel:()=>Rp,Swin2SRPreTrainedModel:()=>dl,SwinForImageClassification:()=>zp,SwinForSemanticSegmentation:()=>Bp,SwinModel:()=>Lp,SwinPreTrainedModel:()=>Sa,T5ForConditionalGeneration:()=>rr,T5Model:()=>Et,T5PreTrainedModel:()=>$t,TableTransformerForObjectDetection:()=>Sp,TableTransformerModel:()=>Cp,TableTransformerObjectDetectionOutput:()=>Ip,TableTransformerPreTrainedModel:()=>il,TokenClassifierOutput:()=>Pr,TrOCRForCausalLM:()=>_h,TrOCRPreTrainedModel:()=>hh,UltravoxModel:()=>zl,UltravoxPreTrainedModel:()=>i_,UniSpeechForCTC:()=>Gm,UniSpeechForSequenceClassification:()=>Km,UniSpeechModel:()=>Wm,UniSpeechPreTrainedModel:()=>ka,UniSpeechSatForAudioFrameClassification:()=>Xm,UniSpeechSatForCTC:()=>qm,UniSpeechSatForSequenceClassification:()=>Qm,UniSpeechSatModel:()=>Hm,UniSpeechSatPreTrainedModel:()=>Oo,VaultGemmaForCausalLM:()=>wd,VaultGemmaModel:()=>Md,VaultGemmaPreTrainedModel:()=>Di,ViTForImageClassification:()=>jd,ViTMAEModel:()=>Qd,ViTMAEPreTrainedModel:()=>qd,ViTMSNForImageClassification:()=>Jd,ViTMSNModel:()=>Xd,ViTMSNPreTrainedModel:()=>qi,ViTModel:()=>Nd,ViTPreTrainedModel:()=>Gi,VisionEncoderDecoderModel:()=>Bn,VitMatteForImageMatting:()=>sp,VitMattePreTrainedModel:()=>rp,VitPoseForPoseEstimation:()=>Gd,VitPosePreTrainedModel:()=>Wd,VitsModel:()=>$l,VitsModelOutput:()=>X_,VitsPreTrainedModel:()=>kh,VoxtralForConditionalGeneration:()=>l_,Wav2Vec2BertForCTC:()=>Ym,Wav2Vec2BertForSequenceClassification:()=>Zm,Wav2Vec2BertModel:()=>Jm,Wav2Vec2BertPreTrainedModel:()=>Aa,Wav2Vec2ForAudioFrameClassification:()=>zm,Wav2Vec2ForCTC:()=>Dm,Wav2Vec2ForSequenceClassification:()=>Lm,Wav2Vec2Model:()=>Om,Wav2Vec2PreTrainedModel:()=>tn,WavLMForAudioFrameClassification:()=>ih,WavLMForCTC:()=>nh,WavLMForSequenceClassification:()=>oh,WavLMForXVector:()=>ah,WavLMModel:()=>sh,WavLMPreTrainedModel:()=>Jn,WeSpeakerResNetModel:()=>Um,WeSpeakerResNetPreTrainedModel:()=>Vm,WhisperForConditionalGeneration:()=>Ln,WhisperModel:()=>ma,WhisperPreTrainedModel:()=>Vs,XLMForQuestionAnswering:()=>ua,XLMForSequenceClassification:()=>la,XLMForTokenClassification:()=>ca,XLMModel:()=>aa,XLMPreTrainedModel:()=>Ys,XLMRobertaForMaskedLM:()=>mo,XLMRobertaForQuestionAnswering:()=>pa,XLMRobertaForSequenceClassification:()=>ho,XLMRobertaForTokenClassification:()=>_o,XLMRobertaModel:()=>da,XLMRobertaPreTrainedModel:()=>Zs,XLMWithLMHeadModel:()=>ia,XVectorOutput:()=>q_,YolosForObjectDetection:()=>ym,YolosModel:()=>bm,YolosObjectDetectionOutput:()=>vm,YolosPreTrainedModel:()=>wl});var s=t("./src/configs.js"),n=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),u=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),y=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),v=t("./src/models/whisper/generation_whisper.js"),I=t("./src/models/whisper/common_whisper.js");const T={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,Supertonic:13},b=new Map,E=new Map,x=new Map;async function S(g,M,j){let ae=j.config?.["transformers.js_config"]??{},me=j.device??ae.device;me&&typeof me!="string"&&(me.hasOwnProperty(M)?me=me[M]:(console.warn(`device not specified for "${M}". Using the default device.`),me=null));const _e=me??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,n.deviceToExecutionProviders)(_e),Le=ae.device_config??{};Le.hasOwnProperty(_e)&&(ae={...ae,...Le[_e]});let Ge=j.dtype??ae.dtype;if(typeof Ge!="string"&&(Ge&&Ge.hasOwnProperty(M)?Ge=Ge[M]:(Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${M}". Using the default dtype (${Ge}) for this device (${_e}).`))),Ge===o.DATA_TYPES.auto){let At=ae.dtype;typeof At!="string"&&(At=At?.[M]),At&&At!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(At)?Ge=At:Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32}const st=Ge;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(st)){if(st===o.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${st}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const wt=ae.kv_cache_dtype,bt=wt?typeof wt=="string"?wt:wt[st]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const Pt={dtype:st,kv_cache_dtype:bt,device:_e},mt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[st],Lt=`${M}${mt}.onnx`,_t=`${j.subfolder??""}/${Lt}`,pt={...j.session_options};pt.executionProviders??=Se;const Ft=ae.free_dimension_overrides;Ft?pt.freeDimensionOverrides??=Ft:_e.startsWith("webnn")&&!pt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${_e}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Wt=w.apis.IS_NODE_ENV&&w.env.useFSCache,er=(0,l.getModelFile)(g,_t,!0,j,Wt),nr=j.use_external_data_format??ae.use_external_data_format;let pr=[];if(nr){let At;typeof nr=="object"?nr.hasOwnProperty(Lt)?At=nr[Lt]:nr.hasOwnProperty(M)?At=nr[M]:At=!1:At=nr;const cr=+At;if(cr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${cr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let kr=0;kr{const eo=await(0,l.getModelFile)(g,Wr,!0,j,Wt);ms(eo instanceof Uint8Array?{path:wn,data:eo}:wn)}))}}else pt.externalData!==void 0&&(pr=pt.externalData.map(async At=>{if(typeof At.data=="string"){const cr=await(0,l.getModelFile)(g,At.data,!0,j);return{...At,data:cr}}return At}));if(pr.length>0){const At=await Promise.all(pr);w.apis.IS_NODE_ENV||(pt.externalData=At)}if(_e==="webgpu"){const At=(0,s.getCacheShapes)(j.config,{prefix:"present"});if(Object.keys(At).length>0&&!(0,n.isONNXProxy)()){const cr={};for(const kr in At)cr[kr]="gpu-buffer";pt.preferredOutputLocation=cr}}return{buffer_or_path:await er,session_options:pt,session_config:Pt}}async function O(g,M,j){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const{buffer_or_path:me,session_options:_e,session_config:Se}=await S(g,M[ae],j),Le=await(0,n.createInferenceSession)(me,_e,Se);return[ae,Le]})))}async function F(g,M,j){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const me=await(0,l.getModelJSON)(g,M[ae],!1,j);return[ae,me]})))}function H(g,M){const j=Object.create(null),ae=[];for(const Se of g.inputNames){const Le=M[Se];if(!(Le instanceof u.Tensor)){ae.push(Se);continue}j[Se]=(0,n.isONNXProxy)()?Le.clone():Le}if(ae.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ae.join(", ")}.`);const me=Object.keys(M).length,_e=g.inputNames.length;if(me>_e){let Se=Object.keys(M).filter(Le=>!g.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${me} > ${_e}). The following inputs will be ignored: "${Se.join(", ")}".`)}return j}async function W(g,M){const j=H(g,M);try{const ae=Object.fromEntries(Object.entries(j).map(([_e,Se])=>[_e,Se.ort_tensor])),me=await(0,n.runInferenceSession)(g,ae);return B(me)}catch(ae){const me=Object.fromEntries(Object.entries(j).map(([_e,Se])=>{const Le={type:Se.type,dims:Se.dims,location:Se.location};return Le.location!=="gpu-buffer"&&(Le.data=Se.data),[_e,Le]}));throw console.error(`An error occurred during model execution: "${ae}".`),console.error("Inputs given to model:",me),ae}}function B(g){for(let M in g)(0,n.isONNXTensor)(g[M])?g[M]=new u.Tensor(g[M]):typeof g[M]=="object"&&B(g[M]);return g}function Y(g){if(g instanceof u.Tensor)return g;if(g.length===0)throw Error("items must be non-empty");if(Array.isArray(g[0])){if(g.some(M=>M.length!==g[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 u.Tensor("int64",BigInt64Array.from(g.flat().map(M=>BigInt(M))),[g.length,g[0].length])}else return new u.Tensor("int64",BigInt64Array.from(g.map(M=>BigInt(M))),[1,g.length])}function X(g){return new u.Tensor("bool",[g],[1])}async function J(g,M){let{encoder_outputs:j,input_ids:ae,decoder_input_ids:me,..._e}=M;if(!j){const Le=(0,a.pick)(M,g.sessions.model.inputNames);j=(await re(g,Le)).last_hidden_state}return _e.input_ids=me,_e.encoder_hidden_states=j,g.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=M.attention_mask),await le(g,_e,!0)}async function re(g,M){const j=g.sessions.model,ae=(0,a.pick)(M,j.inputNames);if(j.inputNames.includes("inputs_embeds")&&!ae.inputs_embeds){if(!M.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ae.inputs_embeds=await g.encode_text({input_ids:M.input_ids})}if(j.inputNames.includes("token_type_ids")&&!ae.token_type_ids){if(!ae.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ae.token_type_ids=(0,u.zeros_like)(ae.input_ids)}if(j.inputNames.includes("pixel_mask")&&!ae.pixel_mask){if(!ae.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const me=ae.pixel_values.dims;ae.pixel_mask=(0,u.ones)([me[0],me[2],me[3]])}return await W(j,ae)}async function ne(g,M){const j=await g.encode(M);return await g.decode(j)}async function le(g,M,j=!1){const ae=g.sessions[j?"decoder_model_merged":"model"],{past_key_values:me,..._e}=M;if(ae.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=X(!!me)),ae.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(g.config.model_type)?1:0;_e.position_ids=Ae(_e,me,Le)}g.addPastKeyValues(_e,me);const Se=(0,a.pick)(_e,ae.inputNames);return await W(ae,Se)}function pe({modality_token_id:g,inputs_embeds:M,modality_features:j,input_ids:ae,attention_mask:me}){const _e=ae.tolist().map(st=>st.reduce((wt,bt,Pt)=>(bt==g&&wt.push(Pt),wt),[])),Se=_e.reduce((st,wt)=>st+wt.length,0),Le=j.dims[0];if(Se!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${Le}`);let Ge=0;for(let st=0;st<_e.length;++st){const wt=_e[st],bt=M[st];for(let Pt=0;Pt_e.dims[1]||me<_e.dims[1]&&(j.input_ids=_e.slice(null,[me,null]))}return j}function je(g,M,j,ae){return j.past_key_values&&(M=M.map(me=>[me.at(-1)])),{...j,decoder_input_ids:Y(M)}}function Te(g,...M){return g.config.is_encoder_decoder?je(g,...M):Ie(g,...M)}function Q(g,M,j,ae){const me=!!j.past_key_values;return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me?j.input_ids=(0,u.cat)([j.input_ids,j.input_ids],0):(j.input_ids=(0,u.cat)([j.input_ids,(0,u.full_like)(j.input_ids,BigInt(ae.pad_token_id))],0),j.attention_mask=(0,u.cat)([j.attention_mask,(0,u.full_like)(j.attention_mask,0n)],0))),(me||!j.pixel_values)&&(j.pixel_values=(0,u.full)([0,0,3,384,384],1)),me&&(j.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),j.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),j}class z extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(M,j,ae){super(),this.config=M,this.sessions=j,this.configs=ae;const me=x.get(this.constructor),_e=b.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,_e){case T.DecoderOnly:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=Ie;break;case T.Seq2Seq:case T.Vision2Seq:case T.Musicgen:this.can_generate=!0,this._forward=J,this._prepare_inputs_for_generation=je;break;case T.EncoderDecoder:this._forward=J;break;case T.ImageTextToText:this.can_generate=!0,this._forward=te,this._prepare_inputs_for_generation=Te;break;case T.AudioTextToText:this.can_generate=!0,this._forward=D,this._prepare_inputs_for_generation=Te;break;case T.Phi3V:case T.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=Te;break;case T.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Q;break;case T.AutoEncoder:this._forward=ne;break;default:this._forward=re;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const M=[];for(const j of Object.values(this.sessions))j?.handler?.dispose&&M.push(j.handler.dispose());return await Promise.all(M)}static async from_pretrained(M,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Pt={}}={}){let mt={progress_callback:j,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Pt};const Lt=x.get(this),_t=b.get(Lt);ae=mt.config=await s.AutoConfig.from_pretrained(M,mt);let pt;if(_t===T.DecoderOnly)pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Seq2Seq||_t===T.Vision2Seq)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MaskGeneration)pt=await Promise.all([O(M,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},mt)]);else if(_t===T.EncoderDecoder)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt)]);else if(_t===T.ImageTextToText){const Ft={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ae.is_encoder_decoder&&(Ft.model="encoder_model"),pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.AudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.ImageAudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.Musicgen)pt=await Promise.all([O(M,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MultiModality)pt=await Promise.all([O(M,{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"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Phi3V)pt=await Promise.all([O(M,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.AutoEncoder)pt=await Promise.all([O(M,{encoder_model:"encoder_model",decoder_model:"decoder_model"},mt)]);else if(_t===T.Supertonic)pt=await Promise.all([O(M,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},mt)]);else{if(_t!==T.EncoderOnly){const Ft=Lt??ae?.model_type;Ft!=="custom"&&console.warn(`Model type for '${Ft}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt)])}return new this(ae,...pt)}async _call(M){return await this.forward(M)}async forward(M){return await this._forward(this,M)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(M,j,ae=null){const me=new p.LogitsProcessorList;if(M.repetition_penalty!==null&&M.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(M.repetition_penalty)),M.no_repeat_ngram_size!==null&&M.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(M.no_repeat_ngram_size)),M.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(M.bad_words_ids,M.eos_token_id)),M.min_length!==null&&M.eos_token_id!==null&&M.min_length>0&&me.push(new p.MinLengthLogitsProcessor(M.min_length,M.eos_token_id)),M.min_new_tokens!==null&&M.eos_token_id!==null&&M.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(j,M.min_new_tokens,M.eos_token_id)),M.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(M.forced_bos_token_id)),M.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(M.max_length,M.forced_eos_token_id)),M.begin_suppress_tokens!==null){const _e=j>1||M.forced_bos_token_id===null?j:j+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(M.begin_suppress_tokens,_e))}return M.guidance_scale!==null&&M.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(M.guidance_scale)),M.temperature===0&&M.do_sample&&(console.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`."),M.do_sample=!1),M.do_sample&&M.temperature!==null&&M.temperature!==1&&me.push(new p.TemperatureLogitsWarper(M.temperature)),ae!==null&&me.extend(ae),me}_prepare_generation_config(M,j,ae=d.GenerationConfig){const me={...this.config};for(const Se of["decoder","generator","text_config"])Se in me&&Object.assign(me,me[Se]);const _e=new ae(me);return Object.assign(_e,this.generation_config??{}),M&&Object.assign(_e,M),j&&Object.assign(_e,(0,a.pick)(j,Object.getOwnPropertyNames(_e))),_e}_get_stopping_criteria(M,j=null){const ae=new y.StoppingCriteriaList;return M.max_length!==null&&ae.push(new y.MaxLengthCriteria(M.max_length,this.config.max_position_embeddings??null)),M.eos_token_id!==null&&ae.push(new y.EosTokenCriteria(M.eos_token_id)),j&&ae.extend(j),ae}_validate_model_class(){if(!this.can_generate){const M=[Nl,jl,Rl,Bl],j=x.get(this.constructor),ae=new Set,me=this.config.model_type;for(const Se of M){const Le=Se.get(me);Le&&ae.add(Le[0])}let _e=`The current model class (${j}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ae.size>0&&(_e+=` Please use the following class instead: ${[...ae].join(", ")}`),Error(_e)}}prepare_inputs_for_generation(...M){return this._prepare_inputs_for_generation(this,...M)}_update_model_kwargs_for_generation({generated_input_ids:M,outputs:j,model_inputs:ae,is_encoder_decoder:me}){return ae.past_key_values=this.getPastKeyValues(j,ae.past_key_values),ae.input_ids=new u.Tensor("int64",M.flat(),[M.length,1]),me||(ae.attention_mask=(0,u.cat)([ae.attention_mask,(0,u.ones)([ae.attention_mask.dims[0],1])],1)),ae.position_ids=null,ae}_prepare_model_inputs({inputs:M,bos_token_id:j,model_kwargs:ae}){const me=(0,a.pick)(ae,this.forward_params),_e=this.main_input_name;if(_e in me){if(M)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[_e]=M;return{inputs_tensor:me[_e],model_inputs:me,model_input_name:_e}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:M,model_inputs:j,model_input_name:ae,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!j.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Se,pixel_values:Le,attention_mask:Ge,...st}=j,wt=await this._prepare_inputs_embeds(j);j={...st,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_e}=await re(this,j);if(me.guidance_scale!==null&&me.guidance_scale>1)_e=(0,u.cat)([_e,(0,u.full_like)(_e,0)],0),"attention_mask"in j&&(j.attention_mask=(0,u.cat)([j.attention_mask,(0,u.zeros_like)(j.attention_mask)],0));else if(j.decoder_input_ids){const Se=Y(j.decoder_input_ids).dims[0];if(Se!==_e.dims[0]){if(_e.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_e.dims[0]}) than the decoder inputs (${Se}).`);_e=(0,u.cat)(Array.from({length:Se},()=>_e),0)}}return j.encoder_outputs=_e,j}_prepare_decoder_input_ids_for_generation({batch_size:M,model_input_name:j,model_kwargs:ae,decoder_start_token_id:me,bos_token_id:_e,generation_config:Se}){let{decoder_input_ids:Le,...Ge}=ae;if(!(Le instanceof u.Tensor)){if(Le)Array.isArray(Le[0])||(Le=Array.from({length:M},()=>Le));else if(me??=_e,this.config.model_type==="musicgen")Le=Array.from({length:M*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==M)throw new Error(`\`decoder_start_token_id\` expcted to have length ${M} but got ${me.length}`);Le=me}else Le=Array.from({length:M},()=>[me]);Le=Y(Le)}return ae.decoder_attention_mask=(0,u.ones_like)(Le),{input_ids:Le,model_inputs:Ge}}async generate({inputs:M=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,streamer:_e=null,...Se}){this._validate_model_class(),j=this._prepare_generation_config(j,Se);let{inputs_tensor:Le,model_inputs:Ge,model_input_name:st}=this._prepare_model_inputs({inputs:M,model_kwargs:Se});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Ge||(Ge=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Le,model_inputs:Ge,model_input_name:st,generation_config:j})));let bt;wt?{input_ids:bt,model_inputs:Ge}=this._prepare_decoder_input_ids_for_generation({batch_size:Ge[st].dims.at(0),model_input_name:st,model_kwargs:Ge,decoder_start_token_id:j.decoder_start_token_id,bos_token_id:j.bos_token_id,generation_config:j}):bt=Ge[st];let Pt=bt.dims.at(-1);j.max_new_tokens!==null&&(j.max_length=Pt+j.max_new_tokens);const mt=this._get_logits_processor(j,Pt,ae),Lt=this._get_stopping_criteria(j,me),_t=Ge[st].dims.at(0),pt=k.LogitsSampler.getSampler(j),Ft=new Array(_t).fill(0),Wt=bt.tolist();_e&&_e.put(Wt);let er,nr={};for(;;){if(Ge=this.prepare_inputs_for_generation(Wt,Ge,j),er=await this.forward(Ge),j.output_attentions&&j.return_dict_in_generate){const Wr=this.getAttentions(er);for(const ms in Wr)ms in nr||(nr[ms]=[]),nr[ms].push(Wr[ms])}const At=er.logits.slice(null,-1,null),cr=mt(Wt,At),kr=[];for(let Wr=0;WrWr))break;Ge=this._update_model_kwargs_for_generation({generated_input_ids:kr,outputs:er,model_inputs:Ge,is_encoder_decoder:wt})}_e&&_e.end();const pr=this.getPastKeyValues(er,Ge.past_key_values,!0),fr=new u.Tensor("int64",Wt.flat(),[Wt.length,Wt[0].length]);if(j.return_dict_in_generate)return{sequences:fr,past_key_values:pr,...nr};for(const At of Object.values(er))At.location==="gpu-buffer"&&At.dispose();return fr}getPastKeyValues(M,j,ae=!1){const me=Object.create(null);for(const _e in M)if(_e.startsWith("present")){const Se=_e.replace("present_conv","past_conv").replace("present","past_key_values"),Le=_e.includes("encoder");if(Le&&j?me[Se]=j[Se]:me[Se]=M[_e],j&&(!Le||ae)){const Ge=j[Se];Ge.location==="gpu-buffer"&&Ge.dispose()}}return me}getAttentions(M){const j={};for(const ae of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in M)me.startsWith(ae)&&(ae in j||(j[ae]=[]),j[ae].push(M[me]));return j}addPastKeyValues(M,j){if(j)Object.assign(M,j);else{const ae=this.sessions.decoder_model_merged??this.sessions.model,me=(M[this.main_input_name]??M.attention_mask)?.dims?.[0]??1,_e=ae?.config?.kv_cache_dtype??"float32",Se=_e==="float16"?u.DataTypeMap.float16:u.DataTypeMap.float32,Le=(0,s.getCacheShapes)(this.config,{batch_size:me});for(const Ge in Le){const st=Le[Ge].reduce((wt,bt)=>wt*bt,1);M[Ge]=new u.Tensor(_e,new Se(st),Le[Ge])}}}async encode_image({pixel_values:M}){return(await W(this.sessions.vision_encoder,{pixel_values:M})).image_features}async encode_text({input_ids:M}){return(await W(this.sessions.embed_tokens,{input_ids:M})).inputs_embeds}async encode_audio({audio_values:M}){return(await W(this.sessions.audio_encoder,{audio_values:M})).audio_features}}class de{}class be extends de{constructor({last_hidden_state:M,hidden_states:j=null,attentions:ae=null}){super(),this.last_hidden_state=M,this.hidden_states=j,this.attentions=ae}}class ve extends z{}class xe extends ve{}class Ce extends ve{async _call(M){return new $r(await super._call(M))}}class ge extends ve{async _call(M){return new xt(await super._call(M))}}class De extends ve{async _call(M){return new Pr(await super._call(M))}}class fe extends ve{async _call(M){return new Br(await super._call(M))}}class Ee extends z{}class We extends Ee{}class Fe extends Ee{async _call(M){return new $r(await super._call(M))}}class tt extends Ee{async _call(M){return new xt(await super._call(M))}}class Re extends Ee{async _call(M){return new Pr(await super._call(M))}}class rt extends Ee{async _call(M){return new Br(await super._call(M))}}class Ze extends z{}class Ne extends Ze{}class Oe extends Ze{async _call(M){return new $r(await super._call(M))}}class ot extends Ze{async _call(M){return new xt(await super._call(M))}}class ht extends Ze{async _call(M){return new Pr(await super._call(M))}}class Rt extends z{}class It extends Rt{}class gr extends Rt{}class Or extends z{}class zt extends Or{}class Rr extends z{}class qs extends Rr{}class Qs extends Rr{async _call(M){return new $r(await super._call(M))}}class Xs extends Rr{async _call(M){return new xt(await super._call(M))}}class or extends Rr{async _call(M){return new Pr(await super._call(M))}}class Sr extends Rr{async _call(M){return new Br(await super._call(M))}}class Qr extends z{}class Bs extends Qr{}class ft extends Qr{async _call(M){return new $r(await super._call(M))}}class qt extends Qr{async _call(M){return new xt(await super._call(M))}}class Ps extends Qr{async _call(M){return new Pr(await super._call(M))}}class Cs extends Qr{async _call(M){return new Br(await super._call(M))}}class Kr extends z{}class yt extends Kr{}class Ss extends Kr{async _call(M){return new $r(await super._call(M))}}class C extends Kr{async _call(M){return new xt(await super._call(M))}}class q extends Kr{async _call(M){return new Pr(await super._call(M))}}class R extends Kr{async _call(M){return new Br(await super._call(M))}}class G extends z{}class Z extends G{}class ce extends G{async _call(M){return new $r(await super._call(M))}}class ye extends G{async _call(M){return new xt(await super._call(M))}}class et extends G{async _call(M){return new Pr(await super._call(M))}}class ut extends G{async _call(M){return new Br(await super._call(M))}}class He extends z{}class Mt extends He{}class qe extends He{async _call(M){return new $r(await super._call(M))}}class Tt extends He{async _call(M){return new xt(await super._call(M))}}class kt extends He{async _call(M){return new Pr(await super._call(M))}}class Mr extends He{async _call(M){return new Br(await super._call(M))}}class dr extends z{}class ar extends dr{}class Tr extends dr{async _call(M){return new $r(await super._call(M))}}class Is extends dr{async _call(M){return new xt(await super._call(M))}}class Dr extends dr{async _call(M){return new Pr(await super._call(M))}}class $s extends dr{async _call(M){return new Br(await super._call(M))}}class Lr extends z{}class zr extends Lr{}class ts extends Lr{async _call(M){return new xt(await super._call(M))}}class wr extends Lr{async _call(M){return new Pr(await super._call(M))}}class ir extends Lr{async _call(M){return new Br(await super._call(M))}}class Hr extends Lr{async _call(M){return new $r(await super._call(M))}}class rs extends z{}class Rs extends rs{}class ks extends rs{async _call(M){return new $r(await super._call(M))}}class As extends rs{async _call(M){return new xt(await super._call(M))}}class Fs extends rs{async _call(M){return new Pr(await super._call(M))}}class ss extends z{}class Nr extends ss{}class ze extends ss{async _call(M){return new $r(await super._call(M))}}class Ue extends ss{async _call(M){return new xt(await super._call(M))}}class nt extends ss{async _call(M){return new Br(await super._call(M))}}class Kt extends z{}class Ns extends Kt{}class Os extends Kt{async _call(M){return new $r(await super._call(M))}}class js extends Kt{async _call(M){return new xt(await super._call(M))}}class Dn extends Kt{async _call(M){return new Pr(await super._call(M))}}class ue extends Kt{async _call(M){return new Br(await super._call(M))}}class $ extends z{}class U extends ${}class ee extends ${async _call(M){return new $r(await super._call(M))}}class se extends ${async _call(M){return new xt(await super._call(M))}}class Me extends ${async _call(M){return new Br(await super._call(M))}}class $e extends z{}class Xe extends $e{}class Je extends $e{async _call(M){return new xt(await super._call(M))}}class Ye extends $e{async _call(M){return new Br(await super._call(M))}}class Ke extends $e{async _call(M){return new $r(await super._call(M))}}class $t extends z{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Et extends $t{}class rr extends $t{}class br extends z{}class Xt extends br{}class sr extends br{}class Ht extends z{}class qr extends Ht{}class ns extends Ht{}class Er extends z{}class ds extends Er{}class Yt extends Er{}class hr extends Er{async _call(M){return new xt(await super._call(M))}}class Ir extends z{}class Xr extends Ir{}class ps extends Ir{}class yr extends Ir{async _call(M){return new xt(await super._call(M))}}class os extends Ir{}class vr extends z{}class Zt extends vr{}class _r extends vr{}class lr extends z{}class Ur extends lr{}class Js extends lr{}class Ds extends z{}class po extends Ds{}class ra extends Ds{async _call(M){return new $r(await super._call(M))}}class sa extends Ds{async _call(M){return new xt(await super._call(M))}}class na extends Ds{async _call(M){return new Pr(await super._call(M))}}class oa extends Ds{async _call(M){return new Br(await super._call(M))}}class Ys extends z{}class aa extends Ys{}class ia extends Ys{async _call(M){return new $r(await super._call(M))}}class la extends Ys{async _call(M){return new xt(await super._call(M))}}class ca extends Ys{async _call(M){return new Pr(await super._call(M))}}class ua extends Ys{async _call(M){return new Br(await super._call(M))}}class Zs extends z{}class da extends Zs{}class mo extends Zs{async _call(M){return new $r(await super._call(M))}}class ho extends Zs{async _call(M){return new xt(await super._call(M))}}class _o extends Zs{async _call(M){return new Pr(await super._call(M))}}class pa extends Zs{async _call(M){return new Br(await super._call(M))}}class fo extends z{}class go extends fo{}class Mo extends fo{}class Vs extends z{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class ma extends Vs{}class Ln extends Vs{_prepare_generation_config(M,j){return super._prepare_generation_config(M,j,v.WhisperGenerationConfig)}_retrieve_init_tokens(M){const j=[M.decoder_start_token_id];let ae=M.language;const me=M.task;if(M.is_multilingual){ae||(console.warn("No language specified - defaulting to English (en)."),ae="en");const Se=`<|${(0,I.whisper_language_to_code)(ae)}|>`;j.push(M.lang_to_id[Se]),j.push(M.task_to_id[me??"transcribe"])}else if(ae||me)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!M.return_timestamps&&M.no_timestamps_token_id&&j.at(-1)!==M.no_timestamps_token_id?j.push(M.no_timestamps_token_id):M.return_timestamps&&j.at(-1)===M.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),j.pop()),j.filter(_e=>_e!=null)}async generate({inputs:M=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,..._e}){j=this._prepare_generation_config(j,_e);const Se=_e.decoder_input_ids??this._retrieve_init_tokens(j);if(j.return_timestamps&&(ae??=new p.LogitsProcessorList,ae.push(new p.WhisperTimeStampLogitsProcessor(j,Se))),j.begin_suppress_tokens&&(ae??=new p.LogitsProcessorList,ae.push(new p.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,Se.length))),j.return_token_timestamps){if(!j.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");j.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),j.output_attentions=!0,j.return_dict_in_generate=!0}const Le=await super.generate({inputs:M,generation_config:j,logits_processor:ae,decoder_input_ids:Se,..._e});return j.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,j.alignment_heads,j.num_frames)),Le}_extract_token_timestamps(M,j,ae=null,me=.02){if(!M.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");ae==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let _e=this.config.median_filter_width;_e===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),_e=7);const Se=M.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(_t,pt)=>(0,u.cat)(Se.map(Ft=>Ft[pt]),2)),Ge=(0,u.stack)(j.map(([_t,pt])=>{if(_t>=Le.length)throw new Error(`Layer index ${_t} is out of bounds for cross attentions (length ${Le.length}).`);return ae?Le[_t].slice(null,pt,null,[0,ae]):Le[_t].slice(null,pt)})).transpose(1,0,2,3),[st,wt]=(0,u.std_mean)(Ge,-2,0,!0),bt=Ge.clone();for(let _t=0;_tFt[At+1]-Ft[At]),nr=(0,a.mergeArrays)([1],er).map(fr=>!!fr),pr=[];for(let fr=0;frArray.from({length:M.dims[0]},er=>Array.from({length:M.dims[1]},nr=>1))),Lt=j?j.tolist():[],_t=ae?ae.tolist():[];let pt=0,Ft=0;for(let Wt=0;WtPt[Wt][Cr]==1),pr=er.reduce((tr,Cr,sn)=>(Cr==Ge&&tr.push(sn),tr),[]).map(tr=>er[tr+1]),fr=pr.filter(tr=>tr==Se).length,At=pr.filter(tr=>tr==Le).length;let cr=[],kr=0,wn=fr,Wr=At;for(let tr=0;trhs>kr&&yn==Se),sn=er.findIndex((yn,hs)=>hs>kr&&yn==Le),bn=wn>0&&Cr!==-1?Cr:er.length+1,to=Wr>0&&sn!==-1?sn:er.length+1;let Wa,Vl,Ul,Wl;bn0?(0,_.max)(cr.at(-1))[0]+1:0;cr.push(Array.from({length:3*Kl},(yn,hs)=>J_+hs%Kl));const Hl=Kl+J_,Ka=Mx*Gl*Ga,wx=Array.from({length:Ka},(yn,hs)=>Hl+Math.floor(hs/(Gl*Ga))),bx=Array.from({length:Ka},(yn,hs)=>Hl+Math.floor(hs/Ga)%Gl),yx=Array.from({length:Ka},(yn,hs)=>Hl+hs%Ga);cr.push([wx,bx,yx].flat()),kr=Wa+Ka}if(kr0?(0,_.max)(cr.at(-1))[0]+1:0,Cr=er.length-kr;cr.push(Array.from({length:3*Cr},(sn,bn)=>tr+bn%Cr))}const ms=cr.reduce((tr,Cr)=>tr+Cr.length,0),Zn=new Array(ms);let eo=0;for(let tr=0;tr<3;++tr)for(let Cr=0;Crbt[pt%bt.length]),Lt=Array.from({length:Pt[0]},(_t,pt)=>(0,_.max)(bt.subarray(Pt[1]*pt,Pt[1]*(pt+1)))[0]+1n+BigInt(Pt[1]));return[new u.Tensor("int64",mt,[3,...Pt]),new u.Tensor("int64",Lt,[Lt.length,1])]}else{const[bt,Pt]=M.dims,mt=BigInt64Array.from({length:3*bt*Pt},(Lt,_t)=>BigInt(Math.floor(_t%Pt/bt)));return[new u.Tensor("int64",mt,[3,...M.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:M,image_grid_thw:j}){return(await W(this.sessions.vision_encoder,{pixel_values:M,grid_thw:j})).image_features}_merge_input_ids_with_image_features(M){return oe({image_token_id:this.config.image_token_id,...M})}prepare_inputs_for_generation(M,j,ae){if(j.attention_mask&&!j.position_ids)if(!j.past_key_values)[j.position_ids,j.rope_deltas]=this.get_rope_index(j.input_ids,j.image_grid_thw,j.video_grid_thw,j.attention_mask);else{j.pixel_values=null;const me=BigInt(Object.values(j.past_key_values)[0].dims.at(-2)),_e=j.rope_deltas.map(Se=>me+Se);j.position_ids=(0,u.stack)([_e,_e,_e],0)}return j}}class Ni extends z{}class $d extends Ni{}class kd extends Ni{}class ji extends z{}class Ad extends ji{}class Fd extends ji{}class Vi extends z{}class Od extends Vi{}class Dd extends Vi{}class Ui extends z{}class Ld extends Ui{}class zd extends Ui{}class Wi extends z{}class Bd extends Wi{}class Rd extends Wi{}class Gi extends z{}class Nd extends Gi{}class jd extends Gi{async _call(M){return new xt(await super._call(M))}}class Ki extends z{}class Vd extends Ki{}class Ud extends Ki{async _call(M){return new xt(await super._call(M))}}class Wd extends z{}class Gd extends Wd{}class Hi extends z{}class Kd extends Hi{}class Hd extends Hi{async _call(M){return new xt(await super._call(M))}}class qd extends z{}class Qd extends qd{}class qi extends z{}class Xd extends qi{}class Jd extends qi{async _call(M){return new xt(await super._call(M))}}class Yd extends z{}class Zd extends Yd{}class Qi extends z{}class ep extends Qi{}class tp extends Qi{async _call(M){return new xt(await super._call(M))}}class rp extends z{}class sp extends rp{async _call(M){return new Q_(await super._call(M))}}class Xi extends z{}class np extends Xi{}class op extends Xi{async _call(M){return new xt(await super._call(M))}}class Ji extends z{}class ap extends Ji{}class ip extends Ji{async _call(M){return new xt(await super._call(M))}}class Yi extends z{}class lp extends Yi{}class cp extends Yi{}class Zi extends z{}class up extends Zi{}class dp extends Zi{}class el extends z{}class pp extends el{}class mp extends el{async _call(M){return new xt(await super._call(M))}}class Ca extends z{}class hp extends Ca{}class _p extends Ca{async _call(M){return new rl(await super._call(M))}}class tl extends Ca{async _call(M){return new fp(await super._call(M))}}class rl extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class fp extends de{constructor({logits:M,pred_boxes:j,pred_masks:ae}){super(),this.logits=M,this.pred_boxes=j,this.pred_masks=ae}}class sl extends z{}class gp extends sl{}class Mp extends sl{async _call(M){return new Fo(await super._call(M))}}class Fo extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class nl extends z{}class wp extends nl{}class bp extends nl{async _call(M){return new yp(await super._call(M))}}class yp extends Fo{}class ol extends z{}class vp extends ol{}class xp extends ol{async _call(M){return new Tp(await super._call(M))}}class Tp extends Fo{}class al extends z{}class Ep extends al{}class Pp extends al{async _call(M){return new Fo(await super._call(M))}}class il extends z{}class Cp extends il{}class Sp extends il{async _call(M){return new Ip(await super._call(M))}}class Ip extends rl{}class ll extends z{}class $p extends ll{}class kp extends ll{async _call(M){return new xt(await super._call(M))}}class cl extends z{}class Ap extends cl{}class Fp extends cl{async _call(M){return new xt(await super._call(M))}}class ul extends z{}class Op extends ul{}class Dp extends ul{async _call(M){return new xt(await super._call(M))}}class Sa extends z{}class Lp extends Sa{}class zp extends Sa{async _call(M){return new xt(await super._call(M))}}class Bp extends Sa{}class dl extends z{}class Rp extends dl{}class Np extends dl{}class pl extends z{}class jp extends pl{}class Vp extends pl{}class Up extends z{}class Wp extends Up{}class Ia extends z{}class Gp extends Ia{}class Kp extends Ia{}class Hp extends Ia{}class qp extends z{}class Qp extends qp{}class Xp extends z{}class Jp extends Xp{}class Yp extends z{}class Zp extends Yp{}class ml extends z{}class em extends ml{}class tm extends ml{}class hl extends z{}class rm extends hl{}class sm extends hl{}class nm extends z{}class om extends nm{}class _l extends z{}class am extends _l{}class im extends _l{async _call(M){return new xt(await super._call(M))}}class fl extends z{}class lm extends fl{}class cm extends fl{async _call(M){return new xt(await super._call(M))}}class gl extends z{}class um extends gl{}class dm extends gl{async _call(M){return new xt(await super._call(M))}}class Ml extends z{}class pm extends Ml{}class mm extends Ml{async _call(M){return new xt(await super._call(M))}}class hm extends z{}class _m extends hm{}class fm extends z{}class gm extends fm{}class Mm extends z{}class wm extends Mm{}class wl extends z{}class bm extends wl{}class ym extends wl{async _call(M){return new vm(await super._call(M))}}class vm extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class xm extends z{}class Tm extends xm{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){!M.image_embeddings||!M.image_positional_embeddings?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_labels??=(0,u.ones)(M.input_points.dims.slice(0,-1));const j={image_embeddings:M.image_embeddings,image_positional_embeddings:M.image_positional_embeddings};return M.input_points&&(j.input_points=M.input_points),M.input_labels&&(j.input_labels=M.input_labels),M.input_boxes&&(j.input_boxes=M.input_boxes),await W(this.sessions.prompt_encoder_mask_decoder,j)}async _call(M){return new Em(await super._call(M))}}class Em extends de{constructor({iou_scores:M,pred_masks:j}){super(),this.iou_scores=M,this.pred_masks=j}}class Pm extends de{constructor({iou_scores:M,pred_masks:j,object_score_logits:ae}){super(),this.iou_scores=M,this.pred_masks=j,this.object_score_logits=ae}}class Cm extends z{}class $a extends Cm{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){const{num_feature_levels:j}=this.config.vision_config;if(Array.from({length:j},(Se,Le)=>`image_embeddings.${Le}`).some(Se=>!M[Se])?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_points){if(M.input_boxes&&M.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 Se=M.input_points.dims;M.input_labels??=(0,u.ones)(Se.slice(0,-1)),M.input_boxes??=(0,u.full)([Se[0],0,4],0)}else if(M.input_boxes){const Se=M.input_boxes.dims;M.input_labels=(0,u.full)([Se[0],Se[1],0],-1n),M.input_points=(0,u.full)([Se[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const me=this.sessions.prompt_encoder_mask_decoder,_e=(0,a.pick)(M,me.inputNames);return await W(me,_e)}async _call(M){return new Pm(await super._call(M))}}class Sm extends $a{}class Im extends $a{}class bl extends z{}class $m extends bl{}class km extends bl{}class yl extends z{}class Am extends yl{}class Fm extends yl{}class tn extends z{}class Om extends tn{}class Dm extends tn{async _call(M){return new rn(await super._call(M))}}class Lm extends tn{async _call(M){return new xt(await super._call(M))}}class zm extends tn{async _call(M){return new Pr(await super._call(M))}}class Bm extends z{}class Rm extends Bm{async _call(M){return new rn(await super._call(M))}}class vl extends z{}class Nm extends vl{}class jm extends vl{async _call(M){return new Pr(await super._call(M))}}class Vm extends z{}class Um extends Vm{}class ka extends z{}class Wm extends ka{}class Gm extends ka{async _call(M){return new rn(await super._call(M))}}class Km extends ka{async _call(M){return new xt(await super._call(M))}}class Oo extends z{}class Hm extends Oo{}class qm extends Oo{async _call(M){return new rn(await super._call(M))}}class Qm extends Oo{async _call(M){return new xt(await super._call(M))}}class Xm extends Oo{async _call(M){return new Pr(await super._call(M))}}class Aa extends z{}class Jm extends Aa{}class Ym extends Aa{async _call(M){return new rn(await super._call(M))}}class Zm extends Aa{async _call(M){return new xt(await super._call(M))}}class Ev extends z{}class eh extends tn{}class th extends tn{async _call(M){return new rn(await super._call(M))}}class rh extends tn{async _call(M){return new xt(await super._call(M))}}class Jn extends z{}class sh extends Jn{}class nh extends Jn{async _call(M){return new rn(await super._call(M))}}class oh extends Jn{async _call(M){return new xt(await super._call(M))}}class ah extends Jn{async _call(M){return new q_(await super._call(M))}}class ih extends Jn{async _call(M){return new Pr(await super._call(M))}}class lh extends z{}class ch extends lh{}class Fa extends z{}class Pv extends Fa{}class uh extends Fa{}class dh extends Fa{async generate_speech(M,j,{threshold:ae=.5,minlenratio:me=0,maxlenratio:_e=20,vocoder:Se=null}={}){const Le={input_ids:M},{encoder_outputs:Ge,encoder_attention_mask:st}=await re(this,Le),wt=Ge.dims[1]/this.config.reduction_factor,bt=Math.floor(wt*_e),Pt=Math.floor(wt*me),mt=this.config.num_mel_bins;let Lt=[],_t=null,pt=null,Ft=0;for(;;){++Ft;const nr=X(!!pt);let pr;pt?pr=pt.output_sequence_out:pr=new u.Tensor("float32",new Float32Array(mt),[1,1,mt]);let fr={use_cache_branch:nr,output_sequence:pr,encoder_attention_mask:st,speaker_embeddings:j,encoder_hidden_states:Ge};this.addPastKeyValues(fr,_t),pt=await W(this.sessions.decoder_model_merged,fr),_t=this.getPastKeyValues(pt,_t);const{prob:At,spectrum:cr}=pt;if(Lt.push(cr),Ft>=Pt&&(Array.from(At.data).filter(kr=>kr>=ae).length>0||Ft>=bt))break}const Wt=(0,u.cat)(Lt),{waveform:er}=await W(Se.sessions.model,{spectrogram:Wt});return{spectrogram:Wt,waveform:er}}}class ph extends z{main_input_name="spectrogram"}class mh extends z{}class xl extends mh{async generate_speech({input_ids:M,attention_mask:j,style:ae,num_inference_steps:me=5,speed:_e=1.05}){const{sampling_rate:Se,chunk_compress_factor:Le,base_chunk_size:Ge,latent_dim:st}=this.config,{last_hidden_state:wt,durations:bt}=await W(this.sessions.text_encoder,{input_ids:M,attention_mask:j,style:ae});bt.div_(_e);const Pt=bt.max().item()*Se,mt=Ge*Le,Lt=Math.floor((Pt+mt-1)/mt),_t=M.dims[0],pt=(0,u.ones)([_t,Lt]),Ft=(0,u.full)([_t],me);let Wt=(0,u.randn)([_t,st*Le,Lt]);for(let nr=0;nr0&&Pt<=_e&&(M.data[Se++]=M.data[st])}const Le=Math.floor(j/me),Ge=Se/(Le*me);return new u.Tensor(M.type,M.data.slice(0,Se),[Le,me,Ge])}prepare_inputs_for_generation(M,j,ae){let me=structuredClone(M);for(let Se=0;Se=Le&&(me[Se][Le]=BigInt(this.config.decoder.pad_token_id));return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,j,ae)}async generate(M){const j=await super.generate(M),ae=this._apply_and_filter_by_delay_pattern_mask(j).unsqueeze_(0),{audio_values:me}=await W(this.sessions.encodec_decode,{audio_codes:ae});return me}}class La extends z{}class Bh extends La{}class Rh extends La{async _call(M){return new xt(await super._call(M))}}class Nh extends La{}class za extends z{}class jh extends za{}class Vh extends za{async _call(M){return new xt(await super._call(M))}}class Uh extends za{}class Ba extends z{}class Wh extends Ba{}class Gh extends Ba{async _call(M){return new xt(await super._call(M))}}class Kh extends Ba{}class Ra extends z{}class Hh extends Ra{}class qh extends Ra{async _call(M){return new xt(await super._call(M))}}class Qh extends Ra{}class Xh extends z{}class Jh extends Xh{}class Yh extends z{}class Zh extends Yh{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...M){super(...M),this._generation_mode="text"}async forward(M){const j=this._generation_mode??"text";let ae;if(j==="text"||!M.past_key_values){const Ge=this.sessions.prepare_inputs_embeds,st=(0,a.pick)(M,Ge.inputNames);ae=await W(Ge,st)}else{const Ge=this.sessions.gen_img_embeds,st=(0,a.pick)({image_ids:M.input_ids},Ge.inputNames);ae=await W(Ge,st)}const me={...M,...ae},_e=await le(this,me),Se=this.sessions[j==="text"?"lm_head":"gen_head"];if(!Se)throw new Error(`Unable to find "${Se}" generation head`);const Le=await W(Se,(0,a.pick)(_e,Se.inputNames));return{...ae,..._e,...Le}}async generate(M){return this._generation_mode="text",super.generate(M)}async generate_images(M){this._generation_mode="image";const j=(M.inputs??M[this.main_input_name]).dims[1],me=(await super.generate(M)).slice(null,[j,null]),_e=this.sessions.image_decode,{decoded_image:Se}=await W(_e,{generated_tokens:me}),Le=Se.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Ge=[];for(const st of Le){const wt=f.RawImage.fromTensor(st);Ge.push(wt)}return Ge}}class e_ extends de{constructor({char_logits:M,bpe_logits:j,wp_logits:ae}){super(),this.char_logits=M,this.bpe_logits=j,this.wp_logits=ae}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class t_ extends z{}class r_ extends t_{async _call(M){return new e_(await super._call(M))}}class Dl extends z{}class s_ extends Dl{}class n_ extends Dl{}class Ll extends z{}class o_ extends Ll{}class a_ extends Ll{}class i_ extends z{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class zl extends i_{_merge_input_ids_with_audio_features(M){const j=M.audio_features.dims.at(-1),ae=M.audio_features.view(-1,j);return K({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...M,audio_features:ae})}}class l_ extends zl{}class Na extends z{main_input_name="input_values";forward_params=["input_values"]}class c_ extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class u_ extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class d_ extends Na{async encode(M){return new c_(await W(this.sessions.encoder_model,M))}async decode(M){return new u_(await W(this.sessions.decoder_model,M))}}class p_ extends Na{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class m_ extends Na{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class ja extends z{main_input_name="input_values";forward_params=["input_values"]}class h_ extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class __ extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class f_ extends ja{async encode(M){return new h_(await W(this.sessions.encoder_model,M))}async decode(M){return new __(await W(this.sessions.decoder_model,M))}}class g_ extends ja{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class M_ extends ja{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Va extends z{main_input_name="input_values";forward_params=["input_values"]}class w_ extends Va{async encode(M){return await W(this.sessions.encoder_model,M)}async decode(M){return await W(this.sessions.decoder_model,M)}}class b_ extends Va{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class y_ extends Va{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Ut{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(M,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Pt={}}={}){const mt={progress_callback:j,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Pt};if(mt.config=await s.AutoConfig.from_pretrained(M,mt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const Lt=mt.config.model_type;for(const _t of this.MODEL_CLASS_MAPPINGS){let pt=_t.get(Lt);if(!pt){for(const Ft of _t.values())if(Ft[0]===Lt){pt=Ft;break}if(!pt)continue}return await pt[1].from_pretrained(M,mt)}if(this.BASE_IF_FAIL)return H_.has(Lt)||console.warn(`Unknown model class "${Lt}", attempting to construct from base class.`),await z.from_pretrained(M,mt);throw Error(`Unsupported model type: ${Lt}`)}}const $v=new Map([["bert",["BertModel",xe]],["neobert",["NeoBertModel",We]],["modernbert",["ModernBertModel",Ne]],["nomic_bert",["NomicBertModel",zt]],["roformer",["RoFormerModel",qs]],["electra",["ElectraModel",yt]],["esm",["EsmModel",Rs]],["convbert",["ConvBertModel",Bs]],["camembert",["CamembertModel",Z]],["deberta",["DebertaModel",Mt]],["deberta-v2",["DebertaV2Model",ar]],["mpnet",["MPNetModel",Ns]],["albert",["AlbertModel",Xe]],["distilbert",["DistilBertModel",zr]],["roberta",["RobertaModel",po]],["xlm",["XLMModel",aa]],["xlm-roberta",["XLMRobertaModel",da]],["clap",["ClapModel",Sh]],["clip",["CLIPModel",vo]],["clipseg",["CLIPSegModel",Po]],["chinese_clip",["ChineseCLIPModel",Eo]],["siglip",["SiglipModel",To]],["jina_clip",["JinaCLIPModel",hn]],["mobilebert",["MobileBertModel",Nr]],["squeezebert",["SqueezeBertModel",U]],["wav2vec2",["Wav2Vec2Model",Om]],["wav2vec2-bert",["Wav2Vec2BertModel",Jm]],["unispeech",["UniSpeechModel",Wm]],["unispeech-sat",["UniSpeechSatModel",Hm]],["hubert",["HubertModel",eh]],["wavlm",["WavLMModel",sh]],["audio-spectrogram-transformer",["ASTModel",go]],["vits",["VitsModel",$l]],["pyannote",["PyAnnoteModel",Nm]],["wespeaker-resnet",["WeSpeakerResNetModel",Um]],["detr",["DetrModel",hp]],["rt_detr",["RTDetrModel",gp]],["rt_detr_v2",["RTDetrV2Model",wp]],["rf_detr",["RFDetrModel",vp]],["d_fine",["DFineModel",Ep]],["table-transformer",["TableTransformerModel",Cp]],["vit",["ViTModel",Nd]],["ijepa",["IJepaModel",Vd]],["pvt",["PvtModel",Kd]],["vit_msn",["ViTMSNModel",Xd]],["vit_mae",["ViTMAEModel",Qd]],["groupvit",["GroupViTModel",Zd]],["fastvit",["FastViTModel",ep]],["mobilevit",["MobileViTModel",np]],["mobilevitv2",["MobileViTV2Model",ap]],["owlvit",["OwlViTModel",lp]],["owlv2",["Owlv2Model",up]],["beit",["BeitModel",pp]],["deit",["DeiTModel",$p]],["hiera",["HieraModel",Ap]],["convnext",["ConvNextModel",am]],["convnextv2",["ConvNextV2Model",lm]],["dinov2",["Dinov2Model",um]],["dinov2_with_registers",["Dinov2WithRegistersModel",pm]],["dinov3_vit",["DINOv3ViTModel",_m]],["dinov3_convnext",["DINOv3ConvNextModel",gm]],["resnet",["ResNetModel",Op]],["swin",["SwinModel",Lp]],["swin2sr",["Swin2SRModel",Rp]],["donut-swin",["DonutSwinModel",om]],["yolos",["YolosModel",bm]],["dpt",["DPTModel",jp]],["glpn",["GLPNModel",rm]],["hifigan",["SpeechT5HifiGan",ph]],["efficientnet",["EfficientNetModel",Lh]],["decision_transformer",["DecisionTransformerModel",Jh]],["patchtst",["PatchTSTForPrediction",s_]],["patchtsmixer",["PatchTSMixerForPrediction",o_]],["mobilenet_v1",["MobileNetV1Model",Bh]],["mobilenet_v2",["MobileNetV2Model",jh]],["mobilenet_v3",["MobileNetV3Model",Wh]],["mobilenet_v4",["MobileNetV4Model",Hh]],["maskformer",["MaskFormerModel",em]],["mgp-str",["MgpstrForSceneTextRecognition",r_]],["style_text_to_speech_2",["StyleTextToSpeech2Model",ch]]]),kv=new Map([["t5",["T5Model",Et]],["longt5",["LongT5Model",Xt]],["mt5",["MT5Model",qr]],["bart",["BartModel",ds]],["mbart",["MBartModel",Xr]],["marian",["MarianModel",$m]],["whisper",["WhisperModel",ma]],["m2m_100",["M2M100Model",Am]],["blenderbot",["BlenderbotModel",Zt]],["blenderbot-small",["BlenderbotSmallModel",Ur]]]),Av=new Map([["mimi",["MimiModel",d_]],["dac",["DacModel",f_]],["snac",["SnacModel",w_]]]),Fv=new Map([["bloom",["BloomModel",Od]],["jais",["JAISModel",Io]],["gpt2",["GPT2Model",Kn]],["gptj",["GPTJModel",h]],["gpt_bigcode",["GPTBigCodeModel",L]],["gpt_neo",["GPTNeoModel",qn]],["gpt_neox",["GPTNeoXModel",ko]],["codegen",["CodeGenModel",Pe]],["llama",["LlamaModel",at]],["nanochat",["NanoChatModel",Us]],["arcee",["ArceeModel",Wu]],["lfm2",["Lfm2Model",Ku]],["smollm3",["SmolLM3Model",qu]],["exaone",["ExaoneModel",ed]],["olmo",["OlmoModel",nd]],["olmo2",["Olmo2Model",ad]],["mobilellm",["MobileLLMModel",rd]],["granite",["GraniteModel",ld]],["granitemoehybrid",["GraniteMoeHybridModel",ud]],["cohere",["CohereModel",pd]],["gemma",["GemmaModel",hd]],["gemma2",["Gemma2Model",fd]],["vaultgemma",["VaultGemmaModel",Md]],["gemma3_text",["Gemma3Model",bd]],["helium",["HeliumModel",Xu]],["glm",["GlmModel",Yu]],["openelm",["OpenELMModel",vd]],["qwen2",["Qwen2Model",Td]],["qwen3",["Qwen3Model",Pd]],["phi",["PhiModel",$d]],["phi3",["Phi3Model",Ad]],["mpt",["MptModel",Ld]],["opt",["OPTModel",Bd]],["mistral",["MistralModel",fh]],["ministral",["MinistralModel",Mh]],["ministral3",["Ministral3Model",bh]],["ernie4_5",["Ernie4_5Model",vh]],["starcoder2",["Starcoder2Model",Th]],["falcon",["FalconModel",Ph]],["stablelm",["StableLmModel",Oh]],["modernbert-decoder",["ModernBertDecoderModel",It]]]),Bl=new Map([["speecht5",["SpeechT5ForSpeechToText",uh]],["whisper",["WhisperForConditionalGeneration",Ln]],["lite-whisper",["LiteWhisperForConditionalGeneration",ha]],["moonshine",["MoonshineForConditionalGeneration",zn]]]),v_=new Map([["speecht5",["SpeechT5ForTextToSpeech",dh]]]),x_=new Map([["vits",["VitsModel",$l]],["musicgen",["MusicgenForConditionalGeneration",Ol]],["supertonic",["SupertonicForConditionalGeneration",xl]]]),T_=new Map([["bert",["BertForSequenceClassification",ge]],["neobert",["NeoBertForSequenceClassification",tt]],["modernbert",["ModernBertForSequenceClassification",ot]],["roformer",["RoFormerForSequenceClassification",Xs]],["electra",["ElectraForSequenceClassification",C]],["esm",["EsmForSequenceClassification",As]],["convbert",["ConvBertForSequenceClassification",qt]],["camembert",["CamembertForSequenceClassification",ye]],["deberta",["DebertaForSequenceClassification",Tt]],["deberta-v2",["DebertaV2ForSequenceClassification",Is]],["mpnet",["MPNetForSequenceClassification",js]],["albert",["AlbertForSequenceClassification",Je]],["distilbert",["DistilBertForSequenceClassification",ts]],["roberta",["RobertaForSequenceClassification",sa]],["xlm",["XLMForSequenceClassification",la]],["xlm-roberta",["XLMRobertaForSequenceClassification",ho]],["bart",["BartForSequenceClassification",hr]],["mbart",["MBartForSequenceClassification",yr]],["mobilebert",["MobileBertForSequenceClassification",Ue]],["squeezebert",["SqueezeBertForSequenceClassification",se]]]),E_=new Map([["bert",["BertForTokenClassification",De]],["neobert",["NeoBertForTokenClassification",Re]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",or]],["electra",["ElectraForTokenClassification",q]],["esm",["EsmForTokenClassification",Fs]],["convbert",["ConvBertForTokenClassification",Ps]],["camembert",["CamembertForTokenClassification",et]],["deberta",["DebertaForTokenClassification",kt]],["deberta-v2",["DebertaV2ForTokenClassification",Dr]],["mpnet",["MPNetForTokenClassification",Dn]],["distilbert",["DistilBertForTokenClassification",wr]],["roberta",["RobertaForTokenClassification",na]],["xlm",["XLMForTokenClassification",ca]],["xlm-roberta",["XLMRobertaForTokenClassification",_o]]]),Rl=new Map([["t5",["T5ForConditionalGeneration",rr]],["longt5",["LongT5ForConditionalGeneration",sr]],["mt5",["MT5ForConditionalGeneration",ns]],["bart",["BartForConditionalGeneration",Yt]],["mbart",["MBartForConditionalGeneration",ps]],["marian",["MarianMTModel",km]],["m2m_100",["M2M100ForConditionalGeneration",Fm]],["blenderbot",["BlenderbotForConditionalGeneration",_r]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Js]]]),Nl=new Map([["bloom",["BloomForCausalLM",Dd]],["gpt2",["GPT2LMHeadModel",So]],["jais",["JAISLMHeadModel",gn]],["gptj",["GPTJForCausalLM",P]],["gpt_bigcode",["GPTBigCodeForCausalLM",V]],["gpt_neo",["GPTNeoForCausalLM",$o]],["gpt_neox",["GPTNeoXForCausalLM",Ao]],["codegen",["CodeGenForCausalLM",Be]],["llama",["LlamaForCausalLM",vt]],["nanochat",["NanoChatForCausalLM",Pa]],["llama4_text",["Llama4ForCausalLM",Vt]],["arcee",["ArceeForCausalLM",Gu]],["lfm2",["Lfm2ForCausalLM",Hu]],["smollm3",["SmolLM3ForCausalLM",Qu]],["exaone",["ExaoneForCausalLM",td]],["olmo",["OlmoForCausalLM",od]],["olmo2",["Olmo2ForCausalLM",id]],["mobilellm",["MobileLLMForCausalLM",sd]],["granite",["GraniteForCausalLM",cd]],["granitemoehybrid",["GraniteMoeHybridForCausalLM",dd]],["cohere",["CohereForCausalLM",md]],["gemma",["GemmaForCausalLM",_d]],["gemma2",["Gemma2ForCausalLM",gd]],["vaultgemma",["VaultGemmaForCausalLM",wd]],["gemma3_text",["Gemma3ForCausalLM",yd]],["helium",["HeliumForCausalLM",Ju]],["glm",["GlmForCausalLM",Zu]],["openelm",["OpenELMForCausalLM",xd]],["qwen2",["Qwen2ForCausalLM",Ed]],["qwen3",["Qwen3ForCausalLM",Cd]],["phi",["PhiForCausalLM",kd]],["phi3",["Phi3ForCausalLM",Fd]],["mpt",["MptForCausalLM",zd]],["opt",["OPTForCausalLM",Rd]],["mbart",["MBartForCausalLM",os]],["mistral",["MistralForCausalLM",gh]],["ministral",["MinistralForCausalLM",wh]],["ministral3",["Ministral3ForCausalLM",yh]],["ernie4_5",["Ernie4_5ForCausalLM",xh]],["starcoder2",["Starcoder2ForCausalLM",Eh]],["falcon",["FalconForCausalLM",Ch]],["trocr",["TrOCRForCausalLM",_h]],["stablelm",["StableLmForCausalLM",Dh]],["modernbert-decoder",["ModernBertDecoderForCausalLM",gr]],["phi3_v",["Phi3VForCausalLM",Un]]]),Ov=new Map([["multi_modality",["MultiModalityCausalLM",Zh]]]),P_=new Map([["bert",["BertForMaskedLM",Ce]],["neobert",["NeoBertForMaskedLM",Fe]],["modernbert",["ModernBertForMaskedLM",Oe]],["roformer",["RoFormerForMaskedLM",Qs]],["electra",["ElectraForMaskedLM",Ss]],["esm",["EsmForMaskedLM",ks]],["convbert",["ConvBertForMaskedLM",ft]],["camembert",["CamembertForMaskedLM",ce]],["deberta",["DebertaForMaskedLM",qe]],["deberta-v2",["DebertaV2ForMaskedLM",Tr]],["mpnet",["MPNetForMaskedLM",Os]],["albert",["AlbertForMaskedLM",Ke]],["distilbert",["DistilBertForMaskedLM",Hr]],["roberta",["RobertaForMaskedLM",ra]],["xlm",["XLMWithLMHeadModel",ia]],["xlm-roberta",["XLMRobertaForMaskedLM",mo]],["mobilebert",["MobileBertForMaskedLM",ze]],["squeezebert",["SqueezeBertForMaskedLM",ee]]]),C_=new Map([["bert",["BertForQuestionAnswering",fe]],["neobert",["NeoBertForQuestionAnswering",rt]],["roformer",["RoFormerForQuestionAnswering",Sr]],["electra",["ElectraForQuestionAnswering",R]],["convbert",["ConvBertForQuestionAnswering",Cs]],["camembert",["CamembertForQuestionAnswering",ut]],["deberta",["DebertaForQuestionAnswering",Mr]],["deberta-v2",["DebertaV2ForQuestionAnswering",$s]],["mpnet",["MPNetForQuestionAnswering",ue]],["albert",["AlbertForQuestionAnswering",Ye]],["distilbert",["DistilBertForQuestionAnswering",ir]],["roberta",["RobertaForQuestionAnswering",oa]],["xlm",["XLMForQuestionAnswering",ua]],["xlm-roberta",["XLMRobertaForQuestionAnswering",pa]],["mobilebert",["MobileBertForQuestionAnswering",nt]],["squeezebert",["SqueezeBertForQuestionAnswering",Me]]]),jl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Bn]],["idefics3",["Idefics3ForConditionalGeneration",jn]],["smolvlm",["SmolVLMForConditionalGeneration",dn]]]),S_=new Map([["llava",["LlavaForConditionalGeneration",Rn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",_a]],["moondream1",["Moondream1ForConditionalGeneration",fa]],["florence2",["Florence2ForConditionalGeneration",Ma]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Id]],["idefics3",["Idefics3ForConditionalGeneration",jn]],["smolvlm",["SmolVLMForConditionalGeneration",dn]],["paligemma",["PaliGemmaForConditionalGeneration",ba]],["llava_qwen2",["LlavaQwen2ForCausalLM",yo]],["gemma3n",["Gemma3nForConditionalGeneration",Nn]],["mistral3",["Mistral3ForConditionalGeneration",un]]]),I_=new Map([["ultravox",["UltravoxModel",zl]],["voxtral",["VoxtralForConditionalGeneration",l_]]]),Dv=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Bn]]]),$_=new Map([["vit",["ViTForImageClassification",jd]],["ijepa",["IJepaForImageClassification",Ud]],["pvt",["PvtForImageClassification",Hd]],["vit_msn",["ViTMSNForImageClassification",Jd]],["fastvit",["FastViTForImageClassification",tp]],["mobilevit",["MobileViTForImageClassification",op]],["mobilevitv2",["MobileViTV2ForImageClassification",ip]],["beit",["BeitForImageClassification",mp]],["deit",["DeiTForImageClassification",kp]],["hiera",["HieraForImageClassification",Fp]],["convnext",["ConvNextForImageClassification",im]],["convnextv2",["ConvNextV2ForImageClassification",cm]],["dinov2",["Dinov2ForImageClassification",dm]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",mm]],["resnet",["ResNetForImageClassification",Dp]],["swin",["SwinForImageClassification",zp]],["segformer",["SegformerForImageClassification",Ah]],["efficientnet",["EfficientNetForImageClassification",zh]],["mobilenet_v1",["MobileNetV1ForImageClassification",Rh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Vh]],["mobilenet_v3",["MobileNetV3ForImageClassification",Gh]],["mobilenet_v4",["MobileNetV4ForImageClassification",qh]]]),k_=new Map([["detr",["DetrForObjectDetection",_p]],["rt_detr",["RTDetrForObjectDetection",Mp]],["rt_detr_v2",["RTDetrV2ForObjectDetection",bp]],["rf_detr",["RFDetrForObjectDetection",xp]],["d_fine",["DFineForObjectDetection",Pp]],["table-transformer",["TableTransformerForObjectDetection",Sp]],["yolos",["YolosForObjectDetection",ym]]]),A_=new Map([["owlvit",["OwlViTForObjectDetection",cp]],["owlv2",["Owlv2ForObjectDetection",dp]],["grounding-dino",["GroundingDinoForObjectDetection",wm]]]),Yn=new Map([["detr",["DetrForSegmentation",tl]],["clipseg",["CLIPSegForImageSegmentation",Co]]]),F_=new Map([["segformer",["SegformerForSemanticSegmentation",Fh]],["sapiens",["SapiensForSemanticSegmentation",Gp]],["swin",["SwinForSemanticSegmentation",Bp]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Nh]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Uh]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Kh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Qh]]]),O_=new Map([["detr",["DetrForSegmentation",tl]],["maskformer",["MaskFormerForInstanceSegmentation",tm]]]),D_=new Map([["sam",["SamModel",Tm]],["sam2",["Sam2Model",$a]],["edgetam",["EdgeTamModel",Sm]],["sam3_tracker",["Sam3TrackerModel",Im]]]),L_=new Map([["wav2vec2",["Wav2Vec2ForCTC",Dm]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ym]],["unispeech",["UniSpeechForCTC",Gm]],["unispeech-sat",["UniSpeechSatForCTC",qm]],["wavlm",["WavLMForCTC",nh]],["hubert",["HubertForCTC",th]],["parakeet_ctc",["ParakeetForCTC",Rm]]]),z_=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Lm]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Zm]],["unispeech",["UniSpeechForSequenceClassification",Km]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Qm]],["wavlm",["WavLMForSequenceClassification",oh]],["hubert",["HubertForSequenceClassification",rh]],["audio-spectrogram-transformer",["ASTForAudioClassification",Mo]]]),B_=new Map([["wavlm",["WavLMForXVector",ah]]]),R_=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Xm]],["wavlm",["WavLMForAudioFrameClassification",ih]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",zm]],["pyannote",["PyAnnoteForAudioFrameClassification",jm]]]),N_=new Map([["vitmatte",["VitMatteForImageMatting",sp]]]),Lv=new Map([["patchtst",["PatchTSTForPrediction",n_]],["patchtsmixer",["PatchTSMixerForPrediction",a_]]]),j_=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Np]]]),V_=new Map([["dpt",["DPTForDepthEstimation",Vp]],["depth_anything",["DepthAnythingForDepthEstimation",Wp]],["glpn",["GLPNForDepthEstimation",sm]],["sapiens",["SapiensForDepthEstimation",Kp]],["depth_pro",["DepthProForDepthEstimation",Qp]],["metric3d",["Metric3DForDepthEstimation",Jp]],["metric3dv2",["Metric3Dv2ForDepthEstimation",Zp]]]),U_=new Map([["sapiens",["SapiensForNormalEstimation",Hp]]]),W_=new Map([["vitpose",["VitPoseForPoseEstimation",Gd]]]),G_=new Map([["clip",["CLIPVisionModelWithProjection",Ta]],["siglip",["SiglipVisionModel",dt]],["jina_clip",["JinaCLIPVisionModel",_n]]]),K_=[[$v,T.EncoderOnly],[kv,T.EncoderDecoder],[Fv,T.DecoderOnly],[Av,T.AutoEncoder],[T_,T.EncoderOnly],[E_,T.EncoderOnly],[Rl,T.Seq2Seq],[Bl,T.Seq2Seq],[Nl,T.DecoderOnly],[Ov,T.MultiModality],[P_,T.EncoderOnly],[C_,T.EncoderOnly],[jl,T.Vision2Seq],[S_,T.ImageTextToText],[I_,T.AudioTextToText],[$_,T.EncoderOnly],[Yn,T.EncoderOnly],[O_,T.EncoderOnly],[F_,T.EncoderOnly],[N_,T.EncoderOnly],[Lv,T.EncoderOnly],[j_,T.EncoderOnly],[V_,T.EncoderOnly],[U_,T.EncoderOnly],[W_,T.EncoderOnly],[k_,T.EncoderOnly],[A_,T.EncoderOnly],[D_,T.MaskGeneration],[L_,T.EncoderOnly],[z_,T.EncoderOnly],[v_,T.Seq2Seq],[x_,T.EncoderOnly],[B_,T.EncoderOnly],[R_,T.EncoderOnly],[G_,T.EncoderOnly]];for(const[g,M]of K_)for(const[j,ae]of g.values())b.set(j,M),x.set(ae,j),E.set(j,ae);const zv=[["MusicgenForConditionalGeneration",Ol,T.Musicgen],["Phi3VForCausalLM",Un,T.Phi3V],["CLIPTextModelWithProjection",xo,T.EncoderOnly],["SiglipTextModel",pn,T.EncoderOnly],["JinaCLIPTextModel",Jr,T.EncoderOnly],["ClapTextModelWithProjection",Ih,T.EncoderOnly],["ClapAudioModelWithProjection",$h,T.EncoderOnly],["DacEncoderModel",g_,T.EncoderOnly],["DacDecoderModel",M_,T.EncoderOnly],["MimiEncoderModel",p_,T.EncoderOnly],["MimiDecoderModel",m_,T.EncoderOnly],["SnacEncoderModel",b_,T.EncoderOnly],["SnacDecoderModel",y_,T.EncoderOnly],["Gemma3nForConditionalGeneration",Nn,T.ImageAudioTextToText],["SupertonicForConditionalGeneration",xl,T.Supertonic]];for(const[g,M,j]of zv)b.set(g,j),x.set(M,g),E.set(g,M);const H_=new Map([["modnet",Yn],["birefnet",Yn],["isnet",Yn],["ben",Yn]]);for(const[g,M]of H_.entries())M.set(g,["PreTrainedModel",z]),b.set(g,T.EncoderOnly),x.set(z,g),E.set(g,z);class Bv extends Ut{static MODEL_CLASS_MAPPINGS=K_.map(M=>M[0]);static BASE_IF_FAIL=!0}class Rv extends Ut{static MODEL_CLASS_MAPPINGS=[T_]}class Nv extends Ut{static MODEL_CLASS_MAPPINGS=[E_]}class jv extends Ut{static MODEL_CLASS_MAPPINGS=[Rl]}class Vv extends Ut{static MODEL_CLASS_MAPPINGS=[Bl]}class Uv extends Ut{static MODEL_CLASS_MAPPINGS=[v_]}class Wv extends Ut{static MODEL_CLASS_MAPPINGS=[x_]}class Gv extends Ut{static MODEL_CLASS_MAPPINGS=[Nl]}class Kv extends Ut{static MODEL_CLASS_MAPPINGS=[P_]}class Hv extends Ut{static MODEL_CLASS_MAPPINGS=[C_]}class qv extends Ut{static MODEL_CLASS_MAPPINGS=[jl]}class Qv extends Ut{static MODEL_CLASS_MAPPINGS=[$_]}class Xv extends Ut{static MODEL_CLASS_MAPPINGS=[Yn]}class Jv extends Ut{static MODEL_CLASS_MAPPINGS=[F_]}class Yv extends Ut{static MODEL_CLASS_MAPPINGS=[O_]}class Zv extends Ut{static MODEL_CLASS_MAPPINGS=[k_]}class ex extends Ut{static MODEL_CLASS_MAPPINGS=[A_]}class tx extends Ut{static MODEL_CLASS_MAPPINGS=[D_]}class rx extends Ut{static MODEL_CLASS_MAPPINGS=[L_]}class sx extends Ut{static MODEL_CLASS_MAPPINGS=[z_]}class nx extends Ut{static MODEL_CLASS_MAPPINGS=[B_]}class ox extends Ut{static MODEL_CLASS_MAPPINGS=[R_]}class ax extends Ut{static MODEL_CLASS_MAPPINGS=[Dv]}class ix extends Ut{static MODEL_CLASS_MAPPINGS=[N_]}class lx extends Ut{static MODEL_CLASS_MAPPINGS=[j_]}class cx extends Ut{static MODEL_CLASS_MAPPINGS=[V_]}class ux extends Ut{static MODEL_CLASS_MAPPINGS=[U_]}class dx extends Ut{static MODEL_CLASS_MAPPINGS=[W_]}class px extends Ut{static MODEL_CLASS_MAPPINGS=[G_]}class mx extends Ut{static MODEL_CLASS_MAPPINGS=[S_]}class hx extends Ut{static MODEL_CLASS_MAPPINGS=[I_]}class _x extends de{constructor({logits:M,past_key_values:j,encoder_outputs:ae,decoder_attentions:me=null,cross_attentions:_e=null}){super(),this.logits=M,this.past_key_values=j,this.encoder_outputs=ae,this.decoder_attentions=me,this.cross_attentions=_e}}class xt extends de{constructor({logits:M,...j}){super(),this.logits=M;const ae=Object.values(j);ae.length>0&&(this.attentions=ae)}}class q_ extends de{constructor({logits:M,embeddings:j}){super(),this.logits=M,this.embeddings=j}}class Pr extends de{constructor({logits:M}){super(),this.logits=M}}class $r extends de{constructor({logits:M}){super(),this.logits=M}}class Br extends de{constructor({start_logits:M,end_logits:j}){super(),this.start_logits=M,this.end_logits=j}}class rn extends de{constructor({logits:M}){super(),this.logits=M}}class fx extends de{constructor({logits:M,past_key_values:j}){super(),this.logits=M,this.past_key_values=j}}class Q_ extends de{constructor({alphas:M}){super(),this.alphas=M}}class X_ extends de{constructor({waveform:M,spectrogram:j}){super(),this.waveform=M,this.spectrogram=j}}}),"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var o=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,c={}){const p=await(0,n.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),d=p.feature_extractor_type,u=o[d];if(!u)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new u(p)}}}),"./src/models/auto/image_processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(c,p={}){const d=await(0,n.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),u=d.image_processor_type??d.feature_extractor_type;let f=i[u?.replace(/Fast$/,"")];return f||(u!==void 0&&console.warn(`Image processor type '${u}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=o.ImageProcessor),new f(d)}}}),"./src/models/auto/processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>c});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(d,u={}){const f=await(0,n.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,u),{image_processor_type:_,feature_extractor_type:y,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,u);if(!_&&!y)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const I=a[_.replace(/Fast$/,"")];if(!I)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new I(f)}if(y){const I=a[y];if(I)w.image_processor=new I(f);else{const T=l[y];if(!T)throw new Error(`Unknown feature_extractor_type: '${y}'.`);w.feature_extractor=new T(f)}}const v={};return new o.Processor(v,w,null)}}}),"./src/models/beit/image_processing_beit.js":((e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/bit/image_processing_bit.js":((e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/chinese_clip/image_processing_chinese_clip.js":((e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/clap/feature_extraction_clap.js":((e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,c,p){let d;const u=a.length-l;if(u>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(u+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(u<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/convnext/image_processing_convnext.js":((e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){const l=this.size?.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const c=Math.floor(l/this.crop_pct),[p,d]=this.get_resize_output_image_size(a,{shortest_edge:c});a=await a.resize(p,d,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class o extends n{}}),"./src/models/dac/feature_extraction_dac.js":((e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>n});var s=t("./src/models/encodec/feature_extraction_encodec.js");class n extends s.EncodecFeatureExtractor{}}),"./src/models/deit/image_processing_deit.js":((e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/detr/image_processing_detr.js":((e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(l){const c=await super._call(l),p=[c.pixel_values.dims[0],64,64],d=(0,n.full)(p,1n);return{...c,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends o{}}),"./src/models/dinov3_vit/image_processing_dinov3_vit.js":((e,r,t)=>{t.r(r),t.d(r,{DINOv3ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/donut/image_processing_donut.js":((e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(a,l,c,p={}){const[d,u,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let y=this.image_std;Array.isArray(y)||(y=new Array(f).fill(_));const k=_.map((w,v)=>-w/y[v]);return super.pad_image(a,l,c,{center:!0,constant_values:k,...p})}}class o extends n{}}),"./src/models/dpt/image_processing_dpt.js":((e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/efficientnet/image_processing_efficientnet.js":((e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}}),"./src/models/encodec/feature_extraction_encodec.js":((e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const c=[1,l,a.length/l];return{input_values:new n.Tensor("float32",a,c)}}}}),"./src/models/feature_extractors.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>o.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>n.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>a.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>w.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,ParakeetFeatureExtractor:()=>c.ParakeetFeatureExtractor,PyAnnoteFeatureExtractor:()=>p.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>u.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>f.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>_.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>k.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),n=t("./src/models/encodec/feature_extraction_encodec.js"),o=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=t("./src/models/moonshine/feature_extraction_moonshine.js"),c=t("./src/models/parakeet/feature_extraction_parakeet.js"),p=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),u=t("./src/models/snac/feature_extraction_snac.js"),f=t("./src/models/speecht5/feature_extraction_speecht5.js"),_=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),k=t("./src/models/whisper/feature_extraction_whisper.js"),w=t("./src/base/image_processors_utils.js")}),"./src/models/florence2/processing_florence2.js":((e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(l,c,p){super(l,c,p);const{tasks_answer_post_processing_type:d,task_prompts_without_inputs:u,task_prompts_with_input:f}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(d??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(f??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const c=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))c.push(this.task_prompts_without_inputs.get(p));else{for(const[d,u]of this.task_prompts_with_input)if(p.includes(d)){c.push(u.replaceAll("{input}",p).replaceAll(d,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const d=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let u;switch(d){case"pure_text":u=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),y=[],k=[];for(const[w,v,...I]of _)y.push(v?v.trim():y.at(-1)??""),k.push(I.map((T,b)=>(Number(T)+.5)/this.size_per_bin*p[b%2]));u={labels:y,[f]:k};break;default:throw new Error(`Task "${c}" (of type "${d}") not yet implemented.`)}return{[c]:u}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),u=c?this.tokenizer(this.construct_prompts(c),p):{};return{...d,...u}}}}),"./src/models/gemma3n/feature_extraction_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nAudioFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const{fft_length:c,feature_size:p,min_frequency:d,max_frequency:u,sampling_rate:f,frame_length:_}=this.config,y=(0,o.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=y,this.window=(0,o.window_function)(_,"hann")}async _extract_fbank_features(l,c){return(0,o.spectrogram)(l,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(l,{max_length:c=48e4,truncation:p=!0,padding:d=!0,pad_to_multiple_of:u=128}={}){if((0,s.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),p&&l.length>c&&(l=l.slice(0,c)),d&&l.length%u!==0){const y=u-l.length%u,k=new Float64Array(l.length+y);k.set(l),this.config.padding_value!==0&&k.fill(this.config.padding_value,l.length),l=k}const f=await this._extract_fbank_features(l,this.config.max_length),_=(0,n.full)([1,f.dims[0]],!0);return{input_features:f.unsqueeze_(0),input_features_mask:_}}}}),"./src/models/gemma3n/processing_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nProcessor:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js");t("./src/utils/image.js"),t("./src/utils/audio.js");class a extends s.Processor{static image_processor_class=n.AutoImageProcessor;static feature_extractor_class=o.AutoFeatureExtractor;static tokenizer_class=i.AutoTokenizer;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(c,p,d){super(c,p,d),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:u,boa_token:f,audio_token:_,eoa_token:y,image_token_id:k,boi_token:w,image_token:v,eoi_token:I}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const T=_.repeat(this.audio_seq_length);this.full_audio_sequence=` +`)}}class c extends l{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:y=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:v=.02,skip_special_tokens:I=!0,decode_kwargs:T={}}={}){super(d,{skip_prompt:u,skip_special_tokens:I,callback_function:f,token_callback_function:_,decode_kwargs:T}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=y,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=v,this.waiting_for_timestamp=!1}put(d){if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const u=d[0];if(u.length===1){const f=Number(u[0])-this.timestamp_begin;if(f>=0){const _=f*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(_):this.on_chunk_start?.(_),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(u);return}}return super.put(d)}end(){super.end(),this.on_finalize?.()}}}),"./src/models.js":((e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Mo,ASTModel:()=>go,ASTPreTrainedModel:()=>fo,AlbertForMaskedLM:()=>Ke,AlbertForQuestionAnswering:()=>Ye,AlbertForSequenceClassification:()=>Je,AlbertModel:()=>Xe,AlbertPreTrainedModel:()=>$e,ArceeForCausalLM:()=>Ku,ArceeModel:()=>Gu,ArceePreTrainedModel:()=>vi,AutoModel:()=>Bv,AutoModelForAudioClassification:()=>sx,AutoModelForAudioFrameClassification:()=>ox,AutoModelForAudioTextToText:()=>hx,AutoModelForCTC:()=>rx,AutoModelForCausalLM:()=>Gv,AutoModelForDepthEstimation:()=>cx,AutoModelForDocumentQuestionAnswering:()=>ax,AutoModelForImageClassification:()=>Qv,AutoModelForImageFeatureExtraction:()=>px,AutoModelForImageMatting:()=>ix,AutoModelForImageSegmentation:()=>Xv,AutoModelForImageTextToText:()=>mx,AutoModelForImageToImage:()=>lx,AutoModelForMaskGeneration:()=>tx,AutoModelForMaskedLM:()=>Kv,AutoModelForNormalEstimation:()=>ux,AutoModelForObjectDetection:()=>Zv,AutoModelForPoseEstimation:()=>dx,AutoModelForQuestionAnswering:()=>Hv,AutoModelForSemanticSegmentation:()=>Jv,AutoModelForSeq2SeqLM:()=>jv,AutoModelForSequenceClassification:()=>Rv,AutoModelForSpeechSeq2Seq:()=>Vv,AutoModelForTextToSpectrogram:()=>Uv,AutoModelForTextToWaveform:()=>Wv,AutoModelForTokenClassification:()=>Nv,AutoModelForUniversalSegmentation:()=>Yv,AutoModelForVision2Seq:()=>qv,AutoModelForXVector:()=>nx,AutoModelForZeroShotObjectDetection:()=>ex,BartForConditionalGeneration:()=>Yt,BartForSequenceClassification:()=>hr,BartModel:()=>ds,BartPretrainedModel:()=>Er,BaseModelOutput:()=>be,BeitForImageClassification:()=>hp,BeitModel:()=>mp,BeitPreTrainedModel:()=>tl,BertForMaskedLM:()=>Ce,BertForQuestionAnswering:()=>fe,BertForSequenceClassification:()=>ge,BertForTokenClassification:()=>De,BertModel:()=>xe,BertPreTrainedModel:()=>ve,BlenderbotForConditionalGeneration:()=>_r,BlenderbotModel:()=>Zt,BlenderbotPreTrainedModel:()=>vr,BlenderbotSmallForConditionalGeneration:()=>Js,BlenderbotSmallModel:()=>Ur,BlenderbotSmallPreTrainedModel:()=>lr,BloomForCausalLM:()=>Ld,BloomModel:()=>Dd,BloomPreTrainedModel:()=>Ui,CLIPModel:()=>vo,CLIPPreTrainedModel:()=>Ls,CLIPSegForImageSegmentation:()=>Co,CLIPSegModel:()=>Po,CLIPSegPreTrainedModel:()=>fn,CLIPTextModel:()=>va,CLIPTextModelWithProjection:()=>xo,CLIPVisionModel:()=>xa,CLIPVisionModelWithProjection:()=>Ta,CamembertForMaskedLM:()=>ce,CamembertForQuestionAnswering:()=>ut,CamembertForSequenceClassification:()=>ye,CamembertForTokenClassification:()=>et,CamembertModel:()=>Z,CamembertPreTrainedModel:()=>G,CausalLMOutput:()=>rn,CausalLMOutputWithPast:()=>fx,ChineseCLIPModel:()=>Eo,ChineseCLIPPreTrainedModel:()=>Ea,ClapAudioModelWithProjection:()=>kh,ClapModel:()=>Ih,ClapPreTrainedModel:()=>Oa,ClapTextModelWithProjection:()=>$h,CodeGenForCausalLM:()=>Be,CodeGenModel:()=>Pe,CodeGenPreTrainedModel:()=>ie,CohereForCausalLM:()=>hd,CohereModel:()=>md,CoherePreTrainedModel:()=>Fi,ConvBertForMaskedLM:()=>ft,ConvBertForQuestionAnswering:()=>Cs,ConvBertForSequenceClassification:()=>qt,ConvBertForTokenClassification:()=>Ps,ConvBertModel:()=>Bs,ConvBertPreTrainedModel:()=>Qr,ConvNextForImageClassification:()=>lm,ConvNextModel:()=>im,ConvNextPreTrainedModel:()=>fl,ConvNextV2ForImageClassification:()=>um,ConvNextV2Model:()=>cm,ConvNextV2PreTrainedModel:()=>gl,DFineForObjectDetection:()=>Cp,DFineModel:()=>Pp,DFinePreTrainedModel:()=>il,DINOv3ConvNextModel:()=>Mm,DINOv3ConvNextPreTrainedModel:()=>gm,DINOv3ViTModel:()=>fm,DINOv3ViTPreTrainedModel:()=>_m,DPTForDepthEstimation:()=>Up,DPTModel:()=>Vp,DPTPreTrainedModel:()=>ml,DacDecoderModel:()=>w_,DacDecoderOutput:()=>f_,DacEncoderModel:()=>M_,DacEncoderOutput:()=>__,DacModel:()=>g_,DacPreTrainedModel:()=>ja,DebertaForMaskedLM:()=>qe,DebertaForQuestionAnswering:()=>Mr,DebertaForSequenceClassification:()=>Tt,DebertaForTokenClassification:()=>kt,DebertaModel:()=>Mt,DebertaPreTrainedModel:()=>He,DebertaV2ForMaskedLM:()=>Tr,DebertaV2ForQuestionAnswering:()=>$s,DebertaV2ForSequenceClassification:()=>Is,DebertaV2ForTokenClassification:()=>Dr,DebertaV2Model:()=>ar,DebertaV2PreTrainedModel:()=>dr,DecisionTransformerModel:()=>Yh,DecisionTransformerPreTrainedModel:()=>Jh,DeiTForImageClassification:()=>Ap,DeiTModel:()=>kp,DeiTPreTrainedModel:()=>cl,DepthAnythingForDepthEstimation:()=>Gp,DepthAnythingPreTrainedModel:()=>Wp,DepthProForDepthEstimation:()=>Xp,DepthProPreTrainedModel:()=>Qp,DetrForObjectDetection:()=>fp,DetrForSegmentation:()=>rl,DetrModel:()=>_p,DetrObjectDetectionOutput:()=>sl,DetrPreTrainedModel:()=>Ca,DetrSegmentationOutput:()=>gp,Dinov2ForImageClassification:()=>pm,Dinov2Model:()=>dm,Dinov2PreTrainedModel:()=>Ml,Dinov2WithRegistersForImageClassification:()=>hm,Dinov2WithRegistersModel:()=>mm,Dinov2WithRegistersPreTrainedModel:()=>wl,DistilBertForMaskedLM:()=>Hr,DistilBertForQuestionAnswering:()=>ir,DistilBertForSequenceClassification:()=>ts,DistilBertForTokenClassification:()=>wr,DistilBertModel:()=>zr,DistilBertPreTrainedModel:()=>Lr,DonutSwinModel:()=>am,DonutSwinPreTrainedModel:()=>om,EdgeTamModel:()=>Im,EfficientNetForImageClassification:()=>Bh,EfficientNetModel:()=>zh,EfficientNetPreTrainedModel:()=>Fl,ElectraForMaskedLM:()=>Ss,ElectraForQuestionAnswering:()=>R,ElectraForSequenceClassification:()=>C,ElectraForTokenClassification:()=>q,ElectraModel:()=>yt,ElectraPreTrainedModel:()=>Kr,Ernie4_5ForCausalLM:()=>Th,Ernie4_5Model:()=>xh,Ernie4_5PreTrainedModel:()=>Sl,EsmForMaskedLM:()=>ks,EsmForSequenceClassification:()=>As,EsmForTokenClassification:()=>Fs,EsmModel:()=>Rs,EsmPreTrainedModel:()=>rs,ExaoneForCausalLM:()=>rd,ExaoneModel:()=>td,ExaonePreTrainedModel:()=>Ci,FalconForCausalLM:()=>Sh,FalconModel:()=>Ch,FalconPreTrainedModel:()=>$l,FastViTForImageClassification:()=>rp,FastViTModel:()=>tp,FastViTPreTrainedModel:()=>Xi,Florence2ForConditionalGeneration:()=>Ma,Florence2PreTrainedModel:()=>ga,GLPNForDepthEstimation:()=>nm,GLPNModel:()=>sm,GLPNPreTrainedModel:()=>_l,GPT2LMHeadModel:()=>So,GPT2Model:()=>Kn,GPT2PreTrainedModel:()=>Gn,GPTBigCodeForCausalLM:()=>V,GPTBigCodeModel:()=>L,GPTBigCodePreTrainedModel:()=>A,GPTJForCausalLM:()=>P,GPTJModel:()=>h,GPTJPreTrainedModel:()=>Xn,GPTNeoForCausalLM:()=>$o,GPTNeoModel:()=>qn,GPTNeoPreTrainedModel:()=>Mn,GPTNeoXForCausalLM:()=>Ao,GPTNeoXModel:()=>ko,GPTNeoXPreTrainedModel:()=>Qn,Gemma2ForCausalLM:()=>Md,Gemma2Model:()=>gd,Gemma2PreTrainedModel:()=>Di,Gemma3ForCausalLM:()=>vd,Gemma3Model:()=>yd,Gemma3PreTrainedModel:()=>zi,Gemma3nForConditionalGeneration:()=>Nn,Gemma3nPreTrainedModel:()=>en,GemmaForCausalLM:()=>fd,GemmaModel:()=>_d,GemmaPreTrainedModel:()=>Oi,GlmForCausalLM:()=>ed,GlmModel:()=>Zu,GlmPreTrainedModel:()=>Pi,GraniteForCausalLM:()=>ud,GraniteModel:()=>cd,GraniteMoeHybridForCausalLM:()=>pd,GraniteMoeHybridModel:()=>dd,GraniteMoeHybridPreTrainedModel:()=>Ai,GranitePreTrainedModel:()=>ki,GroundingDinoForObjectDetection:()=>bm,GroundingDinoPreTrainedModel:()=>wm,GroupViTModel:()=>ep,GroupViTPreTrainedModel:()=>Zd,HeliumForCausalLM:()=>Yu,HeliumModel:()=>Ju,HeliumPreTrainedModel:()=>Ei,HieraForImageClassification:()=>Op,HieraModel:()=>Fp,HieraPreTrainedModel:()=>ul,HubertForCTC:()=>rh,HubertForSequenceClassification:()=>sh,HubertModel:()=>th,HubertPreTrainedModel:()=>Ev,IJepaForImageClassification:()=>Wd,IJepaModel:()=>Ud,IJepaPreTrainedModel:()=>Hi,Idefics3ForConditionalGeneration:()=>jn,Idefics3PreTrainedModel:()=>ya,ImageMattingOutput:()=>X_,JAISLMHeadModel:()=>gn,JAISModel:()=>Io,JAISPreTrainedModel:()=>Hn,JinaCLIPModel:()=>hn,JinaCLIPPreTrainedModel:()=>mn,JinaCLIPTextModel:()=>Jr,JinaCLIPVisionModel:()=>_n,Lfm2ForCausalLM:()=>qu,Lfm2Model:()=>Hu,Lfm2PreTrainedModel:()=>xi,LiteWhisperForConditionalGeneration:()=>ha,Llama4ForCausalLM:()=>Vt,Llama4PreTrainedModel:()=>Ot,LlamaForCausalLM:()=>vt,LlamaModel:()=>at,LlamaPreTrainedModel:()=>Qe,LlavaForConditionalGeneration:()=>Rn,LlavaOnevisionForConditionalGeneration:()=>_a,LlavaPreTrainedModel:()=>bo,LlavaQwen2ForCausalLM:()=>yo,LongT5ForConditionalGeneration:()=>sr,LongT5Model:()=>Xt,LongT5PreTrainedModel:()=>br,M2M100ForConditionalGeneration:()=>Om,M2M100Model:()=>Fm,M2M100PreTrainedModel:()=>vl,MBartForCausalLM:()=>os,MBartForConditionalGeneration:()=>ps,MBartForSequenceClassification:()=>yr,MBartModel:()=>Xr,MBartPreTrainedModel:()=>Ir,MPNetForMaskedLM:()=>Os,MPNetForQuestionAnswering:()=>ue,MPNetForSequenceClassification:()=>js,MPNetForTokenClassification:()=>Dn,MPNetModel:()=>Ns,MPNetPreTrainedModel:()=>Kt,MT5ForConditionalGeneration:()=>ns,MT5Model:()=>qr,MT5PreTrainedModel:()=>Ht,MarianMTModel:()=>Am,MarianModel:()=>km,MarianPreTrainedModel:()=>yl,MaskFormerForInstanceSegmentation:()=>rm,MaskFormerModel:()=>tm,MaskFormerPreTrainedModel:()=>hl,MaskedLMOutput:()=>$r,Metric3DForDepthEstimation:()=>Yp,Metric3DPreTrainedModel:()=>Jp,Metric3Dv2ForDepthEstimation:()=>em,Metric3Dv2PreTrainedModel:()=>Zp,MgpstrForSceneTextRecognition:()=>s_,MgpstrModelOutput:()=>t_,MgpstrPreTrainedModel:()=>r_,MimiDecoderModel:()=>h_,MimiDecoderOutput:()=>d_,MimiEncoderModel:()=>m_,MimiEncoderOutput:()=>u_,MimiModel:()=>p_,MimiPreTrainedModel:()=>Na,Ministral3ForCausalLM:()=>vh,Ministral3Model:()=>yh,Ministral3PreTrainedModel:()=>Cl,MinistralForCausalLM:()=>bh,MinistralModel:()=>wh,MinistralPreTrainedModel:()=>Pl,Mistral3ForConditionalGeneration:()=>un,MistralForCausalLM:()=>Mh,MistralModel:()=>gh,MistralPreTrainedModel:()=>El,MobileBertForMaskedLM:()=>ze,MobileBertForQuestionAnswering:()=>nt,MobileBertForSequenceClassification:()=>Ue,MobileBertModel:()=>Nr,MobileBertPreTrainedModel:()=>ss,MobileLLMForCausalLM:()=>nd,MobileLLMModel:()=>sd,MobileLLMPreTrainedModel:()=>Si,MobileNetV1ForImageClassification:()=>Nh,MobileNetV1ForSemanticSegmentation:()=>jh,MobileNetV1Model:()=>Rh,MobileNetV1PreTrainedModel:()=>La,MobileNetV2ForImageClassification:()=>Uh,MobileNetV2ForSemanticSegmentation:()=>Wh,MobileNetV2Model:()=>Vh,MobileNetV2PreTrainedModel:()=>za,MobileNetV3ForImageClassification:()=>Kh,MobileNetV3ForSemanticSegmentation:()=>Hh,MobileNetV3Model:()=>Gh,MobileNetV3PreTrainedModel:()=>Ba,MobileNetV4ForImageClassification:()=>Qh,MobileNetV4ForSemanticSegmentation:()=>Xh,MobileNetV4Model:()=>qh,MobileNetV4PreTrainedModel:()=>Ra,MobileViTForImageClassification:()=>ap,MobileViTModel:()=>op,MobileViTPreTrainedModel:()=>Ji,MobileViTV2ForImageClassification:()=>lp,MobileViTV2Model:()=>ip,MobileViTV2PreTrainedModel:()=>Yi,ModelOutput:()=>de,ModernBertDecoderForCausalLM:()=>gr,ModernBertDecoderModel:()=>It,ModernBertDecoderPreTrainedModel:()=>Rt,ModernBertForMaskedLM:()=>Oe,ModernBertForSequenceClassification:()=>ot,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>Ne,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>fa,MoonshineForConditionalGeneration:()=>zn,MoonshineModel:()=>yi,MoonshinePreTrainedModel:()=>wo,MptForCausalLM:()=>Bd,MptModel:()=>zd,MptPreTrainedModel:()=>Wi,MultiModalityCausalLM:()=>e_,MultiModalityPreTrainedModel:()=>Zh,MusicgenForCausalLM:()=>Iv,MusicgenForConditionalGeneration:()=>Dl,MusicgenModel:()=>Sv,MusicgenPreTrainedModel:()=>Ol,NanoChatForCausalLM:()=>Pa,NanoChatModel:()=>Us,NanoChatPreTrainedModel:()=>xr,NeoBertForMaskedLM:()=>Fe,NeoBertForQuestionAnswering:()=>rt,NeoBertForSequenceClassification:()=>tt,NeoBertForTokenClassification:()=>Re,NeoBertModel:()=>We,NeoBertPreTrainedModel:()=>Ee,NomicBertModel:()=>zt,NomicBertPreTrainedModel:()=>Or,OPTForCausalLM:()=>Nd,OPTModel:()=>Rd,OPTPreTrainedModel:()=>Gi,Olmo2ForCausalLM:()=>ld,Olmo2Model:()=>id,Olmo2PreTrainedModel:()=>$i,OlmoForCausalLM:()=>ad,OlmoModel:()=>od,OlmoPreTrainedModel:()=>Ii,OpenELMForCausalLM:()=>Td,OpenELMModel:()=>xd,OpenELMPreTrainedModel:()=>Bi,OwlViTForObjectDetection:()=>up,OwlViTModel:()=>cp,OwlViTPreTrainedModel:()=>Zi,Owlv2ForObjectDetection:()=>pp,Owlv2Model:()=>dp,Owlv2PreTrainedModel:()=>el,PaliGemmaForConditionalGeneration:()=>ba,PaliGemmaPreTrainedModel:()=>wa,ParakeetForCTC:()=>Nm,ParakeetPreTrainedModel:()=>Rm,PatchTSMixerForPrediction:()=>i_,PatchTSMixerModel:()=>a_,PatchTSMixerPreTrainedModel:()=>zl,PatchTSTForPrediction:()=>o_,PatchTSTModel:()=>n_,PatchTSTPreTrainedModel:()=>Ll,Phi3ForCausalLM:()=>Od,Phi3Model:()=>Fd,Phi3PreTrainedModel:()=>Vi,Phi3VForCausalLM:()=>Un,Phi3VPreTrainedModel:()=>Vn,PhiForCausalLM:()=>Ad,PhiModel:()=>kd,PhiPreTrainedModel:()=>ji,PreTrainedModel:()=>z,PretrainedMixin:()=>Ut,PvtForImageClassification:()=>qd,PvtModel:()=>Hd,PvtPreTrainedModel:()=>qi,PyAnnoteForAudioFrameClassification:()=>Vm,PyAnnoteModel:()=>jm,PyAnnotePreTrainedModel:()=>xl,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>Pd,Qwen2Model:()=>Ed,Qwen2PreTrainedModel:()=>Ri,Qwen2VLForConditionalGeneration:()=>$d,Qwen2VLPreTrainedModel:()=>Id,Qwen3ForCausalLM:()=>Sd,Qwen3Model:()=>Cd,Qwen3PreTrainedModel:()=>Ni,RFDetrForObjectDetection:()=>Tp,RFDetrModel:()=>xp,RFDetrObjectDetectionOutput:()=>Ep,RFDetrPreTrainedModel:()=>al,RTDetrForObjectDetection:()=>wp,RTDetrModel:()=>Mp,RTDetrObjectDetectionOutput:()=>Fo,RTDetrPreTrainedModel:()=>nl,RTDetrV2ForObjectDetection:()=>yp,RTDetrV2Model:()=>bp,RTDetrV2ObjectDetectionOutput:()=>vp,RTDetrV2PreTrainedModel:()=>ol,ResNetForImageClassification:()=>Lp,ResNetModel:()=>Dp,ResNetPreTrainedModel:()=>dl,RoFormerForMaskedLM:()=>Qs,RoFormerForQuestionAnswering:()=>Sr,RoFormerForSequenceClassification:()=>Xs,RoFormerForTokenClassification:()=>or,RoFormerModel:()=>qs,RoFormerPreTrainedModel:()=>Rr,RobertaForMaskedLM:()=>ra,RobertaForQuestionAnswering:()=>oa,RobertaForSequenceClassification:()=>sa,RobertaForTokenClassification:()=>na,RobertaModel:()=>po,RobertaPreTrainedModel:()=>Ds,Sam2ImageSegmentationOutput:()=>Cm,Sam2Model:()=>$a,Sam2PreTrainedModel:()=>Sm,Sam3TrackerModel:()=>$m,SamImageSegmentationOutput:()=>Pm,SamModel:()=>Em,SamPreTrainedModel:()=>Tm,SapiensForDepthEstimation:()=>Hp,SapiensForNormalEstimation:()=>qp,SapiensForSemanticSegmentation:()=>Kp,SapiensPreTrainedModel:()=>Ia,SegformerForImageClassification:()=>Fh,SegformerForSemanticSegmentation:()=>Oh,SegformerModel:()=>Cv,SegformerPreTrainedModel:()=>Da,Seq2SeqLMOutput:()=>_x,SequenceClassifierOutput:()=>xt,SiglipModel:()=>To,SiglipPreTrainedModel:()=>Wn,SiglipTextModel:()=>pn,SiglipVisionModel:()=>dt,SmolLM3ForCausalLM:()=>Xu,SmolLM3Model:()=>Qu,SmolLM3PreTrainedModel:()=>Ti,SmolVLMForConditionalGeneration:()=>dn,SnacDecoderModel:()=>v_,SnacEncoderModel:()=>y_,SnacModel:()=>b_,SnacPreTrainedModel:()=>Va,SpeechT5ForSpeechToText:()=>dh,SpeechT5ForTextToSpeech:()=>ph,SpeechT5HifiGan:()=>mh,SpeechT5Model:()=>Pv,SpeechT5PreTrainedModel:()=>Fa,SqueezeBertForMaskedLM:()=>ee,SqueezeBertForQuestionAnswering:()=>Me,SqueezeBertForSequenceClassification:()=>se,SqueezeBertModel:()=>U,SqueezeBertPreTrainedModel:()=>$,StableLmForCausalLM:()=>Lh,StableLmModel:()=>Dh,StableLmPreTrainedModel:()=>Al,Starcoder2ForCausalLM:()=>Ph,Starcoder2Model:()=>Eh,Starcoder2PreTrainedModel:()=>Il,StyleTextToSpeech2Model:()=>uh,StyleTextToSpeech2PreTrainedModel:()=>ch,SupertonicForConditionalGeneration:()=>Tl,SupertonicPreTrainedModel:()=>hh,Swin2SRForImageSuperResolution:()=>jp,Swin2SRModel:()=>Np,Swin2SRPreTrainedModel:()=>pl,SwinForImageClassification:()=>Bp,SwinForSemanticSegmentation:()=>Rp,SwinModel:()=>zp,SwinPreTrainedModel:()=>Sa,T5ForConditionalGeneration:()=>rr,T5Model:()=>Et,T5PreTrainedModel:()=>$t,TableTransformerForObjectDetection:()=>Ip,TableTransformerModel:()=>Sp,TableTransformerObjectDetectionOutput:()=>$p,TableTransformerPreTrainedModel:()=>ll,TokenClassifierOutput:()=>Pr,TrOCRForCausalLM:()=>fh,TrOCRPreTrainedModel:()=>_h,UltravoxModel:()=>Bl,UltravoxPreTrainedModel:()=>l_,UniSpeechForCTC:()=>Km,UniSpeechForSequenceClassification:()=>Hm,UniSpeechModel:()=>Gm,UniSpeechPreTrainedModel:()=>ka,UniSpeechSatForAudioFrameClassification:()=>Jm,UniSpeechSatForCTC:()=>Qm,UniSpeechSatForSequenceClassification:()=>Xm,UniSpeechSatModel:()=>qm,UniSpeechSatPreTrainedModel:()=>Oo,VaultGemmaForCausalLM:()=>bd,VaultGemmaModel:()=>wd,VaultGemmaPreTrainedModel:()=>Li,ViTForImageClassification:()=>Vd,ViTMAEModel:()=>Xd,ViTMAEPreTrainedModel:()=>Qd,ViTMSNForImageClassification:()=>Yd,ViTMSNModel:()=>Jd,ViTMSNPreTrainedModel:()=>Qi,ViTModel:()=>jd,ViTPreTrainedModel:()=>Ki,VisionEncoderDecoderModel:()=>Bn,VitMatteForImageMatting:()=>np,VitMattePreTrainedModel:()=>sp,VitPoseForPoseEstimation:()=>Kd,VitPosePreTrainedModel:()=>Gd,VitsModel:()=>kl,VitsModelOutput:()=>J_,VitsPreTrainedModel:()=>Ah,VoxtralForConditionalGeneration:()=>c_,Wav2Vec2BertForCTC:()=>Zm,Wav2Vec2BertForSequenceClassification:()=>eh,Wav2Vec2BertModel:()=>Ym,Wav2Vec2BertPreTrainedModel:()=>Aa,Wav2Vec2ForAudioFrameClassification:()=>Bm,Wav2Vec2ForCTC:()=>Lm,Wav2Vec2ForSequenceClassification:()=>zm,Wav2Vec2Model:()=>Dm,Wav2Vec2PreTrainedModel:()=>tn,WavLMForAudioFrameClassification:()=>lh,WavLMForCTC:()=>oh,WavLMForSequenceClassification:()=>ah,WavLMForXVector:()=>ih,WavLMModel:()=>nh,WavLMPreTrainedModel:()=>Jn,WeSpeakerResNetModel:()=>Wm,WeSpeakerResNetPreTrainedModel:()=>Um,WhisperForConditionalGeneration:()=>Ln,WhisperModel:()=>ma,WhisperPreTrainedModel:()=>Vs,XLMForQuestionAnswering:()=>ua,XLMForSequenceClassification:()=>la,XLMForTokenClassification:()=>ca,XLMModel:()=>aa,XLMPreTrainedModel:()=>Ys,XLMRobertaForMaskedLM:()=>mo,XLMRobertaForQuestionAnswering:()=>pa,XLMRobertaForSequenceClassification:()=>ho,XLMRobertaForTokenClassification:()=>_o,XLMRobertaModel:()=>da,XLMRobertaPreTrainedModel:()=>Zs,XLMWithLMHeadModel:()=>ia,XVectorOutput:()=>Q_,YolosForObjectDetection:()=>vm,YolosModel:()=>ym,YolosObjectDetectionOutput:()=>xm,YolosPreTrainedModel:()=>bl});var s=t("./src/configs.js"),n=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),u=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),y=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),v=t("./src/models/whisper/generation_whisper.js"),I=t("./src/models/whisper/common_whisper.js");const T={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,Supertonic:13},b=new Map,E=new Map,x=new Map;async function S(g,M,j){let ae=j.config?.["transformers.js_config"]??{},me=j.device??ae.device;me&&typeof me!="string"&&(me.hasOwnProperty(M)?me=me[M]:(console.warn(`device not specified for "${M}". Using the default device.`),me=null));const _e=me??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,n.deviceToExecutionProviders)(_e),Le=ae.device_config??{};Le.hasOwnProperty(_e)&&(ae={...ae,...Le[_e]});let Ge=j.dtype??ae.dtype;if(typeof Ge!="string"&&(Ge&&Ge.hasOwnProperty(M)?Ge=Ge[M]:(Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${M}". Using the default dtype (${Ge}) for this device (${_e}).`))),Ge===o.DATA_TYPES.auto){let At=ae.dtype;typeof At!="string"&&(At=At?.[M]),At&&At!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(At)?Ge=At:Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32}const st=Ge;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(st)){if(st===o.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${st}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const wt=ae.kv_cache_dtype,bt=wt?typeof wt=="string"?wt:wt[st]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const Pt={dtype:st,kv_cache_dtype:bt,device:_e},mt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[st],Lt=`${M}${mt}.onnx`,_t=`${j.subfolder??""}/${Lt}`,pt={...j.session_options};pt.executionProviders??=Se;const Ft=ae.free_dimension_overrides;Ft?pt.freeDimensionOverrides??=Ft:_e.startsWith("webnn")&&!pt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${_e}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Wt=w.apis.IS_NODE_ENV&&w.env.useFSCache,er=(0,l.getModelFile)(g,_t,!0,j,Wt),nr=j.use_external_data_format??ae.use_external_data_format;let pr=[];if(nr){let At;typeof nr=="object"?nr.hasOwnProperty(Lt)?At=nr[Lt]:nr.hasOwnProperty(M)?At=nr[M]:At=!1:At=nr;const cr=+At;if(cr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${cr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let kr=0;kr{const eo=await(0,l.getModelFile)(g,Wr,!0,j,Wt);ms(eo instanceof Uint8Array?{path:wn,data:eo}:wn)}))}}else pt.externalData!==void 0&&(pr=pt.externalData.map(async At=>{if(typeof At.data=="string"){const cr=await(0,l.getModelFile)(g,At.data,!0,j);return{...At,data:cr}}return At}));if(pr.length>0){const At=await Promise.all(pr);w.apis.IS_NODE_ENV||(pt.externalData=At)}if(_e==="webgpu"){const At=(0,s.getCacheShapes)(j.config,{prefix:"present"});if(Object.keys(At).length>0&&!(0,n.isONNXProxy)()){const cr={};for(const kr in At)cr[kr]="gpu-buffer";pt.preferredOutputLocation=cr}}return{buffer_or_path:await er,session_options:pt,session_config:Pt}}async function O(g,M,j){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const{buffer_or_path:me,session_options:_e,session_config:Se}=await S(g,M[ae],j),Le=await(0,n.createInferenceSession)(me,_e,Se);return[ae,Le]})))}async function F(g,M,j){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const me=await(0,l.getModelJSON)(g,M[ae],!1,j);return[ae,me]})))}function H(g,M){const j=Object.create(null),ae=[];for(const Se of g.inputNames){const Le=M[Se];if(!(Le instanceof u.Tensor)){ae.push(Se);continue}j[Se]=(0,n.isONNXProxy)()?Le.clone():Le}if(ae.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ae.join(", ")}.`);const me=Object.keys(M).length,_e=g.inputNames.length;if(me>_e){let Se=Object.keys(M).filter(Le=>!g.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${me} > ${_e}). The following inputs will be ignored: "${Se.join(", ")}".`)}return j}async function W(g,M){const j=H(g,M);try{const ae=Object.fromEntries(Object.entries(j).map(([_e,Se])=>[_e,Se.ort_tensor])),me=await(0,n.runInferenceSession)(g,ae);return B(me)}catch(ae){const me=Object.fromEntries(Object.entries(j).map(([_e,Se])=>{const Le={type:Se.type,dims:Se.dims,location:Se.location};return Le.location!=="gpu-buffer"&&(Le.data=Se.data),[_e,Le]}));throw console.error(`An error occurred during model execution: "${ae}".`),console.error("Inputs given to model:",me),ae}}function B(g){for(let M in g)(0,n.isONNXTensor)(g[M])?g[M]=new u.Tensor(g[M]):typeof g[M]=="object"&&B(g[M]);return g}function Y(g){if(g instanceof u.Tensor)return g;if(g.length===0)throw Error("items must be non-empty");if(Array.isArray(g[0])){if(g.some(M=>M.length!==g[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 u.Tensor("int64",BigInt64Array.from(g.flat().map(M=>BigInt(M))),[g.length,g[0].length])}else return new u.Tensor("int64",BigInt64Array.from(g.map(M=>BigInt(M))),[1,g.length])}function X(g){return new u.Tensor("bool",[g],[1])}async function J(g,M){let{encoder_outputs:j,input_ids:ae,decoder_input_ids:me,..._e}=M;if(!j){const Le=(0,a.pick)(M,g.sessions.model.inputNames);j=(await re(g,Le)).last_hidden_state}return _e.input_ids=me,_e.encoder_hidden_states=j,g.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=M.attention_mask),await le(g,_e,!0)}async function re(g,M){const j=g.sessions.model,ae=(0,a.pick)(M,j.inputNames);if(j.inputNames.includes("inputs_embeds")&&!ae.inputs_embeds){if(!M.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ae.inputs_embeds=await g.encode_text({input_ids:M.input_ids})}if(j.inputNames.includes("token_type_ids")&&!ae.token_type_ids){if(!ae.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ae.token_type_ids=(0,u.zeros_like)(ae.input_ids)}if(j.inputNames.includes("pixel_mask")&&!ae.pixel_mask){if(!ae.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const me=ae.pixel_values.dims;ae.pixel_mask=(0,u.ones)([me[0],me[2],me[3]])}return await W(j,ae)}async function ne(g,M){const j=await g.encode(M);return await g.decode(j)}async function le(g,M,j=!1){const ae=g.sessions[j?"decoder_model_merged":"model"],{past_key_values:me,..._e}=M;if(ae.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=X(!!me)),ae.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(g.config.model_type)?1:0;_e.position_ids=Ae(_e,me,Le)}g.addPastKeyValues(_e,me);const Se=(0,a.pick)(_e,ae.inputNames);return await W(ae,Se)}function pe({modality_token_id:g,inputs_embeds:M,modality_features:j,input_ids:ae,attention_mask:me}){const _e=ae.tolist().map(st=>st.reduce((wt,bt,Pt)=>(bt==g&&wt.push(Pt),wt),[])),Se=_e.reduce((st,wt)=>st+wt.length,0),Le=j.dims[0];if(Se!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${Le}`);let Ge=0;for(let st=0;st<_e.length;++st){const wt=_e[st],bt=M[st];for(let Pt=0;Pt_e.dims[1]||me<_e.dims[1]&&(j.input_ids=_e.slice(null,[me,null]))}return j}function je(g,M,j,ae){return j.past_key_values&&(M=M.map(me=>[me.at(-1)])),{...j,decoder_input_ids:Y(M)}}function Te(g,...M){return g.config.is_encoder_decoder?je(g,...M):Ie(g,...M)}function Q(g,M,j,ae){const me=!!j.past_key_values;return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me?j.input_ids=(0,u.cat)([j.input_ids,j.input_ids],0):(j.input_ids=(0,u.cat)([j.input_ids,(0,u.full_like)(j.input_ids,BigInt(ae.pad_token_id))],0),j.attention_mask=(0,u.cat)([j.attention_mask,(0,u.full_like)(j.attention_mask,0n)],0))),(me||!j.pixel_values)&&(j.pixel_values=(0,u.full)([0,0,3,384,384],1)),me&&(j.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),j.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),j}class z extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(M,j,ae){super(),this.config=M,this.sessions=j,this.configs=ae;const me=x.get(this.constructor),_e=b.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,_e){case T.DecoderOnly:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=Ie;break;case T.Seq2Seq:case T.Vision2Seq:case T.Musicgen:this.can_generate=!0,this._forward=J,this._prepare_inputs_for_generation=je;break;case T.EncoderDecoder:this._forward=J;break;case T.ImageTextToText:this.can_generate=!0,this._forward=te,this._prepare_inputs_for_generation=Te;break;case T.AudioTextToText:this.can_generate=!0,this._forward=D,this._prepare_inputs_for_generation=Te;break;case T.Phi3V:case T.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=Te;break;case T.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Q;break;case T.AutoEncoder:this._forward=ne;break;default:this._forward=re;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const M=[];for(const j of Object.values(this.sessions))j?.handler?.dispose&&M.push(j.handler.dispose());return await Promise.all(M)}static async from_pretrained(M,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Pt={}}={}){let mt={progress_callback:j,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Pt};const Lt=x.get(this),_t=b.get(Lt);ae=mt.config=await s.AutoConfig.from_pretrained(M,mt);let pt;if(_t===T.DecoderOnly)pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Seq2Seq||_t===T.Vision2Seq)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MaskGeneration)pt=await Promise.all([O(M,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},mt)]);else if(_t===T.EncoderDecoder)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt)]);else if(_t===T.ImageTextToText){const Ft={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ae.is_encoder_decoder&&(Ft.model="encoder_model"),pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.AudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.ImageAudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.Musicgen)pt=await Promise.all([O(M,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MultiModality)pt=await Promise.all([O(M,{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"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Phi3V)pt=await Promise.all([O(M,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.AutoEncoder)pt=await Promise.all([O(M,{encoder_model:"encoder_model",decoder_model:"decoder_model"},mt)]);else if(_t===T.Supertonic)pt=await Promise.all([O(M,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},mt)]);else{if(_t!==T.EncoderOnly){const Ft=Lt??ae?.model_type;Ft!=="custom"&&console.warn(`Model type for '${Ft}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt)])}return new this(ae,...pt)}async _call(M){return await this.forward(M)}async forward(M){return await this._forward(this,M)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(M,j,ae=null){const me=new p.LogitsProcessorList;if(M.repetition_penalty!==null&&M.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(M.repetition_penalty)),M.no_repeat_ngram_size!==null&&M.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(M.no_repeat_ngram_size)),M.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(M.bad_words_ids,M.eos_token_id)),M.min_length!==null&&M.eos_token_id!==null&&M.min_length>0&&me.push(new p.MinLengthLogitsProcessor(M.min_length,M.eos_token_id)),M.min_new_tokens!==null&&M.eos_token_id!==null&&M.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(j,M.min_new_tokens,M.eos_token_id)),M.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(M.forced_bos_token_id)),M.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(M.max_length,M.forced_eos_token_id)),M.begin_suppress_tokens!==null){const _e=j>1||M.forced_bos_token_id===null?j:j+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(M.begin_suppress_tokens,_e))}return M.guidance_scale!==null&&M.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(M.guidance_scale)),M.temperature===0&&M.do_sample&&(console.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`."),M.do_sample=!1),M.do_sample&&M.temperature!==null&&M.temperature!==1&&me.push(new p.TemperatureLogitsWarper(M.temperature)),ae!==null&&me.extend(ae),me}_prepare_generation_config(M,j,ae=d.GenerationConfig){const me={...this.config};for(const Se of["decoder","generator","text_config"])Se in me&&Object.assign(me,me[Se]);const _e=new ae(me);return Object.assign(_e,this.generation_config??{}),M&&Object.assign(_e,M),j&&Object.assign(_e,(0,a.pick)(j,Object.getOwnPropertyNames(_e))),_e}_get_stopping_criteria(M,j=null){const ae=new y.StoppingCriteriaList;return M.max_length!==null&&ae.push(new y.MaxLengthCriteria(M.max_length,this.config.max_position_embeddings??null)),M.eos_token_id!==null&&ae.push(new y.EosTokenCriteria(M.eos_token_id)),j&&ae.extend(j),ae}_validate_model_class(){if(!this.can_generate){const M=[jl,Vl,Nl,Rl],j=x.get(this.constructor),ae=new Set,me=this.config.model_type;for(const Se of M){const Le=Se.get(me);Le&&ae.add(Le[0])}let _e=`The current model class (${j}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ae.size>0&&(_e+=` Please use the following class instead: ${[...ae].join(", ")}`),Error(_e)}}prepare_inputs_for_generation(...M){return this._prepare_inputs_for_generation(this,...M)}_update_model_kwargs_for_generation({generated_input_ids:M,outputs:j,model_inputs:ae,is_encoder_decoder:me}){return ae.past_key_values=this.getPastKeyValues(j,ae.past_key_values),ae.input_ids=new u.Tensor("int64",M.flat(),[M.length,1]),me||(ae.attention_mask=(0,u.cat)([ae.attention_mask,(0,u.ones)([ae.attention_mask.dims[0],1])],1)),ae.position_ids=null,ae}_prepare_model_inputs({inputs:M,bos_token_id:j,model_kwargs:ae}){const me=(0,a.pick)(ae,this.forward_params),_e=this.main_input_name;if(_e in me){if(M)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[_e]=M;return{inputs_tensor:me[_e],model_inputs:me,model_input_name:_e}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:M,model_inputs:j,model_input_name:ae,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!j.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Se,pixel_values:Le,attention_mask:Ge,...st}=j,wt=await this._prepare_inputs_embeds(j);j={...st,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_e}=await re(this,j);if(me.guidance_scale!==null&&me.guidance_scale>1)_e=(0,u.cat)([_e,(0,u.full_like)(_e,0)],0),"attention_mask"in j&&(j.attention_mask=(0,u.cat)([j.attention_mask,(0,u.zeros_like)(j.attention_mask)],0));else if(j.decoder_input_ids){const Se=Y(j.decoder_input_ids).dims[0];if(Se!==_e.dims[0]){if(_e.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_e.dims[0]}) than the decoder inputs (${Se}).`);_e=(0,u.cat)(Array.from({length:Se},()=>_e),0)}}return j.encoder_outputs=_e,j}_prepare_decoder_input_ids_for_generation({batch_size:M,model_input_name:j,model_kwargs:ae,decoder_start_token_id:me,bos_token_id:_e,generation_config:Se}){let{decoder_input_ids:Le,...Ge}=ae;if(!(Le instanceof u.Tensor)){if(Le)Array.isArray(Le[0])||(Le=Array.from({length:M},()=>Le));else if(me??=_e,this.config.model_type==="musicgen")Le=Array.from({length:M*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==M)throw new Error(`\`decoder_start_token_id\` expcted to have length ${M} but got ${me.length}`);Le=me}else Le=Array.from({length:M},()=>[me]);Le=Y(Le)}return ae.decoder_attention_mask=(0,u.ones_like)(Le),{input_ids:Le,model_inputs:Ge}}async generate({inputs:M=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,streamer:_e=null,...Se}){this._validate_model_class(),j=this._prepare_generation_config(j,Se);let{inputs_tensor:Le,model_inputs:Ge,model_input_name:st}=this._prepare_model_inputs({inputs:M,model_kwargs:Se});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Ge||(Ge=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Le,model_inputs:Ge,model_input_name:st,generation_config:j})));let bt;wt?{input_ids:bt,model_inputs:Ge}=this._prepare_decoder_input_ids_for_generation({batch_size:Ge[st].dims.at(0),model_input_name:st,model_kwargs:Ge,decoder_start_token_id:j.decoder_start_token_id,bos_token_id:j.bos_token_id,generation_config:j}):bt=Ge[st];let Pt=bt.dims.at(-1);j.max_new_tokens!==null&&(j.max_length=Pt+j.max_new_tokens);const mt=this._get_logits_processor(j,Pt,ae),Lt=this._get_stopping_criteria(j,me),_t=Ge[st].dims.at(0),pt=k.LogitsSampler.getSampler(j),Ft=new Array(_t).fill(0),Wt=bt.tolist();_e&&_e.put(Wt);let er,nr={};for(;;){if(Ge=this.prepare_inputs_for_generation(Wt,Ge,j),er=await this.forward(Ge),j.output_attentions&&j.return_dict_in_generate){const Wr=this.getAttentions(er);for(const ms in Wr)ms in nr||(nr[ms]=[]),nr[ms].push(Wr[ms])}const At=er.logits.slice(null,-1,null),cr=mt(Wt,At),kr=[];for(let Wr=0;WrWr))break;Ge=this._update_model_kwargs_for_generation({generated_input_ids:kr,outputs:er,model_inputs:Ge,is_encoder_decoder:wt})}_e&&_e.end();const pr=this.getPastKeyValues(er,Ge.past_key_values,!0),fr=new u.Tensor("int64",Wt.flat(),[Wt.length,Wt[0].length]);if(j.return_dict_in_generate)return{sequences:fr,past_key_values:pr,...nr};for(const At of Object.values(er))At.location==="gpu-buffer"&&At.dispose();return fr}getPastKeyValues(M,j,ae=!1){const me=Object.create(null);for(const _e in M)if(_e.startsWith("present")){const Se=_e.replace("present_conv","past_conv").replace("present","past_key_values"),Le=_e.includes("encoder");if(Le&&j?me[Se]=j[Se]:me[Se]=M[_e],j&&(!Le||ae)){const Ge=j[Se];Ge.location==="gpu-buffer"&&Ge.dispose()}}return me}getAttentions(M){const j={};for(const ae of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in M)me.startsWith(ae)&&(ae in j||(j[ae]=[]),j[ae].push(M[me]));return j}addPastKeyValues(M,j){if(j)Object.assign(M,j);else{const ae=this.sessions.decoder_model_merged??this.sessions.model,me=(M[this.main_input_name]??M.attention_mask)?.dims?.[0]??1,_e=ae?.config?.kv_cache_dtype??"float32",Se=_e==="float16"?u.DataTypeMap.float16:u.DataTypeMap.float32,Le=(0,s.getCacheShapes)(this.config,{batch_size:me});for(const Ge in Le){const st=Le[Ge].reduce((wt,bt)=>wt*bt,1);M[Ge]=new u.Tensor(_e,new Se(st),Le[Ge])}}}async encode_image({pixel_values:M}){return(await W(this.sessions.vision_encoder,{pixel_values:M})).image_features}async encode_text({input_ids:M}){return(await W(this.sessions.embed_tokens,{input_ids:M})).inputs_embeds}async encode_audio({audio_values:M}){return(await W(this.sessions.audio_encoder,{audio_values:M})).audio_features}}class de{}class be extends de{constructor({last_hidden_state:M,hidden_states:j=null,attentions:ae=null}){super(),this.last_hidden_state=M,this.hidden_states=j,this.attentions=ae}}class ve extends z{}class xe extends ve{}class Ce extends ve{async _call(M){return new $r(await super._call(M))}}class ge extends ve{async _call(M){return new xt(await super._call(M))}}class De extends ve{async _call(M){return new Pr(await super._call(M))}}class fe extends ve{async _call(M){return new Br(await super._call(M))}}class Ee extends z{}class We extends Ee{}class Fe extends Ee{async _call(M){return new $r(await super._call(M))}}class tt extends Ee{async _call(M){return new xt(await super._call(M))}}class Re extends Ee{async _call(M){return new Pr(await super._call(M))}}class rt extends Ee{async _call(M){return new Br(await super._call(M))}}class Ze extends z{}class Ne extends Ze{}class Oe extends Ze{async _call(M){return new $r(await super._call(M))}}class ot extends Ze{async _call(M){return new xt(await super._call(M))}}class ht extends Ze{async _call(M){return new Pr(await super._call(M))}}class Rt extends z{}class It extends Rt{}class gr extends Rt{}class Or extends z{}class zt extends Or{}class Rr extends z{}class qs extends Rr{}class Qs extends Rr{async _call(M){return new $r(await super._call(M))}}class Xs extends Rr{async _call(M){return new xt(await super._call(M))}}class or extends Rr{async _call(M){return new Pr(await super._call(M))}}class Sr extends Rr{async _call(M){return new Br(await super._call(M))}}class Qr extends z{}class Bs extends Qr{}class ft extends Qr{async _call(M){return new $r(await super._call(M))}}class qt extends Qr{async _call(M){return new xt(await super._call(M))}}class Ps extends Qr{async _call(M){return new Pr(await super._call(M))}}class Cs extends Qr{async _call(M){return new Br(await super._call(M))}}class Kr extends z{}class yt extends Kr{}class Ss extends Kr{async _call(M){return new $r(await super._call(M))}}class C extends Kr{async _call(M){return new xt(await super._call(M))}}class q extends Kr{async _call(M){return new Pr(await super._call(M))}}class R extends Kr{async _call(M){return new Br(await super._call(M))}}class G extends z{}class Z extends G{}class ce extends G{async _call(M){return new $r(await super._call(M))}}class ye extends G{async _call(M){return new xt(await super._call(M))}}class et extends G{async _call(M){return new Pr(await super._call(M))}}class ut extends G{async _call(M){return new Br(await super._call(M))}}class He extends z{}class Mt extends He{}class qe extends He{async _call(M){return new $r(await super._call(M))}}class Tt extends He{async _call(M){return new xt(await super._call(M))}}class kt extends He{async _call(M){return new Pr(await super._call(M))}}class Mr extends He{async _call(M){return new Br(await super._call(M))}}class dr extends z{}class ar extends dr{}class Tr extends dr{async _call(M){return new $r(await super._call(M))}}class Is extends dr{async _call(M){return new xt(await super._call(M))}}class Dr extends dr{async _call(M){return new Pr(await super._call(M))}}class $s extends dr{async _call(M){return new Br(await super._call(M))}}class Lr extends z{}class zr extends Lr{}class ts extends Lr{async _call(M){return new xt(await super._call(M))}}class wr extends Lr{async _call(M){return new Pr(await super._call(M))}}class ir extends Lr{async _call(M){return new Br(await super._call(M))}}class Hr extends Lr{async _call(M){return new $r(await super._call(M))}}class rs extends z{}class Rs extends rs{}class ks extends rs{async _call(M){return new $r(await super._call(M))}}class As extends rs{async _call(M){return new xt(await super._call(M))}}class Fs extends rs{async _call(M){return new Pr(await super._call(M))}}class ss extends z{}class Nr extends ss{}class ze extends ss{async _call(M){return new $r(await super._call(M))}}class Ue extends ss{async _call(M){return new xt(await super._call(M))}}class nt extends ss{async _call(M){return new Br(await super._call(M))}}class Kt extends z{}class Ns extends Kt{}class Os extends Kt{async _call(M){return new $r(await super._call(M))}}class js extends Kt{async _call(M){return new xt(await super._call(M))}}class Dn extends Kt{async _call(M){return new Pr(await super._call(M))}}class ue extends Kt{async _call(M){return new Br(await super._call(M))}}class $ extends z{}class U extends ${}class ee extends ${async _call(M){return new $r(await super._call(M))}}class se extends ${async _call(M){return new xt(await super._call(M))}}class Me extends ${async _call(M){return new Br(await super._call(M))}}class $e extends z{}class Xe extends $e{}class Je extends $e{async _call(M){return new xt(await super._call(M))}}class Ye extends $e{async _call(M){return new Br(await super._call(M))}}class Ke extends $e{async _call(M){return new $r(await super._call(M))}}class $t extends z{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Et extends $t{}class rr extends $t{}class br extends z{}class Xt extends br{}class sr extends br{}class Ht extends z{}class qr extends Ht{}class ns extends Ht{}class Er extends z{}class ds extends Er{}class Yt extends Er{}class hr extends Er{async _call(M){return new xt(await super._call(M))}}class Ir extends z{}class Xr extends Ir{}class ps extends Ir{}class yr extends Ir{async _call(M){return new xt(await super._call(M))}}class os extends Ir{}class vr extends z{}class Zt extends vr{}class _r extends vr{}class lr extends z{}class Ur extends lr{}class Js extends lr{}class Ds extends z{}class po extends Ds{}class ra extends Ds{async _call(M){return new $r(await super._call(M))}}class sa extends Ds{async _call(M){return new xt(await super._call(M))}}class na extends Ds{async _call(M){return new Pr(await super._call(M))}}class oa extends Ds{async _call(M){return new Br(await super._call(M))}}class Ys extends z{}class aa extends Ys{}class ia extends Ys{async _call(M){return new $r(await super._call(M))}}class la extends Ys{async _call(M){return new xt(await super._call(M))}}class ca extends Ys{async _call(M){return new Pr(await super._call(M))}}class ua extends Ys{async _call(M){return new Br(await super._call(M))}}class Zs extends z{}class da extends Zs{}class mo extends Zs{async _call(M){return new $r(await super._call(M))}}class ho extends Zs{async _call(M){return new xt(await super._call(M))}}class _o extends Zs{async _call(M){return new Pr(await super._call(M))}}class pa extends Zs{async _call(M){return new Br(await super._call(M))}}class fo extends z{}class go extends fo{}class Mo extends fo{}class Vs extends z{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class ma extends Vs{}class Ln extends Vs{_prepare_generation_config(M,j){return super._prepare_generation_config(M,j,v.WhisperGenerationConfig)}_retrieve_init_tokens(M){const j=[M.decoder_start_token_id];let ae=M.language;const me=M.task;if(M.is_multilingual){ae||(console.warn("No language specified - defaulting to English (en)."),ae="en");const Se=`<|${(0,I.whisper_language_to_code)(ae)}|>`;j.push(M.lang_to_id[Se]),j.push(M.task_to_id[me??"transcribe"])}else if(ae||me)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!M.return_timestamps&&M.no_timestamps_token_id&&j.at(-1)!==M.no_timestamps_token_id?j.push(M.no_timestamps_token_id):M.return_timestamps&&j.at(-1)===M.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),j.pop()),j.filter(_e=>_e!=null)}async generate({inputs:M=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,..._e}){j=this._prepare_generation_config(j,_e);const Se=_e.decoder_input_ids??this._retrieve_init_tokens(j);if(j.return_timestamps&&(ae??=new p.LogitsProcessorList,ae.push(new p.WhisperTimeStampLogitsProcessor(j,Se))),j.begin_suppress_tokens&&(ae??=new p.LogitsProcessorList,ae.push(new p.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,Se.length))),j.return_token_timestamps){if(!j.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");j.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),j.output_attentions=!0,j.return_dict_in_generate=!0}const Le=await super.generate({inputs:M,generation_config:j,logits_processor:ae,decoder_input_ids:Se,..._e});return j.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,j.alignment_heads,j.num_frames)),Le}_extract_token_timestamps(M,j,ae=null,me=.02){if(!M.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");ae==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let _e=this.config.median_filter_width;_e===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),_e=7);const Se=M.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(_t,pt)=>(0,u.cat)(Se.map(Ft=>Ft[pt]),2)),Ge=(0,u.stack)(j.map(([_t,pt])=>{if(_t>=Le.length)throw new Error(`Layer index ${_t} is out of bounds for cross attentions (length ${Le.length}).`);return ae?Le[_t].slice(null,pt,null,[0,ae]):Le[_t].slice(null,pt)})).transpose(1,0,2,3),[st,wt]=(0,u.std_mean)(Ge,-2,0,!0),bt=Ge.clone();for(let _t=0;_tFt[At+1]-Ft[At]),nr=(0,a.mergeArrays)([1],er).map(fr=>!!fr),pr=[];for(let fr=0;frArray.from({length:M.dims[0]},er=>Array.from({length:M.dims[1]},nr=>1))),Lt=j?j.tolist():[],_t=ae?ae.tolist():[];let pt=0,Ft=0;for(let Wt=0;WtPt[Wt][Cr]==1),pr=er.reduce((tr,Cr,sn)=>(Cr==Ge&&tr.push(sn),tr),[]).map(tr=>er[tr+1]),fr=pr.filter(tr=>tr==Se).length,At=pr.filter(tr=>tr==Le).length;let cr=[],kr=0,wn=fr,Wr=At;for(let tr=0;trhs>kr&&yn==Se),sn=er.findIndex((yn,hs)=>hs>kr&&yn==Le),bn=wn>0&&Cr!==-1?Cr:er.length+1,to=Wr>0&&sn!==-1?sn:er.length+1;let Wa,Ul,Wl,Gl;bn0?(0,_.max)(cr.at(-1))[0]+1:0;cr.push(Array.from({length:3*Hl},(yn,hs)=>Y_+hs%Hl));const ql=Hl+Y_,Ka=Mx*Kl*Ga,wx=Array.from({length:Ka},(yn,hs)=>ql+Math.floor(hs/(Kl*Ga))),bx=Array.from({length:Ka},(yn,hs)=>ql+Math.floor(hs/Ga)%Kl),yx=Array.from({length:Ka},(yn,hs)=>ql+hs%Ga);cr.push([wx,bx,yx].flat()),kr=Wa+Ka}if(kr0?(0,_.max)(cr.at(-1))[0]+1:0,Cr=er.length-kr;cr.push(Array.from({length:3*Cr},(sn,bn)=>tr+bn%Cr))}const ms=cr.reduce((tr,Cr)=>tr+Cr.length,0),Zn=new Array(ms);let eo=0;for(let tr=0;tr<3;++tr)for(let Cr=0;Crbt[pt%bt.length]),Lt=Array.from({length:Pt[0]},(_t,pt)=>(0,_.max)(bt.subarray(Pt[1]*pt,Pt[1]*(pt+1)))[0]+1n+BigInt(Pt[1]));return[new u.Tensor("int64",mt,[3,...Pt]),new u.Tensor("int64",Lt,[Lt.length,1])]}else{const[bt,Pt]=M.dims,mt=BigInt64Array.from({length:3*bt*Pt},(Lt,_t)=>BigInt(Math.floor(_t%Pt/bt)));return[new u.Tensor("int64",mt,[3,...M.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:M,image_grid_thw:j}){return(await W(this.sessions.vision_encoder,{pixel_values:M,grid_thw:j})).image_features}_merge_input_ids_with_image_features(M){return oe({image_token_id:this.config.image_token_id,...M})}prepare_inputs_for_generation(M,j,ae){if(j.attention_mask&&!j.position_ids)if(!j.past_key_values)[j.position_ids,j.rope_deltas]=this.get_rope_index(j.input_ids,j.image_grid_thw,j.video_grid_thw,j.attention_mask);else{j.pixel_values=null;const me=BigInt(Object.values(j.past_key_values)[0].dims.at(-2)),_e=j.rope_deltas.map(Se=>me+Se);j.position_ids=(0,u.stack)([_e,_e,_e],0)}return j}}class ji extends z{}class kd extends ji{}class Ad extends ji{}class Vi extends z{}class Fd extends Vi{}class Od extends Vi{}class Ui extends z{}class Dd extends Ui{}class Ld extends Ui{}class Wi extends z{}class zd extends Wi{}class Bd extends Wi{}class Gi extends z{}class Rd extends Gi{}class Nd extends Gi{}class Ki extends z{}class jd extends Ki{}class Vd extends Ki{async _call(M){return new xt(await super._call(M))}}class Hi extends z{}class Ud extends Hi{}class Wd extends Hi{async _call(M){return new xt(await super._call(M))}}class Gd extends z{}class Kd extends Gd{}class qi extends z{}class Hd extends qi{}class qd extends qi{async _call(M){return new xt(await super._call(M))}}class Qd extends z{}class Xd extends Qd{}class Qi extends z{}class Jd extends Qi{}class Yd extends Qi{async _call(M){return new xt(await super._call(M))}}class Zd extends z{}class ep extends Zd{}class Xi extends z{}class tp extends Xi{}class rp extends Xi{async _call(M){return new xt(await super._call(M))}}class sp extends z{}class np extends sp{async _call(M){return new X_(await super._call(M))}}class Ji extends z{}class op extends Ji{}class ap extends Ji{async _call(M){return new xt(await super._call(M))}}class Yi extends z{}class ip extends Yi{}class lp extends Yi{async _call(M){return new xt(await super._call(M))}}class Zi extends z{}class cp extends Zi{}class up extends Zi{}class el extends z{}class dp extends el{}class pp extends el{}class tl extends z{}class mp extends tl{}class hp extends tl{async _call(M){return new xt(await super._call(M))}}class Ca extends z{}class _p extends Ca{}class fp extends Ca{async _call(M){return new sl(await super._call(M))}}class rl extends Ca{async _call(M){return new gp(await super._call(M))}}class sl extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class gp extends de{constructor({logits:M,pred_boxes:j,pred_masks:ae}){super(),this.logits=M,this.pred_boxes=j,this.pred_masks=ae}}class nl extends z{}class Mp extends nl{}class wp extends nl{async _call(M){return new Fo(await super._call(M))}}class Fo extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class ol extends z{}class bp extends ol{}class yp extends ol{async _call(M){return new vp(await super._call(M))}}class vp extends Fo{}class al extends z{}class xp extends al{}class Tp extends al{async _call(M){return new Ep(await super._call(M))}}class Ep extends Fo{}class il extends z{}class Pp extends il{}class Cp extends il{async _call(M){return new Fo(await super._call(M))}}class ll extends z{}class Sp extends ll{}class Ip extends ll{async _call(M){return new $p(await super._call(M))}}class $p extends sl{}class cl extends z{}class kp extends cl{}class Ap extends cl{async _call(M){return new xt(await super._call(M))}}class ul extends z{}class Fp extends ul{}class Op extends ul{async _call(M){return new xt(await super._call(M))}}class dl extends z{}class Dp extends dl{}class Lp extends dl{async _call(M){return new xt(await super._call(M))}}class Sa extends z{}class zp extends Sa{}class Bp extends Sa{async _call(M){return new xt(await super._call(M))}}class Rp extends Sa{}class pl extends z{}class Np extends pl{}class jp extends pl{}class ml extends z{}class Vp extends ml{}class Up extends ml{}class Wp extends z{}class Gp extends Wp{}class Ia extends z{}class Kp extends Ia{}class Hp extends Ia{}class qp extends Ia{}class Qp extends z{}class Xp extends Qp{}class Jp extends z{}class Yp extends Jp{}class Zp extends z{}class em extends Zp{}class hl extends z{}class tm extends hl{}class rm extends hl{}class _l extends z{}class sm extends _l{}class nm extends _l{}class om extends z{}class am extends om{}class fl extends z{}class im extends fl{}class lm extends fl{async _call(M){return new xt(await super._call(M))}}class gl extends z{}class cm extends gl{}class um extends gl{async _call(M){return new xt(await super._call(M))}}class Ml extends z{}class dm extends Ml{}class pm extends Ml{async _call(M){return new xt(await super._call(M))}}class wl extends z{}class mm extends wl{}class hm extends wl{async _call(M){return new xt(await super._call(M))}}class _m extends z{}class fm extends _m{}class gm extends z{}class Mm extends gm{}class wm extends z{}class bm extends wm{}class bl extends z{}class ym extends bl{}class vm extends bl{async _call(M){return new xm(await super._call(M))}}class xm extends de{constructor({logits:M,pred_boxes:j}){super(),this.logits=M,this.pred_boxes=j}}class Tm extends z{}class Em extends Tm{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){!M.image_embeddings||!M.image_positional_embeddings?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_labels??=(0,u.ones)(M.input_points.dims.slice(0,-1));const j={image_embeddings:M.image_embeddings,image_positional_embeddings:M.image_positional_embeddings};return M.input_points&&(j.input_points=M.input_points),M.input_labels&&(j.input_labels=M.input_labels),M.input_boxes&&(j.input_boxes=M.input_boxes),await W(this.sessions.prompt_encoder_mask_decoder,j)}async _call(M){return new Pm(await super._call(M))}}class Pm extends de{constructor({iou_scores:M,pred_masks:j}){super(),this.iou_scores=M,this.pred_masks=j}}class Cm extends de{constructor({iou_scores:M,pred_masks:j,object_score_logits:ae}){super(),this.iou_scores=M,this.pred_masks=j,this.object_score_logits=ae}}class Sm extends z{}class $a extends Sm{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){const{num_feature_levels:j}=this.config.vision_config;if(Array.from({length:j},(Se,Le)=>`image_embeddings.${Le}`).some(Se=>!M[Se])?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_points){if(M.input_boxes&&M.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 Se=M.input_points.dims;M.input_labels??=(0,u.ones)(Se.slice(0,-1)),M.input_boxes??=(0,u.full)([Se[0],0,4],0)}else if(M.input_boxes){const Se=M.input_boxes.dims;M.input_labels=(0,u.full)([Se[0],Se[1],0],-1n),M.input_points=(0,u.full)([Se[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const me=this.sessions.prompt_encoder_mask_decoder,_e=(0,a.pick)(M,me.inputNames);return await W(me,_e)}async _call(M){return new Cm(await super._call(M))}}class Im extends $a{}class $m extends $a{}class yl extends z{}class km extends yl{}class Am extends yl{}class vl extends z{}class Fm extends vl{}class Om extends vl{}class tn extends z{}class Dm extends tn{}class Lm extends tn{async _call(M){return new rn(await super._call(M))}}class zm extends tn{async _call(M){return new xt(await super._call(M))}}class Bm extends tn{async _call(M){return new Pr(await super._call(M))}}class Rm extends z{}class Nm extends Rm{async _call(M){return new rn(await super._call(M))}}class xl extends z{}class jm extends xl{}class Vm extends xl{async _call(M){return new Pr(await super._call(M))}}class Um extends z{}class Wm extends Um{}class ka extends z{}class Gm extends ka{}class Km extends ka{async _call(M){return new rn(await super._call(M))}}class Hm extends ka{async _call(M){return new xt(await super._call(M))}}class Oo extends z{}class qm extends Oo{}class Qm extends Oo{async _call(M){return new rn(await super._call(M))}}class Xm extends Oo{async _call(M){return new xt(await super._call(M))}}class Jm extends Oo{async _call(M){return new Pr(await super._call(M))}}class Aa extends z{}class Ym extends Aa{}class Zm extends Aa{async _call(M){return new rn(await super._call(M))}}class eh extends Aa{async _call(M){return new xt(await super._call(M))}}class Ev extends z{}class th extends tn{}class rh extends tn{async _call(M){return new rn(await super._call(M))}}class sh extends tn{async _call(M){return new xt(await super._call(M))}}class Jn extends z{}class nh extends Jn{}class oh extends Jn{async _call(M){return new rn(await super._call(M))}}class ah extends Jn{async _call(M){return new xt(await super._call(M))}}class ih extends Jn{async _call(M){return new Q_(await super._call(M))}}class lh extends Jn{async _call(M){return new Pr(await super._call(M))}}class ch extends z{}class uh extends ch{}class Fa extends z{}class Pv extends Fa{}class dh extends Fa{}class ph extends Fa{async generate_speech(M,j,{threshold:ae=.5,minlenratio:me=0,maxlenratio:_e=20,vocoder:Se=null}={}){const Le={input_ids:M},{encoder_outputs:Ge,encoder_attention_mask:st}=await re(this,Le),wt=Ge.dims[1]/this.config.reduction_factor,bt=Math.floor(wt*_e),Pt=Math.floor(wt*me),mt=this.config.num_mel_bins;let Lt=[],_t=null,pt=null,Ft=0;for(;;){++Ft;const nr=X(!!pt);let pr;pt?pr=pt.output_sequence_out:pr=new u.Tensor("float32",new Float32Array(mt),[1,1,mt]);let fr={use_cache_branch:nr,output_sequence:pr,encoder_attention_mask:st,speaker_embeddings:j,encoder_hidden_states:Ge};this.addPastKeyValues(fr,_t),pt=await W(this.sessions.decoder_model_merged,fr),_t=this.getPastKeyValues(pt,_t);const{prob:At,spectrum:cr}=pt;if(Lt.push(cr),Ft>=Pt&&(Array.from(At.data).filter(kr=>kr>=ae).length>0||Ft>=bt))break}const Wt=(0,u.cat)(Lt),{waveform:er}=await W(Se.sessions.model,{spectrogram:Wt});return{spectrogram:Wt,waveform:er}}}class mh extends z{main_input_name="spectrogram"}class hh extends z{}class Tl extends hh{async generate_speech({input_ids:M,attention_mask:j,style:ae,num_inference_steps:me=5,speed:_e=1.05}){const{sampling_rate:Se,chunk_compress_factor:Le,base_chunk_size:Ge,latent_dim:st}=this.config,{last_hidden_state:wt,durations:bt}=await W(this.sessions.text_encoder,{input_ids:M,attention_mask:j,style:ae});bt.div_(_e);const Pt=bt.max().item()*Se,mt=Ge*Le,Lt=Math.floor((Pt+mt-1)/mt),_t=M.dims[0],pt=(0,u.ones)([_t,Lt]),Ft=(0,u.full)([_t],me);let Wt=(0,u.randn)([_t,st*Le,Lt]);for(let nr=0;nr0&&Pt<=_e&&(M.data[Se++]=M.data[st])}const Le=Math.floor(j/me),Ge=Se/(Le*me);return new u.Tensor(M.type,M.data.slice(0,Se),[Le,me,Ge])}prepare_inputs_for_generation(M,j,ae){let me=structuredClone(M);for(let Se=0;Se=Le&&(me[Se][Le]=BigInt(this.config.decoder.pad_token_id));return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,j,ae)}async generate(M){const j=await super.generate(M),ae=this._apply_and_filter_by_delay_pattern_mask(j).unsqueeze_(0),{audio_values:me}=await W(this.sessions.encodec_decode,{audio_codes:ae});return me}}class La extends z{}class Rh extends La{}class Nh extends La{async _call(M){return new xt(await super._call(M))}}class jh extends La{}class za extends z{}class Vh extends za{}class Uh extends za{async _call(M){return new xt(await super._call(M))}}class Wh extends za{}class Ba extends z{}class Gh extends Ba{}class Kh extends Ba{async _call(M){return new xt(await super._call(M))}}class Hh extends Ba{}class Ra extends z{}class qh extends Ra{}class Qh extends Ra{async _call(M){return new xt(await super._call(M))}}class Xh extends Ra{}class Jh extends z{}class Yh extends Jh{}class Zh extends z{}class e_ extends Zh{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...M){super(...M),this._generation_mode="text"}async forward(M){const j=this._generation_mode??"text";let ae;if(j==="text"||!M.past_key_values){const Ge=this.sessions.prepare_inputs_embeds,st=(0,a.pick)(M,Ge.inputNames);ae=await W(Ge,st)}else{const Ge=this.sessions.gen_img_embeds,st=(0,a.pick)({image_ids:M.input_ids},Ge.inputNames);ae=await W(Ge,st)}const me={...M,...ae},_e=await le(this,me),Se=this.sessions[j==="text"?"lm_head":"gen_head"];if(!Se)throw new Error(`Unable to find "${Se}" generation head`);const Le=await W(Se,(0,a.pick)(_e,Se.inputNames));return{...ae,..._e,...Le}}async generate(M){return this._generation_mode="text",super.generate(M)}async generate_images(M){this._generation_mode="image";const j=(M.inputs??M[this.main_input_name]).dims[1],me=(await super.generate(M)).slice(null,[j,null]),_e=this.sessions.image_decode,{decoded_image:Se}=await W(_e,{generated_tokens:me}),Le=Se.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Ge=[];for(const st of Le){const wt=f.RawImage.fromTensor(st);Ge.push(wt)}return Ge}}class t_ extends de{constructor({char_logits:M,bpe_logits:j,wp_logits:ae}){super(),this.char_logits=M,this.bpe_logits=j,this.wp_logits=ae}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class r_ extends z{}class s_ extends r_{async _call(M){return new t_(await super._call(M))}}class Ll extends z{}class n_ extends Ll{}class o_ extends Ll{}class zl extends z{}class a_ extends zl{}class i_ extends zl{}class l_ extends z{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class Bl extends l_{_merge_input_ids_with_audio_features(M){const j=M.audio_features.dims.at(-1),ae=M.audio_features.view(-1,j);return K({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...M,audio_features:ae})}}class c_ extends Bl{}class Na extends z{main_input_name="input_values";forward_params=["input_values"]}class u_ extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class d_ extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class p_ extends Na{async encode(M){return new u_(await W(this.sessions.encoder_model,M))}async decode(M){return new d_(await W(this.sessions.decoder_model,M))}}class m_ extends Na{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class h_ extends Na{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class ja extends z{main_input_name="input_values";forward_params=["input_values"]}class __ extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class f_ extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class g_ extends ja{async encode(M){return new __(await W(this.sessions.encoder_model,M))}async decode(M){return new f_(await W(this.sessions.decoder_model,M))}}class M_ extends ja{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class w_ extends ja{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Va extends z{main_input_name="input_values";forward_params=["input_values"]}class b_ extends Va{async encode(M){return await W(this.sessions.encoder_model,M)}async decode(M){return await W(this.sessions.decoder_model,M)}}class y_ extends Va{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class v_ extends Va{static async from_pretrained(M,j={}){return super.from_pretrained(M,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Ut{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(M,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Pt={}}={}){const mt={progress_callback:j,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Pt};if(mt.config=await s.AutoConfig.from_pretrained(M,mt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const Lt=mt.config.model_type;for(const _t of this.MODEL_CLASS_MAPPINGS){let pt=_t.get(Lt);if(!pt){for(const Ft of _t.values())if(Ft[0]===Lt){pt=Ft;break}if(!pt)continue}return await pt[1].from_pretrained(M,mt)}if(this.BASE_IF_FAIL)return q_.has(Lt)||console.warn(`Unknown model class "${Lt}", attempting to construct from base class.`),await z.from_pretrained(M,mt);throw Error(`Unsupported model type: ${Lt}`)}}const $v=new Map([["bert",["BertModel",xe]],["neobert",["NeoBertModel",We]],["modernbert",["ModernBertModel",Ne]],["nomic_bert",["NomicBertModel",zt]],["roformer",["RoFormerModel",qs]],["electra",["ElectraModel",yt]],["esm",["EsmModel",Rs]],["convbert",["ConvBertModel",Bs]],["camembert",["CamembertModel",Z]],["deberta",["DebertaModel",Mt]],["deberta-v2",["DebertaV2Model",ar]],["mpnet",["MPNetModel",Ns]],["albert",["AlbertModel",Xe]],["distilbert",["DistilBertModel",zr]],["roberta",["RobertaModel",po]],["xlm",["XLMModel",aa]],["xlm-roberta",["XLMRobertaModel",da]],["clap",["ClapModel",Ih]],["clip",["CLIPModel",vo]],["clipseg",["CLIPSegModel",Po]],["chinese_clip",["ChineseCLIPModel",Eo]],["siglip",["SiglipModel",To]],["jina_clip",["JinaCLIPModel",hn]],["mobilebert",["MobileBertModel",Nr]],["squeezebert",["SqueezeBertModel",U]],["wav2vec2",["Wav2Vec2Model",Dm]],["wav2vec2-bert",["Wav2Vec2BertModel",Ym]],["unispeech",["UniSpeechModel",Gm]],["unispeech-sat",["UniSpeechSatModel",qm]],["hubert",["HubertModel",th]],["wavlm",["WavLMModel",nh]],["audio-spectrogram-transformer",["ASTModel",go]],["vits",["VitsModel",kl]],["pyannote",["PyAnnoteModel",jm]],["wespeaker-resnet",["WeSpeakerResNetModel",Wm]],["detr",["DetrModel",_p]],["rt_detr",["RTDetrModel",Mp]],["rt_detr_v2",["RTDetrV2Model",bp]],["rf_detr",["RFDetrModel",xp]],["d_fine",["DFineModel",Pp]],["table-transformer",["TableTransformerModel",Sp]],["vit",["ViTModel",jd]],["ijepa",["IJepaModel",Ud]],["pvt",["PvtModel",Hd]],["vit_msn",["ViTMSNModel",Jd]],["vit_mae",["ViTMAEModel",Xd]],["groupvit",["GroupViTModel",ep]],["fastvit",["FastViTModel",tp]],["mobilevit",["MobileViTModel",op]],["mobilevitv2",["MobileViTV2Model",ip]],["owlvit",["OwlViTModel",cp]],["owlv2",["Owlv2Model",dp]],["beit",["BeitModel",mp]],["deit",["DeiTModel",kp]],["hiera",["HieraModel",Fp]],["convnext",["ConvNextModel",im]],["convnextv2",["ConvNextV2Model",cm]],["dinov2",["Dinov2Model",dm]],["dinov2_with_registers",["Dinov2WithRegistersModel",mm]],["dinov3_vit",["DINOv3ViTModel",fm]],["dinov3_convnext",["DINOv3ConvNextModel",Mm]],["resnet",["ResNetModel",Dp]],["swin",["SwinModel",zp]],["swin2sr",["Swin2SRModel",Np]],["donut-swin",["DonutSwinModel",am]],["yolos",["YolosModel",ym]],["dpt",["DPTModel",Vp]],["glpn",["GLPNModel",sm]],["hifigan",["SpeechT5HifiGan",mh]],["efficientnet",["EfficientNetModel",zh]],["decision_transformer",["DecisionTransformerModel",Yh]],["patchtst",["PatchTSTForPrediction",n_]],["patchtsmixer",["PatchTSMixerForPrediction",a_]],["mobilenet_v1",["MobileNetV1Model",Rh]],["mobilenet_v2",["MobileNetV2Model",Vh]],["mobilenet_v3",["MobileNetV3Model",Gh]],["mobilenet_v4",["MobileNetV4Model",qh]],["maskformer",["MaskFormerModel",tm]],["mgp-str",["MgpstrForSceneTextRecognition",s_]],["style_text_to_speech_2",["StyleTextToSpeech2Model",uh]]]),kv=new Map([["t5",["T5Model",Et]],["longt5",["LongT5Model",Xt]],["mt5",["MT5Model",qr]],["bart",["BartModel",ds]],["mbart",["MBartModel",Xr]],["marian",["MarianModel",km]],["whisper",["WhisperModel",ma]],["m2m_100",["M2M100Model",Fm]],["blenderbot",["BlenderbotModel",Zt]],["blenderbot-small",["BlenderbotSmallModel",Ur]]]),Av=new Map([["mimi",["MimiModel",p_]],["dac",["DacModel",g_]],["snac",["SnacModel",b_]]]),Fv=new Map([["bloom",["BloomModel",Dd]],["jais",["JAISModel",Io]],["gpt2",["GPT2Model",Kn]],["gptj",["GPTJModel",h]],["gpt_bigcode",["GPTBigCodeModel",L]],["gpt_neo",["GPTNeoModel",qn]],["gpt_neox",["GPTNeoXModel",ko]],["codegen",["CodeGenModel",Pe]],["llama",["LlamaModel",at]],["nanochat",["NanoChatModel",Us]],["arcee",["ArceeModel",Gu]],["lfm2",["Lfm2Model",Hu]],["smollm3",["SmolLM3Model",Qu]],["exaone",["ExaoneModel",td]],["olmo",["OlmoModel",od]],["olmo2",["Olmo2Model",id]],["mobilellm",["MobileLLMModel",sd]],["granite",["GraniteModel",cd]],["granitemoehybrid",["GraniteMoeHybridModel",dd]],["cohere",["CohereModel",md]],["gemma",["GemmaModel",_d]],["gemma2",["Gemma2Model",gd]],["vaultgemma",["VaultGemmaModel",wd]],["gemma3_text",["Gemma3Model",yd]],["helium",["HeliumModel",Ju]],["glm",["GlmModel",Zu]],["openelm",["OpenELMModel",xd]],["qwen2",["Qwen2Model",Ed]],["qwen3",["Qwen3Model",Cd]],["phi",["PhiModel",kd]],["phi3",["Phi3Model",Fd]],["mpt",["MptModel",zd]],["opt",["OPTModel",Rd]],["mistral",["MistralModel",gh]],["ministral",["MinistralModel",wh]],["ministral3",["Ministral3Model",yh]],["ernie4_5",["Ernie4_5Model",xh]],["starcoder2",["Starcoder2Model",Eh]],["falcon",["FalconModel",Ch]],["stablelm",["StableLmModel",Dh]],["modernbert-decoder",["ModernBertDecoderModel",It]]]),Rl=new Map([["speecht5",["SpeechT5ForSpeechToText",dh]],["whisper",["WhisperForConditionalGeneration",Ln]],["lite-whisper",["LiteWhisperForConditionalGeneration",ha]],["moonshine",["MoonshineForConditionalGeneration",zn]]]),x_=new Map([["speecht5",["SpeechT5ForTextToSpeech",ph]]]),T_=new Map([["vits",["VitsModel",kl]],["musicgen",["MusicgenForConditionalGeneration",Dl]],["supertonic",["SupertonicForConditionalGeneration",Tl]]]),E_=new Map([["bert",["BertForSequenceClassification",ge]],["neobert",["NeoBertForSequenceClassification",tt]],["modernbert",["ModernBertForSequenceClassification",ot]],["roformer",["RoFormerForSequenceClassification",Xs]],["electra",["ElectraForSequenceClassification",C]],["esm",["EsmForSequenceClassification",As]],["convbert",["ConvBertForSequenceClassification",qt]],["camembert",["CamembertForSequenceClassification",ye]],["deberta",["DebertaForSequenceClassification",Tt]],["deberta-v2",["DebertaV2ForSequenceClassification",Is]],["mpnet",["MPNetForSequenceClassification",js]],["albert",["AlbertForSequenceClassification",Je]],["distilbert",["DistilBertForSequenceClassification",ts]],["roberta",["RobertaForSequenceClassification",sa]],["xlm",["XLMForSequenceClassification",la]],["xlm-roberta",["XLMRobertaForSequenceClassification",ho]],["bart",["BartForSequenceClassification",hr]],["mbart",["MBartForSequenceClassification",yr]],["mobilebert",["MobileBertForSequenceClassification",Ue]],["squeezebert",["SqueezeBertForSequenceClassification",se]]]),P_=new Map([["bert",["BertForTokenClassification",De]],["neobert",["NeoBertForTokenClassification",Re]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",or]],["electra",["ElectraForTokenClassification",q]],["esm",["EsmForTokenClassification",Fs]],["convbert",["ConvBertForTokenClassification",Ps]],["camembert",["CamembertForTokenClassification",et]],["deberta",["DebertaForTokenClassification",kt]],["deberta-v2",["DebertaV2ForTokenClassification",Dr]],["mpnet",["MPNetForTokenClassification",Dn]],["distilbert",["DistilBertForTokenClassification",wr]],["roberta",["RobertaForTokenClassification",na]],["xlm",["XLMForTokenClassification",ca]],["xlm-roberta",["XLMRobertaForTokenClassification",_o]]]),Nl=new Map([["t5",["T5ForConditionalGeneration",rr]],["longt5",["LongT5ForConditionalGeneration",sr]],["mt5",["MT5ForConditionalGeneration",ns]],["bart",["BartForConditionalGeneration",Yt]],["mbart",["MBartForConditionalGeneration",ps]],["marian",["MarianMTModel",Am]],["m2m_100",["M2M100ForConditionalGeneration",Om]],["blenderbot",["BlenderbotForConditionalGeneration",_r]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Js]]]),jl=new Map([["bloom",["BloomForCausalLM",Ld]],["gpt2",["GPT2LMHeadModel",So]],["jais",["JAISLMHeadModel",gn]],["gptj",["GPTJForCausalLM",P]],["gpt_bigcode",["GPTBigCodeForCausalLM",V]],["gpt_neo",["GPTNeoForCausalLM",$o]],["gpt_neox",["GPTNeoXForCausalLM",Ao]],["codegen",["CodeGenForCausalLM",Be]],["llama",["LlamaForCausalLM",vt]],["nanochat",["NanoChatForCausalLM",Pa]],["llama4_text",["Llama4ForCausalLM",Vt]],["arcee",["ArceeForCausalLM",Ku]],["lfm2",["Lfm2ForCausalLM",qu]],["smollm3",["SmolLM3ForCausalLM",Xu]],["exaone",["ExaoneForCausalLM",rd]],["olmo",["OlmoForCausalLM",ad]],["olmo2",["Olmo2ForCausalLM",ld]],["mobilellm",["MobileLLMForCausalLM",nd]],["granite",["GraniteForCausalLM",ud]],["granitemoehybrid",["GraniteMoeHybridForCausalLM",pd]],["cohere",["CohereForCausalLM",hd]],["gemma",["GemmaForCausalLM",fd]],["gemma2",["Gemma2ForCausalLM",Md]],["vaultgemma",["VaultGemmaForCausalLM",bd]],["gemma3_text",["Gemma3ForCausalLM",vd]],["helium",["HeliumForCausalLM",Yu]],["glm",["GlmForCausalLM",ed]],["openelm",["OpenELMForCausalLM",Td]],["qwen2",["Qwen2ForCausalLM",Pd]],["qwen3",["Qwen3ForCausalLM",Sd]],["phi",["PhiForCausalLM",Ad]],["phi3",["Phi3ForCausalLM",Od]],["mpt",["MptForCausalLM",Bd]],["opt",["OPTForCausalLM",Nd]],["mbart",["MBartForCausalLM",os]],["mistral",["MistralForCausalLM",Mh]],["ministral",["MinistralForCausalLM",bh]],["ministral3",["Ministral3ForCausalLM",vh]],["ernie4_5",["Ernie4_5ForCausalLM",Th]],["starcoder2",["Starcoder2ForCausalLM",Ph]],["falcon",["FalconForCausalLM",Sh]],["trocr",["TrOCRForCausalLM",fh]],["stablelm",["StableLmForCausalLM",Lh]],["modernbert-decoder",["ModernBertDecoderForCausalLM",gr]],["phi3_v",["Phi3VForCausalLM",Un]]]),Ov=new Map([["multi_modality",["MultiModalityCausalLM",e_]]]),C_=new Map([["bert",["BertForMaskedLM",Ce]],["neobert",["NeoBertForMaskedLM",Fe]],["modernbert",["ModernBertForMaskedLM",Oe]],["roformer",["RoFormerForMaskedLM",Qs]],["electra",["ElectraForMaskedLM",Ss]],["esm",["EsmForMaskedLM",ks]],["convbert",["ConvBertForMaskedLM",ft]],["camembert",["CamembertForMaskedLM",ce]],["deberta",["DebertaForMaskedLM",qe]],["deberta-v2",["DebertaV2ForMaskedLM",Tr]],["mpnet",["MPNetForMaskedLM",Os]],["albert",["AlbertForMaskedLM",Ke]],["distilbert",["DistilBertForMaskedLM",Hr]],["roberta",["RobertaForMaskedLM",ra]],["xlm",["XLMWithLMHeadModel",ia]],["xlm-roberta",["XLMRobertaForMaskedLM",mo]],["mobilebert",["MobileBertForMaskedLM",ze]],["squeezebert",["SqueezeBertForMaskedLM",ee]]]),S_=new Map([["bert",["BertForQuestionAnswering",fe]],["neobert",["NeoBertForQuestionAnswering",rt]],["roformer",["RoFormerForQuestionAnswering",Sr]],["electra",["ElectraForQuestionAnswering",R]],["convbert",["ConvBertForQuestionAnswering",Cs]],["camembert",["CamembertForQuestionAnswering",ut]],["deberta",["DebertaForQuestionAnswering",Mr]],["deberta-v2",["DebertaV2ForQuestionAnswering",$s]],["mpnet",["MPNetForQuestionAnswering",ue]],["albert",["AlbertForQuestionAnswering",Ye]],["distilbert",["DistilBertForQuestionAnswering",ir]],["roberta",["RobertaForQuestionAnswering",oa]],["xlm",["XLMForQuestionAnswering",ua]],["xlm-roberta",["XLMRobertaForQuestionAnswering",pa]],["mobilebert",["MobileBertForQuestionAnswering",nt]],["squeezebert",["SqueezeBertForQuestionAnswering",Me]]]),Vl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Bn]],["idefics3",["Idefics3ForConditionalGeneration",jn]],["smolvlm",["SmolVLMForConditionalGeneration",dn]]]),I_=new Map([["llava",["LlavaForConditionalGeneration",Rn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",_a]],["moondream1",["Moondream1ForConditionalGeneration",fa]],["florence2",["Florence2ForConditionalGeneration",Ma]],["qwen2-vl",["Qwen2VLForConditionalGeneration",$d]],["idefics3",["Idefics3ForConditionalGeneration",jn]],["smolvlm",["SmolVLMForConditionalGeneration",dn]],["paligemma",["PaliGemmaForConditionalGeneration",ba]],["llava_qwen2",["LlavaQwen2ForCausalLM",yo]],["gemma3n",["Gemma3nForConditionalGeneration",Nn]],["mistral3",["Mistral3ForConditionalGeneration",un]]]),$_=new Map([["ultravox",["UltravoxModel",Bl]],["voxtral",["VoxtralForConditionalGeneration",c_]]]),Dv=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Bn]]]),k_=new Map([["vit",["ViTForImageClassification",Vd]],["ijepa",["IJepaForImageClassification",Wd]],["pvt",["PvtForImageClassification",qd]],["vit_msn",["ViTMSNForImageClassification",Yd]],["fastvit",["FastViTForImageClassification",rp]],["mobilevit",["MobileViTForImageClassification",ap]],["mobilevitv2",["MobileViTV2ForImageClassification",lp]],["beit",["BeitForImageClassification",hp]],["deit",["DeiTForImageClassification",Ap]],["hiera",["HieraForImageClassification",Op]],["convnext",["ConvNextForImageClassification",lm]],["convnextv2",["ConvNextV2ForImageClassification",um]],["dinov2",["Dinov2ForImageClassification",pm]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",hm]],["resnet",["ResNetForImageClassification",Lp]],["swin",["SwinForImageClassification",Bp]],["segformer",["SegformerForImageClassification",Fh]],["efficientnet",["EfficientNetForImageClassification",Bh]],["mobilenet_v1",["MobileNetV1ForImageClassification",Nh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Uh]],["mobilenet_v3",["MobileNetV3ForImageClassification",Kh]],["mobilenet_v4",["MobileNetV4ForImageClassification",Qh]]]),A_=new Map([["detr",["DetrForObjectDetection",fp]],["rt_detr",["RTDetrForObjectDetection",wp]],["rt_detr_v2",["RTDetrV2ForObjectDetection",yp]],["rf_detr",["RFDetrForObjectDetection",Tp]],["d_fine",["DFineForObjectDetection",Cp]],["table-transformer",["TableTransformerForObjectDetection",Ip]],["yolos",["YolosForObjectDetection",vm]]]),F_=new Map([["owlvit",["OwlViTForObjectDetection",up]],["owlv2",["Owlv2ForObjectDetection",pp]],["grounding-dino",["GroundingDinoForObjectDetection",bm]]]),Yn=new Map([["detr",["DetrForSegmentation",rl]],["clipseg",["CLIPSegForImageSegmentation",Co]]]),O_=new Map([["segformer",["SegformerForSemanticSegmentation",Oh]],["sapiens",["SapiensForSemanticSegmentation",Kp]],["swin",["SwinForSemanticSegmentation",Rp]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",jh]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Wh]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Hh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Xh]]]),D_=new Map([["detr",["DetrForSegmentation",rl]],["maskformer",["MaskFormerForInstanceSegmentation",rm]]]),L_=new Map([["sam",["SamModel",Em]],["sam2",["Sam2Model",$a]],["edgetam",["EdgeTamModel",Im]],["sam3_tracker",["Sam3TrackerModel",$m]]]),z_=new Map([["wav2vec2",["Wav2Vec2ForCTC",Lm]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Zm]],["unispeech",["UniSpeechForCTC",Km]],["unispeech-sat",["UniSpeechSatForCTC",Qm]],["wavlm",["WavLMForCTC",oh]],["hubert",["HubertForCTC",rh]],["parakeet_ctc",["ParakeetForCTC",Nm]]]),B_=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",zm]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",eh]],["unispeech",["UniSpeechForSequenceClassification",Hm]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Xm]],["wavlm",["WavLMForSequenceClassification",ah]],["hubert",["HubertForSequenceClassification",sh]],["audio-spectrogram-transformer",["ASTForAudioClassification",Mo]]]),R_=new Map([["wavlm",["WavLMForXVector",ih]]]),N_=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Jm]],["wavlm",["WavLMForAudioFrameClassification",lh]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Bm]],["pyannote",["PyAnnoteForAudioFrameClassification",Vm]]]),j_=new Map([["vitmatte",["VitMatteForImageMatting",np]]]),Lv=new Map([["patchtst",["PatchTSTForPrediction",o_]],["patchtsmixer",["PatchTSMixerForPrediction",i_]]]),V_=new Map([["swin2sr",["Swin2SRForImageSuperResolution",jp]]]),U_=new Map([["dpt",["DPTForDepthEstimation",Up]],["depth_anything",["DepthAnythingForDepthEstimation",Gp]],["glpn",["GLPNForDepthEstimation",nm]],["sapiens",["SapiensForDepthEstimation",Hp]],["depth_pro",["DepthProForDepthEstimation",Xp]],["metric3d",["Metric3DForDepthEstimation",Yp]],["metric3dv2",["Metric3Dv2ForDepthEstimation",em]]]),W_=new Map([["sapiens",["SapiensForNormalEstimation",qp]]]),G_=new Map([["vitpose",["VitPoseForPoseEstimation",Kd]]]),K_=new Map([["clip",["CLIPVisionModelWithProjection",Ta]],["siglip",["SiglipVisionModel",dt]],["jina_clip",["JinaCLIPVisionModel",_n]]]),H_=[[$v,T.EncoderOnly],[kv,T.EncoderDecoder],[Fv,T.DecoderOnly],[Av,T.AutoEncoder],[E_,T.EncoderOnly],[P_,T.EncoderOnly],[Nl,T.Seq2Seq],[Rl,T.Seq2Seq],[jl,T.DecoderOnly],[Ov,T.MultiModality],[C_,T.EncoderOnly],[S_,T.EncoderOnly],[Vl,T.Vision2Seq],[I_,T.ImageTextToText],[$_,T.AudioTextToText],[k_,T.EncoderOnly],[Yn,T.EncoderOnly],[D_,T.EncoderOnly],[O_,T.EncoderOnly],[j_,T.EncoderOnly],[Lv,T.EncoderOnly],[V_,T.EncoderOnly],[U_,T.EncoderOnly],[W_,T.EncoderOnly],[G_,T.EncoderOnly],[A_,T.EncoderOnly],[F_,T.EncoderOnly],[L_,T.MaskGeneration],[z_,T.EncoderOnly],[B_,T.EncoderOnly],[x_,T.Seq2Seq],[T_,T.EncoderOnly],[R_,T.EncoderOnly],[N_,T.EncoderOnly],[K_,T.EncoderOnly]];for(const[g,M]of H_)for(const[j,ae]of g.values())b.set(j,M),x.set(ae,j),E.set(j,ae);const zv=[["MusicgenForConditionalGeneration",Dl,T.Musicgen],["Phi3VForCausalLM",Un,T.Phi3V],["CLIPTextModelWithProjection",xo,T.EncoderOnly],["SiglipTextModel",pn,T.EncoderOnly],["JinaCLIPTextModel",Jr,T.EncoderOnly],["ClapTextModelWithProjection",$h,T.EncoderOnly],["ClapAudioModelWithProjection",kh,T.EncoderOnly],["DacEncoderModel",M_,T.EncoderOnly],["DacDecoderModel",w_,T.EncoderOnly],["MimiEncoderModel",m_,T.EncoderOnly],["MimiDecoderModel",h_,T.EncoderOnly],["SnacEncoderModel",y_,T.EncoderOnly],["SnacDecoderModel",v_,T.EncoderOnly],["Gemma3nForConditionalGeneration",Nn,T.ImageAudioTextToText],["SupertonicForConditionalGeneration",Tl,T.Supertonic]];for(const[g,M,j]of zv)b.set(g,j),x.set(M,g),E.set(g,M);const q_=new Map([["modnet",Yn],["birefnet",Yn],["isnet",Yn],["ben",Yn]]);for(const[g,M]of q_.entries())M.set(g,["PreTrainedModel",z]),b.set(g,T.EncoderOnly),x.set(z,g),E.set(g,z);class Bv extends Ut{static MODEL_CLASS_MAPPINGS=H_.map(M=>M[0]);static BASE_IF_FAIL=!0}class Rv extends Ut{static MODEL_CLASS_MAPPINGS=[E_]}class Nv extends Ut{static MODEL_CLASS_MAPPINGS=[P_]}class jv extends Ut{static MODEL_CLASS_MAPPINGS=[Nl]}class Vv extends Ut{static MODEL_CLASS_MAPPINGS=[Rl]}class Uv extends Ut{static MODEL_CLASS_MAPPINGS=[x_]}class Wv extends Ut{static MODEL_CLASS_MAPPINGS=[T_]}class Gv extends Ut{static MODEL_CLASS_MAPPINGS=[jl]}class Kv extends Ut{static MODEL_CLASS_MAPPINGS=[C_]}class Hv extends Ut{static MODEL_CLASS_MAPPINGS=[S_]}class qv extends Ut{static MODEL_CLASS_MAPPINGS=[Vl]}class Qv extends Ut{static MODEL_CLASS_MAPPINGS=[k_]}class Xv extends Ut{static MODEL_CLASS_MAPPINGS=[Yn]}class Jv extends Ut{static MODEL_CLASS_MAPPINGS=[O_]}class Yv extends Ut{static MODEL_CLASS_MAPPINGS=[D_]}class Zv extends Ut{static MODEL_CLASS_MAPPINGS=[A_]}class ex extends Ut{static MODEL_CLASS_MAPPINGS=[F_]}class tx extends Ut{static MODEL_CLASS_MAPPINGS=[L_]}class rx extends Ut{static MODEL_CLASS_MAPPINGS=[z_]}class sx extends Ut{static MODEL_CLASS_MAPPINGS=[B_]}class nx extends Ut{static MODEL_CLASS_MAPPINGS=[R_]}class ox extends Ut{static MODEL_CLASS_MAPPINGS=[N_]}class ax extends Ut{static MODEL_CLASS_MAPPINGS=[Dv]}class ix extends Ut{static MODEL_CLASS_MAPPINGS=[j_]}class lx extends Ut{static MODEL_CLASS_MAPPINGS=[V_]}class cx extends Ut{static MODEL_CLASS_MAPPINGS=[U_]}class ux extends Ut{static MODEL_CLASS_MAPPINGS=[W_]}class dx extends Ut{static MODEL_CLASS_MAPPINGS=[G_]}class px extends Ut{static MODEL_CLASS_MAPPINGS=[K_]}class mx extends Ut{static MODEL_CLASS_MAPPINGS=[I_]}class hx extends Ut{static MODEL_CLASS_MAPPINGS=[$_]}class _x extends de{constructor({logits:M,past_key_values:j,encoder_outputs:ae,decoder_attentions:me=null,cross_attentions:_e=null}){super(),this.logits=M,this.past_key_values=j,this.encoder_outputs=ae,this.decoder_attentions=me,this.cross_attentions=_e}}class xt extends de{constructor({logits:M,...j}){super(),this.logits=M;const ae=Object.values(j);ae.length>0&&(this.attentions=ae)}}class Q_ extends de{constructor({logits:M,embeddings:j}){super(),this.logits=M,this.embeddings=j}}class Pr extends de{constructor({logits:M}){super(),this.logits=M}}class $r extends de{constructor({logits:M}){super(),this.logits=M}}class Br extends de{constructor({start_logits:M,end_logits:j}){super(),this.start_logits=M,this.end_logits=j}}class rn extends de{constructor({logits:M}){super(),this.logits=M}}class fx extends de{constructor({logits:M,past_key_values:j}){super(),this.logits=M,this.past_key_values=j}}class X_ extends de{constructor({alphas:M}){super(),this.alphas=M}}class J_ extends de{constructor({waveform:M,spectrogram:j}){super(),this.waveform=M,this.spectrogram=j}}}),"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var o=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,c={}){const p=await(0,n.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),d=p.feature_extractor_type,u=o[d];if(!u)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new u(p)}}}),"./src/models/auto/image_processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(c,p={}){const d=await(0,n.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),u=d.image_processor_type??d.feature_extractor_type;let f=i[u?.replace(/Fast$/,"")];return f||(u!==void 0&&console.warn(`Image processor type '${u}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=o.ImageProcessor),new f(d)}}}),"./src/models/auto/processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>c});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(d,u={}){const f=await(0,n.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,u),{image_processor_type:_,feature_extractor_type:y,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,u);if(!_&&!y)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const I=a[_.replace(/Fast$/,"")];if(!I)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new I(f)}if(y){const I=a[y];if(I)w.image_processor=new I(f);else{const T=l[y];if(!T)throw new Error(`Unknown feature_extractor_type: '${y}'.`);w.feature_extractor=new T(f)}}const v={};return new o.Processor(v,w,null)}}}),"./src/models/beit/image_processing_beit.js":((e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/bit/image_processing_bit.js":((e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/chinese_clip/image_processing_chinese_clip.js":((e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/clap/feature_extraction_clap.js":((e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,n.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,c,p){let d;const u=a.length-l;if(u>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(u+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(u<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/convnext/image_processing_convnext.js":((e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){const l=this.size?.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const c=Math.floor(l/this.crop_pct),[p,d]=this.get_resize_output_image_size(a,{shortest_edge:c});a=await a.resize(p,d,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class o extends n{}}),"./src/models/dac/feature_extraction_dac.js":((e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>n});var s=t("./src/models/encodec/feature_extraction_encodec.js");class n extends s.EncodecFeatureExtractor{}}),"./src/models/deit/image_processing_deit.js":((e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/detr/image_processing_detr.js":((e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(l){const c=await super._call(l),p=[c.pixel_values.dims[0],64,64],d=(0,n.full)(p,1n);return{...c,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends o{}}),"./src/models/dinov3_vit/image_processing_dinov3_vit.js":((e,r,t)=>{t.r(r),t.d(r,{DINOv3ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/donut/image_processing_donut.js":((e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(a,l,c,p={}){const[d,u,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let y=this.image_std;Array.isArray(y)||(y=new Array(f).fill(_));const k=_.map((w,v)=>-w/y[v]);return super.pad_image(a,l,c,{center:!0,constant_values:k,...p})}}class o extends n{}}),"./src/models/dpt/image_processing_dpt.js":((e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/efficientnet/image_processing_efficientnet.js":((e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}}),"./src/models/encodec/feature_extraction_encodec.js":((e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const c=[1,l,a.length/l];return{input_values:new n.Tensor("float32",a,c)}}}}),"./src/models/feature_extractors.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>o.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>n.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>a.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>w.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,ParakeetFeatureExtractor:()=>c.ParakeetFeatureExtractor,PyAnnoteFeatureExtractor:()=>p.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>u.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>f.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>_.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>k.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),n=t("./src/models/encodec/feature_extraction_encodec.js"),o=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=t("./src/models/moonshine/feature_extraction_moonshine.js"),c=t("./src/models/parakeet/feature_extraction_parakeet.js"),p=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),u=t("./src/models/snac/feature_extraction_snac.js"),f=t("./src/models/speecht5/feature_extraction_speecht5.js"),_=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),k=t("./src/models/whisper/feature_extraction_whisper.js"),w=t("./src/base/image_processors_utils.js")}),"./src/models/florence2/processing_florence2.js":((e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(l,c,p){super(l,c,p);const{tasks_answer_post_processing_type:d,task_prompts_without_inputs:u,task_prompts_with_input:f}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(d??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(f??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const c=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))c.push(this.task_prompts_without_inputs.get(p));else{for(const[d,u]of this.task_prompts_with_input)if(p.includes(d)){c.push(u.replaceAll("{input}",p).replaceAll(d,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const d=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let u;switch(d){case"pure_text":u=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),y=[],k=[];for(const[w,v,...I]of _)y.push(v?v.trim():y.at(-1)??""),k.push(I.map((T,b)=>(Number(T)+.5)/this.size_per_bin*p[b%2]));u={labels:y,[f]:k};break;default:throw new Error(`Task "${c}" (of type "${d}") not yet implemented.`)}return{[c]:u}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),u=c?this.tokenizer(this.construct_prompts(c),p):{};return{...d,...u}}}}),"./src/models/gemma3n/feature_extraction_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nAudioFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const{fft_length:c,feature_size:p,min_frequency:d,max_frequency:u,sampling_rate:f,frame_length:_}=this.config,y=(0,o.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=y,this.window=(0,o.window_function)(_,"hann")}async _extract_fbank_features(l,c){return(0,o.spectrogram)(l,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(l,{max_length:c=48e4,truncation:p=!0,padding:d=!0,pad_to_multiple_of:u=128}={}){if((0,s.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),p&&l.length>c&&(l=l.slice(0,c)),d&&l.length%u!==0){const y=u-l.length%u,k=new Float64Array(l.length+y);k.set(l),this.config.padding_value!==0&&k.fill(this.config.padding_value,l.length),l=k}const f=await this._extract_fbank_features(l,this.config.max_length),_=(0,n.full)([1,f.dims[0]],!0);return{input_features:f.unsqueeze_(0),input_features_mask:_}}}}),"./src/models/gemma3n/processing_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nProcessor:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js");t("./src/utils/image.js"),t("./src/utils/audio.js");class a extends s.Processor{static image_processor_class=n.AutoImageProcessor;static feature_extractor_class=o.AutoFeatureExtractor;static tokenizer_class=i.AutoTokenizer;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(c,p,d){super(c,p,d),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:u,boa_token:f,audio_token:_,eoa_token:y,image_token_id:k,boi_token:w,image_token:v,eoi_token:I}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const T=_.repeat(this.audio_seq_length);this.full_audio_sequence=` ${f}${T}${y} @@ -2842,4 +2842,4 @@ ${w}${b}${I} ${_}${k}`+y.repeat(d)+`${_}`,w}function l(d,u,f,_){return`${u}${_}`+f.repeat(d)+`${u}`}function c(d,u,f,_,y,k){return d===0&&u===0?l(f,_,y,k):a(f,d,u,_,y,k)}class p extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(u,f=null,_={}){_.return_row_col_info??=!0;let y;f&&(y=await this.image_processor(f,_)),Array.isArray(u)||(u=[u]);const k=y.rows??[new Array(u.length).fill(0)],w=y.cols??[new Array(u.length).fill(0)],v=this.config.image_seq_len,I=[],T=[];for(let E=0;Ec(B,O[Y],v,this.fake_image_token,this.image_token,this.global_img_token)),H=x.split(this.image_token);if(H.length===0)throw new Error("The image token should be present in the text.");let W=H[0];for(let B=0;B{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>n.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DINOv3ViTImageProcessor:()=>p.DINOv3ViTImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutImageProcessor:()=>d.DonutImageProcessor,EfficientNetImageProcessor:()=>f.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>y.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>k.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>I.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>T.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>b.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>b.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>E.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>E.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>x.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>x.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>S.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>S.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>F.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>F.MobileViTImageProcessor,NougatImageProcessor:()=>H.NougatImageProcessor,OwlViTFeatureExtractor:()=>B.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>B.OwlViTImageProcessor,Owlv2ImageProcessor:()=>W.Owlv2ImageProcessor,Phi3VImageProcessor:()=>Y.Phi3VImageProcessor,PixtralImageProcessor:()=>X.PixtralImageProcessor,PvtImageProcessor:()=>J.PvtImageProcessor,Qwen2VLImageProcessor:()=>re.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ne.RTDetrImageProcessor,Sam2ImageProcessor:()=>pe.Sam2ImageProcessor,Sam3ImageProcessor:()=>oe.Sam3ImageProcessor,SamImageProcessor:()=>le.SamImageProcessor,SegformerFeatureExtractor:()=>K.SegformerFeatureExtractor,SegformerImageProcessor:()=>K.SegformerImageProcessor,SiglipImageProcessor:()=>N.SiglipImageProcessor,SmolVLMImageProcessor:()=>D.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>te.Swin2SRImageProcessor,VLMImageProcessor:()=>w.VLMImageProcessor,ViTFeatureExtractor:()=>he.ViTFeatureExtractor,ViTImageProcessor:()=>he.ViTImageProcessor,VitMatteImageProcessor:()=>Ae.VitMatteImageProcessor,VitPoseImageProcessor:()=>Ie.VitPoseImageProcessor,YolosFeatureExtractor:()=>je.YolosFeatureExtractor,YolosImageProcessor:()=>je.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),n=t("./src/models/bit/image_processing_bit.js"),o=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),c=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/dinov3_vit/image_processing_dinov3_vit.js"),d=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),f=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),y=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),k=t("./src/models/idefics3/image_processing_idefics3.js"),w=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),I=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),T=t("./src/models/mask2former/image_processing_mask2former.js"),b=t("./src/models/maskformer/image_processing_maskformer.js"),E=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),x=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),S=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),F=t("./src/models/mobilevit/image_processing_mobilevit.js"),H=t("./src/models/nougat/image_processing_nougat.js"),W=t("./src/models/owlv2/image_processing_owlv2.js"),B=t("./src/models/owlvit/image_processing_owlvit.js"),Y=t("./src/models/phi3_v/image_processing_phi3_v.js"),X=t("./src/models/pixtral/image_processing_pixtral.js"),J=t("./src/models/pvt/image_processing_pvt.js"),re=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ne=t("./src/models/rt_detr/image_processing_rt_detr.js"),le=t("./src/models/sam/image_processing_sam.js"),pe=t("./src/models/sam2/image_processing_sam2.js"),oe=t("./src/models/sam3/image_processing_sam3.js"),K=t("./src/models/segformer/image_processing_segformer.js"),N=t("./src/models/siglip/image_processing_siglip.js"),D=t("./src/models/smolvlm/image_processing_smolvlm.js"),te=t("./src/models/swin2sr/image_processing_swin2sr.js"),he=t("./src/models/vit/image_processing_vit.js"),Ae=t("./src/models/vitmatte/image_processing_vitmatte.js"),Ie=t("./src/models/vitpose/image_processing_vitpose.js"),je=t("./src/models/yolos/image_processing_yolos.js")}),"./src/models/janus/image_processing_janus.js":((e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,c){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...c})}}}),"./src/models/janus/processing_janus.js":((e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>c});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class c extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;constructor(d,u,f){super(d,u,f),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(d,{images:u=null,chat_template:f="default"}={}){u?Array.isArray(u)||(u=[u]):u=await Promise.all(d.filter(F=>F.images).flatMap(F=>F.images).map(F=>l.RawImage.read(F)));const _=this.tokenizer,y=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=F=>_.encode(F,{add_special_tokens:!1}),w=y.split(this.image_tag),v=w.length-1;if(u.length!==v)throw new Error(`Number of images provided (${u.length}) does not match number of "${this.image_tag}" image tags (${v})`);const[I,T,b]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let E=k(w[0]),x=new Array(E.length).fill(!1);for(let F=1;F0){const F=await this.image_processor(u);return F.pixel_values.unsqueeze_(0),{...O,...F}}return O}}}),"./src/models/jina_clip/image_processing_jina_clip.js":((e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:c,size:p,...d}=i,u=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=c==="bicubic"?3:2;super({...d,size:u,resample:f,do_center_crop:!0,crop_size:p,do_normalize:!0})}}}),"./src/models/jina_clip/processing_jina_clip.js":((e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(l=null,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},u=c?await this.image_processor(c,p):{};return{...d,...u}}}}),"./src/models/llava/processing_llava.js":((e,r,t)=>{t.r(r),t.d(r,{LlavaProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!0;async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:y,patch_size:k,num_additional_image_tokens:w}=this.config,v=Math.floor(f/k)*Math.floor(_/k)+w;c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let I=0;I{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/mask2former/image_processing_mask2former.js":((e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>n});var s=t("./src/models/maskformer/image_processing_maskformer.js");class n extends s.MaskFormerImageProcessor{}}),"./src/models/maskformer/image_processing_maskformer.js":((e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class o extends n{}}),"./src/models/mgp_str/processing_mgp_str.js":((e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[u,f]=a[d],_=this[u].bind(this),[y,k]=p.dims,w=[],v=[],I=p.tolist();for(let b=0;b0?S.reduce((F,H)=>F*H,1):0;v.push(x),w.push(O)}return[_(v),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,u]){const[f,_]=this._decode_helper(p,"char"),[y,k]=this._decode_helper(d,"bpe"),[w,v]=this._decode_helper(u,"wp"),I=[],T=[];for(let b=0;b{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilevit/image_processing_mobilevit.js":((e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/moonshine/feature_extraction_moonshine.js":((e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new n.Tensor("float32",a,l)}}}}),"./src/models/moonshine/processing_moonshine.js":((e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/nougat/image_processing_nougat.js":((e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>n});var s=t("./src/models/donut/image_processing_donut.js");class n extends s.DonutImageProcessor{}}),"./src/models/owlv2/image_processing_owlv2.js":((e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>n});var s=t("./src/models/owlvit/image_processing_owlvit.js");class n extends s.OwlViTImageProcessor{}}),"./src/models/owlvit/image_processing_owlvit.js":((e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class o extends n{}}),"./src/models/owlvit/processing_owlvit.js":((e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor}}),"./src/models/paligemma/processing_paligemma.js":((e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");const i="";function a(c,p,d,u,f){return`${u.repeat(d*f)}${p}${c} `}class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!1;async _call(p,d=null,u={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let y;d.some(v=>v.includes(i))?y=d.map(v=>{const I=v.replaceAll(i,i.repeat(_)),T=I.lastIndexOf(i),b=T===-1?0:T+i.length;return I.slice(0,b)+f+I.slice(b)+` `}):(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."),y=d.map(v=>a(v,f,_,i,p.length)));const k=this.tokenizer(y,u);return{...await this.image_processor(p,u),...k}}}}),"./src/models/parakeet/feature_extraction_parakeet.js":((e,r,t)=>{t.r(r),t.d(r,{ParakeetFeatureExtractor:()=>a});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");const i=1e-5;class a extends s.FeatureExtractor{constructor(c){super(c),this.config.mel_filters??=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");const p=(0,o.window_function)(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const d=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(p,d)}async _extract_fbank_features(c){const p=this.config.preemphasis;c=new Float64Array(c);for(let u=c.length-1;u>=1;--u)c[u]-=p*c[u-1];return await(0,o.spectrogram)(c,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(c){(0,s.validate_audio_inputs)(c,"ParakeetFeatureExtractor");const p=await this._extract_fbank_features(c),d=Math.floor((c.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),u=p.data;u.fill(0,d*p.dims[1]);const[f,_]=p.dims,y=new Float64Array(_),k=new Float64Array(_);for(let I=0;I1?d-1:1;for(let I=0;I<_;++I){const T=y[I]/d,b=(k[I]-d*T*T)/w,x=1/(Math.sqrt(b)+i);for(let S=0;S{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");const o=336,i=[2,3],{ceil:a,floor:l,sqrt:c}=Math;class p extends s.ImageProcessor{constructor(u){super({...u,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=u.num_crops}calc_num_image_tokens_from_image_size(u,f){const{num_img_tokens:_}=this.config;return l((l(f/o)*l(u/o)+1)*_+1+(l(f/o)+1)*c(_))}get_resize_output_image_size(u,f){const _=this._num_crops,[y,k]=u.size;let w=y/k,v=1;for(;v*Math.ceil(v/w)<=_;)v+=1;v-=1;const I=Math.floor(v*336),T=Math.floor(I/w);return[I,T]}pad_image(u,f,_,y={}){const[k,w]=f,v=o*a(k/o),I=o*a(w/o),T=[1,1,1].map((b,E)=>(b-this.image_mean[E])/this.image_std[E]);return super.pad_image(u,f,{width:I,height:v},{center:!0,constant_values:T,...y})}async _call(u,{num_crops:f=null}={}){if(this._num_crops=f??=this.config.num_crops,f<4||c(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(u)||(u=[u]);const _=u.length,y=await Promise.all(u.map(x=>this.preprocess(x))),k=y.map(x=>x.original_size),w=y.map(x=>x.reshaped_input_size),v=[];for(const{pixel_values:x}of y){x.unsqueeze_(0);const[S,O]=x.dims.slice(-2),F=await(0,n.interpolate_4d)(x,{size:[o,o],mode:"bicubic"});if(f>0){const H=[],W=c(f),B=l(O/W),Y=l(S/W);for(let J=0;Jx.map(S=>o*a(S/o))),b=new n.Tensor("int64",T.flat(),[_,2]),E=T.map(([x,S])=>this.calc_num_image_tokens_from_image_size(S,x));return{pixel_values:I,original_sizes:k,reshaped_input_sizes:w,image_sizes:b,num_img_tokens:E}}}}),"./src/models/phi3_v/processing_phi3_v.js":((e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(p,d=null,{padding:u=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let y,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:w}=k,v=p.map((T,b)=>T.split(a).join(i.repeat(w[b])));y=this.tokenizer(v,{padding:u,truncation:f});const I=this.tokenizer.model.convert_tokens_to_ids([i])[0];y.input_ids.map_(T=>T==I?-T:T)}else y=this.tokenizer(p);return{...y,...k}}}}),"./src/models/pixtral/image_processing_pixtral.js":((e,r,t)=>{t.r(r),t.d(r,{PixtralImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{get_resize_output_image_size(i,a){const{longest_edge:l}=a;if(l===void 0)throw new Error("size must contain 'longest_edge'");const[c,p]=i.size,d=Math.max(c,p)/l;let u=c,f=p;d>1&&(u=Math.floor(c/d),f=Math.floor(p/d));const{patch_size:_,spatial_merge_size:y}=this.config;if(!y)throw new Error("config must contain 'spatial_merge_size'");const k=_*y,w=Math.floor((u-1)/k)+1,v=Math.floor((f-1)/k)+1;return[w*k,v*k]}}}),"./src/models/pixtral/processing_pixtral.js":((e,r,t)=>{t.r(r),t.d(r,{PixtralProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!0;async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:y,image_break_token:k,image_end_token:w,patch_size:v,spatial_merge_size:I}=this.config,T=v*I,b=Math.floor(f/T),E=Math.floor(_/T);c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let x=0;x{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,Gemma3nProcessor:()=>n.Gemma3nProcessor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>i.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,LlavaProcessor:()=>c.LlavaProcessor,MgpstrProcessor:()=>p.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>u.OwlViTProcessor,PaliGemmaProcessor:()=>f.PaliGemmaProcessor,Phi3VProcessor:()=>_.Phi3VProcessor,PixtralProcessor:()=>y.PixtralProcessor,PyAnnoteProcessor:()=>k.PyAnnoteProcessor,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Sam2Processor:()=>I.Sam2Processor,Sam2VideoProcessor:()=>I.Sam2VideoProcessor,SamProcessor:()=>v.SamProcessor,SmolVLMProcessor:()=>T.SmolVLMProcessor,SpeechT5Processor:()=>b.SpeechT5Processor,UltravoxProcessor:()=>E.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,VoxtralProcessor:()=>x.VoxtralProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>O.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>F.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),n=t("./src/models/gemma3n/processing_gemma3n.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),i=t("./src/models/idefics3/processing_idefics3.js"),a=t("./src/models/janus/processing_janus.js"),l=t("./src/models/jina_clip/processing_jina_clip.js"),c=t("./src/models/llava/processing_llava.js"),p=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),u=t("./src/models/owlvit/processing_owlvit.js"),f=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/phi3_v/processing_phi3_v.js"),y=t("./src/models/pixtral/processing_pixtral.js"),k=t("./src/models/pyannote/processing_pyannote.js"),w=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),v=t("./src/models/sam/processing_sam.js"),I=t("./src/models/sam2/processing_sam2.js"),T=t("./src/models/smolvlm/processing_smolvlm.js"),b=t("./src/models/speecht5/processing_speecht5.js"),E=t("./src/models/ultravox/processing_ultravox.js"),x=t("./src/models/voxtral/processing_voxtral.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),O=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),F=t("./src/models/whisper/processing_whisper.js")}),"./src/models/pvt/image_processing_pvt.js":((e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/pyannote/feature_extraction_pyannote.js":((e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const c=[1,1,l.length];return{input_values:new n.Tensor("float32",l,c)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,c){const p=c/this.samples_to_frames(c)/this.config.sampling_rate,d=[];for(const u of l.tolist()){const f=[];let _=-1;for(let y=0;y({id:y,start:k*p,end:w*p,confidence:v/(w-k)})))}return d}}}),"./src/models/pyannote/processing_pyannote.js":((e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>o});var s=t("./src/base/processing_utils.js"),n=t("./src/models/pyannote/feature_extraction_pyannote.js");class o extends s.Processor{static feature_extractor_class=n.PyAnnoteFeatureExtractor;async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}}),"./src/models/qwen2_vl/image_processing_qwen2_vl.js":((e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a,...l){const{pixel_values:c,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let u=c;const{temporal_patch_size:f,merge_size:_,patch_size:y}=this.config;u.dims[0]===1&&(u=(0,n.cat)(Array.from({length:f},()=>u),0));const k=u.dims[0]/f,w=u.dims[1],v=Math.floor(u.dims[2]/y),I=Math.floor(u.dims[3]/y),T=u.view(k,f,w,Math.floor(v/_),_,y,Math.floor(I/_),_,y).permute(0,3,6,4,7,2,1,5,8).view(k*v*I,w*f*y*y),b=new n.Tensor("int64",[k,v,I],[1,3]);return{pixel_values:T,image_grid_thw:b,original_sizes:p,reshaped_input_sizes:d}}}}),"./src/models/qwen2_vl/processing_qwen2_vl.js":((e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(l,c=null,...p){Array.isArray(l)||(l=[l]);let d,u;if(c&&(d=await this.image_processor(c),u=d.image_grid_thw),u){let _=this.image_processor.config.merge_size**2,y=0;const k=u.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const v=Number(k[y++].reduce((I,T)=>I*T,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(v/_)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}}),"./src/models/rt_detr/image_processing_rt_detr.js":((e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}}),"./src/models/sam/image_processing_sam.js":((e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/core.js"),o=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,c,p,d=!1){l=structuredClone(l);let u=(0,n.calculateDimensions)(l);if(u.length===3)d||(u=[1,...u]),l=[l];else if(u.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let f=0;fd!==c.dims[u]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:c=null,input_labels:p=null,input_boxes:d=null}={}){const u=await super._call(l);if(c&&(u.input_points=this.reshape_input_points(c,u.original_sizes,u.reshaped_input_sizes)),p){if(!u.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");u.input_labels=this.add_input_labels(p,u.input_points)}return d&&(u.input_boxes=this.reshape_input_points(d,u.original_sizes,u.reshaped_input_sizes,!0)),u}async post_process_masks(l,c,p,{mask_threshold:d=0,binarize:u=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size??this.size;const y=[f.height,f.width];for(let k=0;kd&&(b[E]=1);I=new o.Tensor("bool",b,I.dims)}_.push(I)}return _}generate_crop_boxes(l,c,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:u=32,crop_n_points_downscale_factor:f=1}={}){}}}),"./src/models/sam/processing_sam.js":((e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>o});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js");class o extends s.Processor{static image_processor_class=n.AutoImageProcessor;async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}}),"./src/models/sam2/image_processing_sam2.js":((e,r,t)=>{t.r(r),t.d(r,{Sam2ImageProcessor:()=>s.SamImageProcessor});var s=t("./src/models/sam/image_processing_sam.js")}),"./src/models/sam2/processing_sam2.js":((e,r,t)=>{t.r(r),t.d(r,{Sam2Processor:()=>n,Sam2VideoProcessor:()=>o});var s=t("./src/models/sam/processing_sam.js");class n extends s.SamProcessor{}class o extends n{}}),"./src/models/sam3/image_processing_sam3.js":((e,r,t)=>{t.r(r),t.d(r,{Sam3ImageProcessor:()=>s.Sam2ImageProcessor});var s=t("./src/models/sam2/image_processing_sam2.js")}),"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":((e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const c=this.config.sampling_rate,p=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);this.mel_filters=p,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,c){return l=l.map(p=>p*32768),(0,o.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:c,transpose:!0})}async _call(l,{padding:c=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:u=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[b,E]=f.dims,x=f.data;for(let S=0;S0){const O=new Float32Array(E*(b+S));O.set(x),O.fill(this.config.padding_value,x.length);const F=b+S;f=new n.Tensor(f.type,O,[F,E]),u&&(_=new n.Tensor("int64",new BigInt64Array(F),[1,F]),_.data.fill(1n,0,b))}}const[y,k]=f.dims,w=this.config.stride;if(y%w!==0)throw new Error(`The number of frames (${y}) must be a multiple of the stride (${w}).`);const I=f.view(1,Math.floor(y/w),k*w),T={input_features:I};if(u){const b=I.dims[1],E=new BigInt64Array(b);if(_){const x=_.data;for(let S=1,O=0;S{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class o extends n{}}),"./src/models/siglip/image_processing_siglip.js":((e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/smolvlm/image_processing_smolvlm.js":((e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")}),"./src/models/smolvlm/processing_smolvlm.js":((e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")}),"./src/models/snac/feature_extraction_snac.js":((e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>n});var s=t("./src/models/dac/feature_extraction_dac.js");class n extends s.DacFeatureExtractor{}}),"./src/models/speecht5/feature_extraction_speecht5.js":((e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");class n extends s.FeatureExtractor{}}),"./src/models/speecht5/processing_speecht5.js":((e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=o.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/swin2sr/image_processing_swin2sr.js":((e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(i,a,l,c={}){const[p,d,u]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...c})}}}),"./src/models/ultravox/processing_ultravox.js":((e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;static uses_processor_config=!0;async _call(l,c=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(c){const f=c.length,{input_features:_}=await this.feature_extractor(c,{...p,max_length:f}),y=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(y/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}}),"./src/models/vit/image_processing_vit.js":((e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/vitmatte/image_processing_vitmatte.js":((e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const c=await Promise.all(a.map(u=>this.preprocess(u))),p=await Promise.all(l.map(u=>this.preprocess(u,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,n.stack)(c.map((u,f)=>(0,n.cat)([u.pixel_values,p[f].pixel_values],0)),0),original_sizes:c.map(u=>u.original_size),reshaped_input_sizes:c.map(u=>u.reshaped_input_size)}}}}),"./src/models/vitpose/image_processing_vitpose.js":((e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const c=i.tolist(),[p,d,u,f]=i.dims,_=[];for(let y=0;y{t.r(r),t.d(r,{VoxtralProcessor:()=>d});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js"),i=t("./src/utils/tensor.js");const a="[AUDIO]",l="[BEGIN_AUDIO]",c=375;function p(u,f){const _=[];for(let y=0;yp(F,T)),E=b.map(F=>F.length),x=b.flat(),S=(await Promise.all(x.map(F=>this.feature_extractor(F,y)))).map(F=>F.input_features);k.audio_values=S.length>1?(0,i.cat)(S,0):S[0];let O=v[0];for(let F=0;F{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const c=a.reduce((d,u)=>d+u,0)/a.length,p=a.reduce((d,u)=>d+(u-c)**2,0)/a.length;return a.map(d=>(d-c)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const c=[1,l.length];return{input_values:new n.Tensor("float32",l,c),attention_mask:new n.Tensor("int64",new BigInt64Array(l.length).fill(1n),c)}}}}),"./src/models/wav2vec2/processing_wav2vec2.js":((e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=n.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":((e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=n.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/wespeaker/feature_extraction_wespeaker.js":((e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const c=l.mean(1).data,p=l.data,[d,u,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>n,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,whisper_language_to_code:()=>i});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],n=new Map(s),o=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function i(a){a=a.toLowerCase();let l=o.get(a);if(l===void 0){const c=a.match(/^<\|([a-z]{2})\|>$/);if(c&&(a=c[1]),n.has(a))l=a;else{const d=a.length===2?n.keys():n.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}}),"./src/models/whisper/feature_extraction_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js"),o=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){super(l),this.config.mel_filters??=(0,n.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney"),this.window=(0,n.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const c=await(0,n.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=c.data,d=(0,o.max)(p)[0];for(let u=0;ud?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,d)):(p=new Float32Array(d),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}}),"./src/models/whisper/generation_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>n});var s=t("./src/generation/configuration_utils.js");class n extends s.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1}}),"./src/models/whisper/processing_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/yolos/image_processing_yolos.js":((e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class o extends n{}}),"./src/ops/registry.js":((e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>i});var s=t("./src/backends/onnx.js"),n=t("./src/utils/tensor.js");const o=async(a,l,c)=>{const p=await(0,s.createInferenceSession)(new Uint8Array(a),l);return(async d=>{const u=(0,s.isONNXProxy)(),f=Object.fromEntries(Object.entries(d).map(([y,k])=>[y,(u?k.clone():k).ort_tensor])),_=await(0,s.runInferenceSession)(p,f);return Array.isArray(c)?c.map(y=>new n.Tensor(_[y])):new n.Tensor(_[c])})};class i{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=o([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=o([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=o([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=o([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=o([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=o([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=o([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=o([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}}),"./src/pipelines.js":((e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>W,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>ne,DepthEstimationPipeline:()=>te,DocumentQuestionAnsweringPipeline:()=>K,FeatureExtractionPipeline:()=>F,FillMaskPipeline:()=>I,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>H,ImageSegmentationPipeline:()=>re,ImageToImagePipeline:()=>D,ImageToTextPipeline:()=>X,ObjectDetectionPipeline:()=>pe,Pipeline:()=>y,QuestionAnsweringPipeline:()=>v,SummarizationPipeline:()=>b,Text2TextGenerationPipeline:()=>T,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>S,TextToAudioPipeline:()=>N,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>E,ZeroShotAudioClassificationPipeline:()=>B,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>le,ZeroShotObjectDetectionPipeline:()=>oe,pipeline:()=>Ie});var s=t("./src/tokenizers.js"),n=t("./src/models.js"),o=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),c=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function u(Te){return Array.isArray(Te)||(Te=[Te]),await Promise.all(Te.map(Q=>d.RawImage.read(Q)))}async function f(Te,Q){return Array.isArray(Te)||(Te=[Te]),await Promise.all(Te.map(z=>typeof z=="string"||z instanceof URL?(0,c.read_audio)(z,Q):z instanceof Float64Array?new Float32Array(z):z))}function _(Te,Q){Q&&(Te=Te.map(xe=>xe|0));const[z,de,be,ve]=Te;return{xmin:z,ymin:de,xmax:be,ymax:ve}}class y extends i.Callable{constructor({task:Q,model:z,tokenizer:de=null,processor:be=null}){super(),this.task=Q,this.model=z,this.tokenizer=de,this.processor=be}async dispose(){await this.model.dispose()}}class k extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=1}={}){const de=this.tokenizer(Q,{padding:!0,truncation:!0}),be=await this.model(de),ve=this.model.config.problem_type==="multi_label_classification"?ge=>ge.sigmoid():ge=>new p.Tensor("float32",(0,l.softmax)(ge.data),ge.dims),xe=this.model.config.id2label,Ce=[];for(const ge of be.logits){const De=ve(ge),fe=await(0,p.topk)(De,z),Ee=fe[0].tolist(),Fe=fe[1].tolist().map((tt,Re)=>({label:xe?xe[tt]:`LABEL_${tt}`,score:Ee[Re]}));z===1?Ce.push(...Fe):Ce.push(Fe)}return Array.isArray(Q)||z===1?Ce:Ce[0]}}class w extends y{constructor(Q){super(Q)}async _call(Q,{ignore_labels:z=["O"]}={}){const de=Array.isArray(Q),be=this.tokenizer(de?Q:[Q],{padding:!0,truncation:!0}),xe=(await this.model(be)).logits,Ce=this.model.config.id2label,ge=[];for(let De=0;DeOe==this.tokenizer.sep_token_id);ge[Ee].map((Oe,ot)=>Oe==1&&(ot===0||ot>Fe&&De.findIndex(ht=>ht==We[ot])===-1));const tt=ve[Ee].tolist(),Re=xe[Ee].tolist();for(let Oe=1;Oeot==We[Oe])!==-1)&&(tt[Oe]=-1/0,Re[Oe]=-1/0);const rt=(0,l.softmax)(tt).map((Oe,ot)=>[Oe,ot]),Ze=(0,l.softmax)(Re).map((Oe,ot)=>[Oe,ot]);rt[0][0]=0,Ze[0][0]=0;const Ne=(0,a.product)(rt,Ze).filter(Oe=>Oe[0][1]<=Oe[1][1]).map(Oe=>[Oe[0][1],Oe[1][1],Oe[0][0]*Oe[1][0]]).sort((Oe,ot)=>ot[2]-Oe[2]);for(let Oe=0;Oett==this.tokenizer.mask_token_id);if(De===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const fe=be[Ce][De],Ee=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(fe.data),fe.dims),z),We=Ee[0].tolist(),Fe=Ee[1].tolist();ve.push(Fe.map((tt,Re)=>{const rt=ge.slice();return rt[De]=tt,{score:We[Re],token:Number(tt),token_str:this.tokenizer.decode([tt]),sequence:this.tokenizer.decode(rt,{skip_special_tokens:!0})}}))}return Array.isArray(Q)?ve:ve[0]}}class T extends y{_key="generated_text";constructor(Q){super(Q)}async _call(Q,z={}){Array.isArray(Q)||(Q=[Q]),this.model.config.prefix&&(Q=Q.map(ge=>this.model.config.prefix+ge));const de=this.model.config.task_specific_params;de&&de[this.task]&&de[this.task].prefix&&(Q=Q.map(ge=>de[this.task].prefix+ge));const be=this.tokenizer,ve={padding:!0,truncation:!0};let xe;this instanceof E&&"_build_translation_inputs"in be?xe=be._build_translation_inputs(Q,ve,z):xe=be(Q,ve);const Ce=await this.model.generate({...xe,...z});return be.batch_decode(Ce,{skip_special_tokens:!0}).map(ge=>({[this._key]:ge}))}}class b extends T{_key="summary_text";constructor(Q){super(Q)}}class E extends T{_key="translation_text";constructor(Q){super(Q)}}function x(Te){return Array.isArray(Te)&&Te.every(Q=>"role"in Q&&"content"in Q)}class S extends y{constructor(Q){super(Q)}async _call(Q,z={}){let de=!1,be=!1,ve=z.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,xe;if(typeof Q=="string")xe=Q=[Q];else if(Array.isArray(Q)&&Q.every(Fe=>typeof Fe=="string"))de=!0,xe=Q;else{if(x(Q))Q=[Q];else if(Array.isArray(Q)&&Q.every(x))de=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,xe=Q.map(Fe=>this.tokenizer.apply_chat_template(Fe,{tokenize:!1,add_generation_prompt:!0})),ve=!1}const Ce=be?!1:z.return_full_text??!0;this.tokenizer.padding_side="left";const ge=this.tokenizer(xe,{add_special_tokens:ve,padding:!0,truncation:!0}),De=await this.model.generate({...ge,...z}),fe=this.tokenizer.batch_decode(De,{skip_special_tokens:!0});let Ee;!Ce&&ge.input_ids.dims.at(-1)>0&&(Ee=this.tokenizer.batch_decode(ge.input_ids,{skip_special_tokens:!0}).map(Fe=>Fe.length));const We=Array.from({length:Q.length},Fe=>[]);for(let Fe=0;Fe[z.toLowerCase(),de])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(Q,z,{hypothesis_template:de="This example is {}.",multi_label:be=!1}={}){const ve=Array.isArray(Q);ve||(Q=[Q]),Array.isArray(z)||(z=[z]);const xe=z.map(De=>de.replace("{}",De)),Ce=be||z.length===1,ge=[];for(const De of Q){const fe=[];for(const Fe of xe){const tt=this.tokenizer(De,{text_pair:Fe,padding:!0,truncation:!0}),Re=await this.model(tt);Ce?fe.push([Re.logits.data[this.contradiction_id],Re.logits.data[this.entailment_id]]):fe.push(Re.logits.data[this.entailment_id])}const We=(Ce?fe.map(Fe=>(0,l.softmax)(Fe)[1]):(0,l.softmax)(fe)).map((Fe,tt)=>[Fe,tt]).sort((Fe,tt)=>tt[0]-Fe[0]);ge.push({sequence:De,labels:We.map(Fe=>z[Fe[1]]),scores:We.map(Fe=>Fe[0])})}return ve?ge:ge[0]}}class F extends y{constructor(Q){super(Q)}async _call(Q,{pooling:z="none",normalize:de=!1,quantize:be=!1,precision:ve="binary"}={}){const xe=this.tokenizer(Q,{padding:!0,truncation:!0}),Ce=await this.model(xe);let ge=Ce.last_hidden_state??Ce.logits??Ce.token_embeddings;switch(z){case"none":break;case"mean":ge=(0,p.mean_pooling)(ge,xe.attention_mask);break;case"first_token":case"cls":ge=ge.slice(null,0);break;case"last_token":case"eos":ge=ge.slice(null,-1);break;default:throw Error(`Pooling method '${z}' not supported.`)}return de&&(ge=ge.normalize(2,-1)),be&&(ge=(0,p.quantize_embeddings)(ge,ve)),ge}}class H extends y{constructor(Q){super(Q)}async _call(Q,{pool:z=null}={}){const de=await u(Q),{pixel_values:be}=await this.processor(de),ve=await this.model({pixel_values:be});let xe;if(z){if(!("pooler_output"in ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");xe=ve.pooler_output}else xe=ve.last_hidden_state??ve.logits??ve.image_embeds;return xe}}class W extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=5}={}){const de=this.processor.feature_extractor.config.sampling_rate,be=await f(Q,de),ve=this.model.config.id2label,xe=[];for(const Ce of be){const ge=await this.processor(Ce),fe=(await this.model(ge)).logits[0],Ee=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(fe.data),fe.dims),z),We=Ee[0].tolist(),tt=Ee[1].tolist().map((Re,rt)=>({label:ve?ve[Re]:`LABEL_${Re}`,score:We[rt]}));xe.push(tt)}return Array.isArray(Q)?xe:xe[0]}}class B extends y{constructor(Q){super(Q)}async _call(Q,z,{hypothesis_template:de="This is a sound of {}."}={}){const be=!Array.isArray(Q);be&&(Q=[Q]);const ve=z.map(fe=>de.replace("{}",fe)),xe=this.tokenizer(ve,{padding:!0,truncation:!0}),Ce=this.processor.feature_extractor.config.sampling_rate,ge=await f(Q,Ce),De=[];for(const fe of ge){const Ee=await this.processor(fe),We=await this.model({...xe,...Ee}),Fe=(0,l.softmax)(We.logits_per_audio.data);De.push([...Fe].map((tt,Re)=>({score:tt,label:z[Re]})))}return be?De[0]:De}}class Y extends y{constructor(Q){super(Q)}async _call(Q,z={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(Q,z);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(Q,z);case"moonshine":return this._call_moonshine(Q,z);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Q,z){z.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),z.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const de=!Array.isArray(Q);de&&(Q=[Q]);const be=this.processor.feature_extractor.config.sampling_rate,ve=await f(Q,be),xe=[];for(const Ce of ve){const ge=await this.processor(Ce),fe=(await this.model(ge)).logits[0],Ee=[];for(const Fe of fe)Ee.push((0,l.max)(Fe.data)[1]);const We=this.tokenizer.decode(Ee,{skip_special_tokens:!0}).trim();xe.push({text:We})}return de?xe[0]:xe}async _call_whisper(Q,z){const de=z.return_timestamps??!1,be=z.chunk_length_s??0,ve=z.force_full_sequences??!1;let xe=z.stride_length_s??null;const Ce={...z};de==="word"&&(Ce.return_token_timestamps=!0,Ce.return_timestamps=!1);const ge=!Array.isArray(Q);ge&&(Q=[Q]);const De=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,fe=this.processor.feature_extractor.config.hop_length,Ee=this.processor.feature_extractor.config.sampling_rate,We=await f(Q,Ee),Fe=[];for(const tt of We){let Re=[];if(be>0){if(xe===null)xe=be/6;else if(be<=xe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ne=Ee*be,Oe=Ee*xe,ot=Ne-2*Oe;let ht=0;for(;;){const Rt=ht+Ne,It=tt.subarray(ht,Rt),gr=await this.processor(It),Or=ht===0,zt=Rt>=tt.length;if(Re.push({stride:[It.length,Or?0:Oe,zt?0:Oe],input_features:gr.input_features,is_last:zt}),zt)break;ht+=ot}}else Re=[{stride:[tt.length,0,0],input_features:(await this.processor(tt)).input_features,is_last:!0}];for(const Ne of Re){Ce.num_frames=Math.floor(Ne.stride[0]/fe);const Oe=await this.model.generate({inputs:Ne.input_features,...Ce});de==="word"?(Ne.tokens=Oe.sequences.tolist()[0],Ne.token_timestamps=Oe.token_timestamps.tolist()[0].map(ot=>(0,l.round)(ot,2))):Ne.tokens=Oe[0].tolist(),Ne.stride=Ne.stride.map(ot=>ot/Ee)}const[rt,Ze]=this.tokenizer._decode_asr(Re,{time_precision:De,return_timestamps:de,force_full_sequences:ve});Fe.push({text:rt,...Ze})}return ge?Fe[0]:Fe}async _call_moonshine(Q,z){const de=!Array.isArray(Q);de&&(Q=[Q]);const be=this.processor.feature_extractor.config.sampling_rate,ve=await f(Q,be),xe=[];for(const Ce of ve){const ge=await this.processor(Ce),De=Math.floor(Ce.length/be)*6,fe=await this.model.generate({max_new_tokens:De,...z,...ge}),Ee=this.processor.batch_decode(fe,{skip_special_tokens:!0})[0];xe.push({text:Ee})}return de?xe[0]:xe}}class X extends y{constructor(Q){super(Q)}async _call(Q,z={}){const de=Array.isArray(Q),be=await u(Q),{pixel_values:ve}=await this.processor(be),xe=[];for(const Ce of ve){Ce.dims=[1,...Ce.dims];const ge=await this.model.generate({inputs:Ce,...z}),De=this.tokenizer.batch_decode(ge,{skip_special_tokens:!0}).map(fe=>({generated_text:fe.trim()}));xe.push(De)}return de?xe:xe[0]}}class J extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=5}={}){const de=await u(Q),{pixel_values:be}=await this.processor(de),ve=await this.model({pixel_values:be}),xe=this.model.config.id2label,Ce=[];for(const ge of ve.logits){const De=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(ge.data),ge.dims),z),fe=De[0].tolist(),We=De[1].tolist().map((Fe,tt)=>({label:xe?xe[Fe]:`LABEL_${Fe}`,score:fe[tt]}));Ce.push(We)}return Array.isArray(Q)?Ce:Ce[0]}}class re extends y{constructor(Q){super(Q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Q,{threshold:z=.5,mask_threshold:de=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:ve=null,target_sizes:xe=null,subtask:Ce=null}={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const De=await u(Q),fe=De.map(Ne=>[Ne.height,Ne.width]),Ee=await this.processor(De),{inputNames:We,outputNames:Fe}=this.model.sessions.model;if(!We.includes("pixel_values")){if(We.length!==1)throw Error(`Expected a single input name, but got ${We.length} inputs: ${We}.`);const Ne=We[0];if(Ne in Ee)throw Error(`Input name ${Ne} already exists in the inputs.`);Ee[Ne]=Ee.pixel_values}const tt=await this.model(Ee);let Re=null;if(Ce!==null)Re=this.subtasks_mapping[Ce];else if(this.processor.image_processor){for(const[Ne,Oe]of Object.entries(this.subtasks_mapping))if(Oe in this.processor.image_processor){Re=this.processor.image_processor[Oe].bind(this.processor.image_processor),Ce=Ne;break}}const rt=this.model.config.id2label,Ze=[];if(Ce)if(Ce==="panoptic"||Ce==="instance"){const Ne=Re(tt,z,de,be,ve,xe??fe)[0],Oe=Ne.segmentation;for(const ot of Ne.segments_info){const ht=new Uint8ClampedArray(Oe.data.length);for(let It=0;Itgr<-1e-5||gr>1+1e-5)&&Rt.sigmoid_();const It=await d.RawImage.fromTensor(Rt.mul_(255).to("uint8")).resize(ht[1],ht[0]);Ze.push({label:null,score:null,mask:It})}}return Ze}}class ne extends re{constructor(Q){super(Q)}async _call(Q,z={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await u(Q),ve=await super._call(Q,z);return be.map((Ce,ge)=>{const De=Ce.clone();return De.putAlpha(ve[ge].mask),De})}}class le extends y{constructor(Q){super(Q)}async _call(Q,z,{hypothesis_template:de="This is a photo of {}"}={}){const be=Array.isArray(Q),ve=await u(Q),xe=z.map(We=>de.replace("{}",We)),Ce=this.tokenizer(xe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ge}=await this.processor(ve),De=await this.model({...Ce,pixel_values:ge}),fe=this.model.config.model_type==="siglip"?We=>We.sigmoid().data:We=>(0,l.softmax)(We.data),Ee=[];for(const We of De.logits_per_image){const tt=[...fe(We)].map((Re,rt)=>({score:Re,label:z[rt]}));tt.sort((Re,rt)=>rt.score-Re.score),Ee.push(tt)}return be?Ee:Ee[0]}}class pe extends y{constructor(Q){super(Q)}async _call(Q,{threshold:z=.9,percentage:de=!1}={}){const be=Array.isArray(Q);if(be&&Q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const ve=await u(Q),xe=de?null:ve.map(Fe=>[Fe.height,Fe.width]),{pixel_values:Ce,pixel_mask:ge}=await this.processor(ve),De=await this.model({pixel_values:Ce,pixel_mask:ge}),fe=this.processor.image_processor.post_process_object_detection(De,z,xe),Ee=this.model.config.id2label,We=fe.map(Fe=>Fe.boxes.map((tt,Re)=>({score:Fe.scores[Re],label:Ee[Fe.classes[Re]],box:_(tt,!de)})));return be?We:We[0]}}class oe extends y{constructor(Q){super(Q)}async _call(Q,z,{threshold:de=.1,top_k:be=null,percentage:ve=!1}={}){const xe=Array.isArray(Q),Ce=await u(Q),ge=this.tokenizer(z,{padding:!0,truncation:!0}),De=await this.processor(Ce),fe=[];for(let Ee=0;Ee({score:Ze.scores[Oe],label:Ze.labels[Oe],box:_(Ne,!ve)}))}else{const Ze=this.processor.image_processor.post_process_object_detection(Re,de,Fe,!0)[0];rt=Ze.boxes.map((Ne,Oe)=>({score:Ze.scores[Oe],label:z[Ze.classes[Oe]],box:_(Ne,!ve)}))}rt.sort((Ze,Ne)=>Ne.score-Ze.score),be!==null&&(rt=rt.slice(0,be)),fe.push(rt)}return xe?fe:fe[0]}}class K extends y{constructor(Q){super(Q)}async _call(Q,z,de={}){const be=(await u(Q))[0],{pixel_values:ve}=await this.processor(be),xe=`${z}`,Ce=this.tokenizer(xe,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ge=await this.model.generate({inputs:ve,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ce,...de}),fe=this.tokenizer.batch_decode(ge)[0].match(/(.*?)<\/s_answer>/);let Ee=null;return fe&&fe.length>=2&&(Ee=fe[1].trim()),[{answer:Ee}]}}class N extends y{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(Q){super(Q),this.vocoder=Q.vocoder??null}async _prepare_speaker_embeddings(Q){if((typeof Q=="string"||Q instanceof URL)&&(Q=new Float32Array(await(await fetch(Q)).arrayBuffer())),Q instanceof Float32Array)Q=new p.Tensor("float32",Q,[Q.length]);else if(!(Q instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");return Q}async _call(Q,{speaker_embeddings:z=null,num_inference_steps:de,speed:be}={}){return this.processor?this._call_text_to_spectrogram(Q,{speaker_embeddings:z}):this.model.config.model_type==="supertonic"?this._call_supertonic(Q,{speaker_embeddings:z,num_inference_steps:de,speed:be}):this._call_text_to_waveform(Q)}async _call_supertonic(Q,{speaker_embeddings:z,num_inference_steps:de,speed:be}){if(!z)throw new Error("Speaker embeddings must be provided for Supertonic models.");z=await this._prepare_speaker_embeddings(z);const{sampling_rate:ve,style_dim:xe}=this.model.config;z=z.view(1,-1,xe);const Ce=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:ge}=await this.model.generate_speech({...Ce,style:z,num_inference_steps:de,speed:be});return new c.RawAudio(ge.data,ve)}async _call_text_to_waveform(Q){const z=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:de}=await this.model(z),be=this.model.config.sampling_rate;return new c.RawAudio(de.data,be)}async _call_text_to_spectrogram(Q,{speaker_embeddings:z}){this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await n.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:de}=this.tokenizer(Q,{padding:!0,truncation:!0});z=await this._prepare_speaker_embeddings(z),z=z.view(1,-1);const{waveform:be}=await this.model.generate_speech(de,z,{vocoder:this.vocoder}),ve=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(be.data,ve)}}class D extends y{constructor(Q){super(Q)}async _call(Q){const z=await u(Q),de=await this.processor(z),be=await this.model(de),ve=[];for(const xe of be.reconstruction){const Ce=xe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");ve.push(d.RawImage.fromTensor(Ce))}return ve.length>1?ve:ve[0]}}class te extends y{constructor(Q){super(Q)}async _call(Q){const z=await u(Q),de=await this.processor(z),{predicted_depth:be}=await this.model(de),ve=[];for(let xe=0;xe1?ve:ve[0]}}const he=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:n.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:v,model:n.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:I,model:n.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:b,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:E,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:T,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:S,model:n.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:O,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:W,model:n.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:B,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[n.AutoModelForSpeechSeq2Seq,n.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:N,model:[n.AutoModelForTextToWaveform,n.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:X,model:n.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:n.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:re,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ne,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:le,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:n.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:oe,model:n.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:K,model:n.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:D,model:n.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:te,model:n.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:F,model:n.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:H,model:[n.AutoModelForImageFeatureExtraction,n.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ae=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Ie(Te,Q=null,{progress_callback:z=null,config:de=null,cache_dir:be=null,local_files_only:ve=!1,revision:xe="main",device:Ce=null,dtype:ge=null,subfolder:De="onnx",use_external_data_format:fe=null,model_file_name:Ee=null,session_options:We={}}={}){Te=Ae[Te]??Te;const Fe=he[Te.split("_",1)[0]];if(!Fe)throw Error(`Unsupported pipeline: ${Te}. Must be one of [${Object.keys(he)}]`);Q||(Q=Fe.default.model,console.log(`No model specified. Using default model: "${Q}".`));const tt={progress_callback:z,config:de,cache_dir:be,local_files_only:ve,revision:xe,device:Ce,dtype:ge,subfolder:De,use_external_data_format:fe,model_file_name:Ee,session_options:We},Re=new Map([["tokenizer",Fe.tokenizer],["model",Fe.model],["processor",Fe.processor]]),rt=await je(Re,Q,tt);rt.task=Te,(0,a.dispatchCallback)(z,{status:"ready",task:Te,model:Q});const Ze=Fe.pipeline;return new Ze(rt)}async function je(Te,Q,z){const de=Object.create(null),be=[];for(const[ve,xe]of Te.entries()){if(!xe)continue;let Ce;Array.isArray(xe)?Ce=new Promise(async(ge,De)=>{let fe;for(const Ee of xe){if(Ee===null){ge(null);return}try{ge(await Ee.from_pretrained(Q,z));return}catch(We){if(We.message?.includes("Unsupported model type"))fe=We;else if(We.message?.includes("Could not locate file"))fe=We;else{De(We);return}}}De(fe)}):Ce=xe.from_pretrained(Q,z),de[ve]=Ce,be.push(Ce)}await Promise.all(be);for(const[ve,xe]of Object.entries(de))de[ve]=await xe;return de}}),"./src/tokenizers.js":((e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ps,AutoTokenizer:()=>Dn,BartTokenizer:()=>He,BertTokenizer:()=>qt,BlenderbotSmallTokenizer:()=>Ue,BlenderbotTokenizer:()=>ze,BloomTokenizer:()=>kt,CLIPTokenizer:()=>As,CamembertTokenizer:()=>Z,CodeGenTokenizer:()=>ks,CodeLlamaTokenizer:()=>ar,CohereTokenizer:()=>Os,ConvBertTokenizer:()=>q,DebertaTokenizer:()=>yt,DebertaV2Tokenizer:()=>Ss,DistilBertTokenizer:()=>G,ElectraTokenizer:()=>ye,EsmTokenizer:()=>Lr,FalconTokenizer:()=>Dr,GPT2Tokenizer:()=>ut,GPTNeoXTokenizer:()=>$s,GemmaTokenizer:()=>ts,Grok1Tokenizer:()=>wr,HerbertTokenizer:()=>C,LlamaTokenizer:()=>dr,M2M100Tokenizer:()=>rs,MBart50Tokenizer:()=>qe,MBartTokenizer:()=>Mt,MPNetTokenizer:()=>Is,MarianTokenizer:()=>ss,MgpstrTokenizer:()=>js,MobileBertTokenizer:()=>Cs,NllbTokenizer:()=>Hr,NougatTokenizer:()=>Kt,PreTrainedTokenizer:()=>ft,Qwen2Tokenizer:()=>zr,RoFormerTokenizer:()=>R,RobertaTokenizer:()=>Tt,SiglipTokenizer:()=>Fs,SpeechT5Tokenizer:()=>nt,SqueezeBertTokenizer:()=>Kr,T5Tokenizer:()=>et,TokenizerModel:()=>H,VitsTokenizer:()=>Ns,Wav2Vec2CTCTokenizer:()=>Nr,WhisperTokenizer:()=>Rs,XLMRobertaTokenizer:()=>Tr,XLMTokenizer:()=>ce,is_chinese_char:()=>I});var s=t("./src/utils/generic.js"),n=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),c=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(ue,$){const U=await Promise.all([(0,o.getModelJSON)(ue,"tokenizer.json",!0,$),(0,o.getModelJSON)(ue,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(U[1].legacy=$.legacy),U}function u(ue,$){const U=[];let ee=0;for(const se of ue.matchAll($)){const Me=se[0];ee0&&U.push(Me),ee=se.index+Me.length}return ee=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function T(ue,$,U){const ee=[];let se=0;for(;sethis.tokens_to_ids.get(U)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(U=>this.vocab[U]??this.unk_token)}}class W extends H{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[U,ee]of this.tokens_to_ids)this.vocab[ee]=U}encode($){const U=[];for(const ee of $){const se=[...ee];if(se.length>this.max_input_chars_per_word){U.push(this.unk_token);continue}let Me=!1,$e=0;const Xe=[];for(;$e0&&(Ke=this.config.continuing_subword_prefix+Ke),this.tokens_to_ids.has(Ke)){Ye=Ke;break}--Je}if(Ye===null){Me=!0;break}Xe.push(Ye),$e=Je}Me?U.push(this.unk_token):U.push(...Xe)}return U}}class B extends H{constructor($,U){super($);const ee=$.vocab.length;this.vocab=new Array(ee),this.scores=new Array(ee);for(let se=0;se[se,Me])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=U.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes($){const U=$.chars,ee=1;let se=0;for(;se{const ue=[...Array.from({length:94},(se,Me)=>Me+33),...Array.from({length:12},(se,Me)=>Me+161),...Array.from({length:82},(se,Me)=>Me+174)],$=ue.slice();let U=0;for(let se=0;se<256;++se)ue.includes(se)||(ue.push(se),$.push(256+U),U+=1);const ee=$.map(se=>String.fromCharCode(se));return Object.fromEntries(ue.map((se,Me)=>[se,ee[Me]]))})(),X=(0,n.reverseDictionary)(Y);class J extends H{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ee,se]of this.tokens_to_ids)this.vocab[se]=ee;const U=Array.isArray($.merges[0]);this.merges=U?$.merges:$.merges.map(ee=>ee.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ee,se)=>[JSON.stringify(ee),se])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe($){if($.length===0)return[];const U=this.cache.get($);if(U!==void 0)return U;const ee=Array.from($);this.end_of_word_suffix&&(ee[ee.length-1]+=this.end_of_word_suffix);let se=[];if(ee.length>1){const Me=new l.PriorityQueue((Je,Ye)=>Je.score`<0x${Xe.toString(16).toUpperCase().padStart(2,"0")}>`);$e.every(Xe=>this.tokens_to_ids.has(Xe))?U.push(...$e):U.push(this.unk_token)}else U.push(this.unk_token)}return U}}class re extends H{constructor($,U){super($),this.tokens_to_ids=_(U.target_lang?$.vocab[U.target_lang]:$.vocab),this.bos_token=U.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=U.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=U.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=U.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[ee,se]of this.tokens_to_ids)this.vocab[se]=ee}encode($){return $}}class ne extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new Te($);case"Precompiled":return new zt($);case"Sequence":return new je($);case"Replace":return new le($);case"NFC":return new oe($);case"NFD":return new K($);case"NFKC":return new N($);case"NFKD":return new D($);case"Strip":return new te($);case"StripAccents":return new he($);case"Lowercase":return new Ae($);case"Prepend":return new Ie($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class le extends ne{normalize($){const U=f(this.config.pattern);return U===null?$:$.replaceAll(U,this.config.content)}}class pe extends ne{form=void 0;normalize($){return $=$.normalize(this.form),$}}class oe extends pe{form="NFC"}class K extends pe{form="NFD"}class N extends pe{form="NFKC"}class D extends pe{form="NFKD"}class te extends ne{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class he extends ne{normalize($){return $=w($),$}}class Ae extends ne{normalize($){return $=$.toLowerCase(),$}}class Ie extends ne{normalize($){return $=this.config.prepend+$,$}}class je extends ne{constructor($){super($),this.normalizers=$.normalizers.map(U=>ne.fromConfig(U))}normalize($){return this.normalizers.reduce((U,ee)=>ee.normalize(U),$)}}class Te extends ne{_tokenize_chinese_chars($){const U=[];for(let ee=0;ee<$.length;++ee){const se=$[ee],Me=se.charCodeAt(0);I(Me)?(U.push(" "),U.push(se),U.push(" ")):U.push(se)}return U.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` -`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const U=[];for(const ee of $){const se=ee.charCodeAt(0);se===0||se===65533||this._is_control(ee)||(/^\s$/.test(ee)?U.push(" "):U.push(ee))}return U.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class Q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new z($);case"Sequence":return new Rr($);case"Whitespace":return new qs($);case"WhitespaceSplit":return new Qs($);case"Metaspace":return new gr($);case"ByteLevel":return new de($);case"Split":return new be($);case"Punctuation":return new ve($);case"Digits":return new xe($);case"Replace":return new Xs($);case"FixedLength":return new or($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,U){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,U){return(Array.isArray($)?$.map(ee=>this.pre_tokenize_text(ee,U)):this.pre_tokenize_text($,U)).flat()}_call($,U){return this.pre_tokenize($,U)}}class z extends Q{constructor($){super(),this.pattern=new RegExp(`[^\\s${E}]+|[${E}]`,"gu")}pre_tokenize_text($,U){return $.trim().match(this.pattern)||[]}}class de extends Q{constructor($){super(),this.config=$,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text($,U){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(se=>Array.from(this.text_encoder.encode(se),Me=>this.byte_encoder[Me]).join(""))}}class be extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text($,U){return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?$.split(this.pattern).filter(ee=>ee):u($,this.pattern)}}class ve extends Q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${E}]+|[${E}]+`,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class xe extends Q{constructor($){super(),this.config=$;const U=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(U,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class Ce extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new fe($);case"ByteLevel":return new Ee($);case"RobertaProcessing":return new De($);case"BertProcessing":return new ge($);case"Sequence":return new We($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...U){throw Error("post_process should be implemented in subclass.")}_call($,...U){return this.post_process($,...U)}}class ge extends Ce{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,U=null,{add_special_tokens:ee=!0}={}){ee&&($=(0,n.mergeArrays)([this.cls],$,[this.sep]));let se=new Array($.length).fill(0);if(U!==null){const Me=ee&&this instanceof De?[this.sep]:[],$e=ee?[this.sep]:[];$=(0,n.mergeArrays)($,Me,U,$e),se=(0,n.mergeArrays)(se,new Array(U.length+Me.length+$e.length).fill(1))}return{tokens:$,token_type_ids:se}}}class De extends ge{}class fe extends Ce{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,U=null,{add_special_tokens:ee=!0}={}){const se=U===null?this.single:this.pair;let Me=[],$e=[];for(const Xe of se)"SpecialToken"in Xe?ee&&(Me.push(Xe.SpecialToken.id),$e.push(Xe.SpecialToken.type_id)):"Sequence"in Xe&&(Xe.Sequence.id==="A"?(Me=(0,n.mergeArrays)(Me,$),$e=(0,n.mergeArrays)($e,new Array($.length).fill(Xe.Sequence.type_id))):Xe.Sequence.id==="B"&&(Me=(0,n.mergeArrays)(Me,U),$e=(0,n.mergeArrays)($e,new Array(U.length).fill(Xe.Sequence.type_id))));return{tokens:Me,token_type_ids:$e}}}class Ee extends Ce{post_process($,U=null){return U&&($=(0,n.mergeArrays)($,U)),{tokens:$}}}class We extends Ce{constructor($){super($),this.processors=$.processors.map(U=>Ce.fromConfig(U))}post_process($,U=null,ee={}){let se;for(const Me of this.processors)if(Me instanceof Ee)$=Me.post_process($).tokens,U&&(U=Me.post_process(U).tokens);else{const $e=Me.post_process($,U,ee);$=$e.tokens,se=$e.token_type_ids}return{tokens:$,token_type_ids:se}}}class Fe extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new Ne($);case"Metaspace":return new Or($);case"ByteLevel":return new Oe($);case"Replace":return new tt($);case"ByteFallback":return new Re($);case"Fuse":return new rt($);case"Strip":return new Ze($);case"Sequence":return new ht($);case"CTC":return new ot($);case"BPEDecoder":return new Rt($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class tt extends Fe{decode_chain($){const U=f(this.config.pattern);return U===null?$:$.map(ee=>ee.replaceAll(U,this.config.content))}}class Re extends Fe{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const U=[];let ee=[];for(const se of $){let Me=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const $e=parseInt(se.slice(3,5),16);isNaN($e)||(Me=$e)}if(Me!==null)ee.push(Me);else{if(ee.length>0){const $e=this.text_decoder.decode(Uint8Array.from(ee));U.push($e),ee=[]}U.push(se)}}if(ee.length>0){const se=this.text_decoder.decode(Uint8Array.from(ee));U.push(se),ee=[]}return U}}class rt extends Fe{decode_chain($){return[$.join("")]}}class Ze extends Fe{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(U=>{let ee=0;for(let Me=0;Me(ee!==0&&(U.startsWith(this.config.prefix)?U=U.replace(this.config.prefix,""):U=" "+U),this.cleanup&&(U=k(U)),U))}}class Oe extends Fe{constructor($){super($),this.byte_decoder=X,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string($){const U=$.join(""),ee=new Uint8Array([...U].map(Me=>this.byte_decoder[Me]));return this.text_decoder.decode(ee)}decode_chain($){const U=[];let ee=[];for(const se of $)this.added_tokens.find(Me=>Me.content===se)!==void 0?(ee.length>0&&(U.push(this.convert_tokens_to_string(ee)),ee=[]),U.push(se)):ee.push(se);return ee.length>0&&U.push(this.convert_tokens_to_string(ee)),U}}class ot extends Fe{constructor($){super($),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string($){if($.length===0)return"";const U=[$[0]];for(let Me=1;Me<$.length;++Me)$[Me]!==U.at(-1)&&U.push($[Me]);let se=U.filter(Me=>Me!==this.pad_token).join("");return this.cleanup&&(se=k(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain($){return[this.convert_tokens_to_string($)]}}class ht extends Fe{constructor($){super($),this.decoders=$.decoders.map(U=>Fe.fromConfig(U))}decode_chain($){return this.decoders.reduce((U,ee)=>ee.decode_chain(U),$)}}class Rt extends Fe{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((U,ee)=>U.replaceAll(this.suffix,ee===$.length-1?"":" "))}}class It extends Fe{decode_chain($){let U="";for(let ee=1;ee<$.length;ee+=2)U+=$[ee];return[U]}}class gr extends Q{constructor($){super(),this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:U=void 0}={}){let ee=$.replaceAll(" ",this.strRep);return!ee.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&U===0)&&(ee=this.strRep+ee),[ee]}}class Or extends Fe{constructor($){super($),this.replacement=$.replacement}decode_chain($){const U=[];for(let ee=0;ee<$.length;++ee){let se=$[ee].replaceAll(this.replacement," ");ee==0&&se.startsWith(" ")&&(se=se.substring(1)),U.push(se)}return U}}class zt extends ne{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(ee=>ee.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class Rr extends Q{constructor($){super(),this.tokenizers=$.pretokenizers.map(U=>Q.fromConfig(U))}pre_tokenize_text($,U){return this.tokenizers.reduce((ee,se)=>se.pre_tokenize(ee,U),[$])}}class qs extends Q{constructor($){super()}pre_tokenize_text($,U){return $.match(/\w+|[^\w\s]+/g)||[]}}class Qs extends Q{constructor($){super()}pre_tokenize_text($,U){return b($)}}class Xs extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,U){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}class or extends Q{constructor($){super(),this._length=$.length}pre_tokenize_text($,U){const ee=[];for(let se=0;se<$.length;se+=this._length)ee.push($.slice(se,se+this._length));return ee}}const Sr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Qr(ue,$,U,ee){for(const se of Object.keys(ue)){const Me=$-ue[se].length,$e=U(se),Xe=new Array(Me).fill($e);ue[se]=ee==="right"?(0,n.mergeArrays)(ue[se],Xe):(0,n.mergeArrays)(Xe,ue[se])}}function Bs(ue,$){for(const U of Object.keys(ue))ue[U].length=$}class ft extends s.Callable{return_token_type_ids=!1;padding_side="right";constructor($,U){super(),this.config=U,this.normalizer=ne.fromConfig($.normalizer),this.pre_tokenizer=Q.fromConfig($.pre_tokenizer),this.model=H.fromConfig($.model,U),this.post_processor=Ce.fromConfig($.post_processor),this.decoder=Fe.fromConfig($.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ee of $.added_tokens){const se=new F(ee);this.added_tokens.push(se),this.model.tokens_to_ids.set(se.content,se.id),this.model.vocab[se.id]=se.content,se.special&&(this.special_tokens.push(se.content),this.all_special_ids.push(se.id))}if(this.additional_special_tokens=U.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(ee=>ee.content)),this.added_tokens_map=new Map(this.added_tokens.map(ee=>[ee.content,ee])),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=U.model_max_length,this.remove_space=U.remove_space,this.clean_up_tokenization_spaces=U.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=U.do_lowercase_and_remove_accent??!1,U.padding_side&&(this.padding_side=U.padding_side),this.add_bos_token=U.add_bos_token,this.add_eos_token=U.add_eos_token,this.legacy=!1,this.chat_template=U.chat_template??null,Array.isArray(this.chat_template)){const ee=Object.create(null);for(const{name:se,template:Me}of this.chat_template){if(typeof se!="string"||typeof Me!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ee[se]=Me}this.chat_template=ee}this._compiled_template_cache=new Map}getToken(...$){for(const U of $){const ee=this.config[U];if(ee)if(typeof ee=="object"){if(ee.__type==="AddedToken")return ee.content;throw Error(`Unknown token: ${ee}`)}else return ee}return null}static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const Je=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe});return new this(...Je)}_call($,{text_pair:U=null,add_special_tokens:ee=!0,padding:se=!1,truncation:Me=null,max_length:$e=null,return_tensor:Xe=!0,return_token_type_ids:Je=null}={}){const Ye=Array.isArray($);let Ke;if(Ye){if($.length===0)throw Error("text array must be non-empty");if(U!==null){if(Array.isArray(U)){if($.length!==U.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ke=$.map((Et,rr)=>this._encode_plus(Et,{text_pair:U[rr],add_special_tokens:ee,return_token_type_ids:Je}))}else Ke=$.map(Et=>this._encode_plus(Et,{add_special_tokens:ee,return_token_type_ids:Je}))}else{if($==null)throw Error("text may not be null or undefined");if(Array.isArray(U))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ke=[this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:Je})]}if($e===null?$e=this.model_max_length:Me===null&&(se===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),$e=this.model_max_length):se===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),Me=!0)),se===!0&&($e=Math.min((0,i.max)(Ke.map(Et=>Et.input_ids.length))[0],$e??1/0)),$e=Math.min($e,this.model_max_length??1/0),se||Me)for(let Et=0;Et$e?Me&&Bs(Ke[Et],$e):se&&Qr(Ke[Et],$e,rr=>rr==="input_ids"?this.pad_token_id:0,this.padding_side));const $t={};if(Xe){if(!(se&&Me)&&Ke.some(rr=>{for(const br of Object.keys(rr))if(rr[br].length!==Ke[0][br]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Et=[Ke.length,Ke[0].input_ids.length];for(const rr of Object.keys(Ke[0]))$t[rr]=new a.Tensor("int64",BigInt64Array.from(Ke.flatMap(br=>br[rr]).map(BigInt)),Et)}else{for(const Et of Object.keys(Ke[0]))$t[Et]=Ke.map(rr=>rr[Et]);if(!Ye)for(const Et of Object.keys($t))$t[Et]=$t[Et][0]}return $t}_encode_text($){if($===null)return null;const U=this.added_tokens_splitter.split($);for(let se=0;se0&&(U[se-1]=U[se-1].trimEnd()),Me.rstrip&&se{if(se.length===0)return[];if(this.added_tokens_map.has(se))return[se];if(this.remove_space===!0&&(se=se.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(se=v(se)),this.normalizer!==null&&(se=this.normalizer(se)),se.length===0)return[];const $e=this.pre_tokenizer!==null?this.pre_tokenizer(se,{section_index:Me}):[se];return this.model($e)})}_encode_plus($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){const{tokens:Me,token_type_ids:$e}=this._tokenize_helper($,{pair:U,add_special_tokens:ee}),Xe=this.model.convert_tokens_to_ids(Me),Je={input_ids:Xe,attention_mask:new Array(Xe.length).fill(1)};return(se??this.return_token_type_ids)&&$e&&(Je.token_type_ids=$e),Je}_tokenize_helper($,{pair:U=null,add_special_tokens:ee=!1}={}){const se=this._encode_text($),Me=this._encode_text(U);return this.post_processor?this.post_processor(se,Me,{add_special_tokens:ee}):{tokens:(0,n.mergeArrays)(se??[],Me??[])}}tokenize($,{pair:U=null,add_special_tokens:ee=!1}={}){return this._tokenize_helper($,{pair:U,add_special_tokens:ee}).tokens}encode($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){return this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:se}).input_ids}batch_decode($,U={}){return $ instanceof a.Tensor&&($=$.tolist()),$.map(ee=>this.decode(ee,U))}decode($,U={}){if($ instanceof a.Tensor&&($=y($)),!Array.isArray($)||$.length===0||!(0,n.isIntegralNumber)($[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single($,U)}decode_single($,{skip_special_tokens:U=!1,clean_up_tokenization_spaces:ee=null}){let se=this.model.convert_ids_to_tokens($);U&&(se=se.filter($e=>!this.special_tokens.includes($e)));let Me=this.decoder?this.decoder(se):se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Me=Me.replaceAll(this.decoder.end_of_word_suffix," "),U&&(Me=Me.trim())),(ee??this.clean_up_tokenization_spaces)&&(Me=k(Me)),Me}get_chat_template({chat_template:$=null,tools:U=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ee=this.chat_template;if($!==null&&Object.hasOwn(ee,$))$=ee[$];else if($===null)if(U!==null&&"tool_use"in ee)$=ee.tool_use;else if("default"in ee)$=ee.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(ee).sort()}.`)}else if($===null)if(this.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 $}apply_chat_template($,{tools:U=null,documents:ee=null,chat_template:se=null,add_generation_prompt:Me=!1,tokenize:$e=!0,padding:Xe=!1,truncation:Je=!1,max_length:Ye=null,return_tensor:Ke=!0,return_dict:$t=!1,tokenizer_kwargs:Et={},...rr}={}){if(se=this.get_chat_template({chat_template:se,tools:U}),typeof se!="string")throw Error(`chat_template must be a string, but got ${typeof se}`);let br=this._compiled_template_cache.get(se);br===void 0&&(br=new c.Template(se),this._compiled_template_cache.set(se,br));const Xt=Object.create(null);for(const Ht of Sr){const qr=this.getToken(Ht);qr&&(Xt[Ht]=qr)}const sr=br.render({messages:$,add_generation_prompt:Me,tools:U,documents:ee,...Xt,...rr});if($e){const Ht=this._call(sr,{add_special_tokens:!1,padding:Xe,truncation:Je,max_length:Ye,return_tensor:Ke,...Et});return $t?Ht:Ht.input_ids}return sr}}class qt extends ft{return_token_type_ids=!0}class Ps extends ft{return_token_type_ids=!0}class Cs extends ft{return_token_type_ids=!0}class Kr extends ft{return_token_type_ids=!0}class yt extends ft{return_token_type_ids=!0}class Ss extends ft{return_token_type_ids=!0}class C extends ft{return_token_type_ids=!0}class q extends ft{return_token_type_ids=!0}class R extends ft{return_token_type_ids=!0}class G extends ft{}class Z extends ft{}class ce extends ft{return_token_type_ids=!0;constructor($,U){super($,U),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ye extends ft{return_token_type_ids=!0}class et extends ft{}class ut extends ft{}class He extends ft{}class Mt extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class qe extends Mt{}class Tt extends ft{}class kt extends ft{}const Mr="▁";class dr extends ft{padding_side="left";constructor($,U){super($,U),this.legacy=U.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gr({replacement:Mr,prepend_scheme:"first"}))}_encode_text($){if($===null)return null;if(this.legacy||$.length===0)return super._encode_text($);let U=super._encode_text(Mr+$.replaceAll(Mr," "));return U.length>1&&U[0]===Mr&&this.special_tokens.includes(U[1])&&(U=U.slice(1)),U}}class ar extends ft{}class Tr extends ft{}class Is extends ft{}class Dr extends ft{}class $s extends ft{}class Lr extends ft{}class zr extends ft{}class ts extends ft{}class wr extends ft{}function ir(ue,$,U,ee){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const se=ee.src_lang,Me=ee.tgt_lang;if(!ue.language_codes.includes(Me))throw new Error(`Target language code "${Me}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(se!==void 0){if(!ue.language_codes.includes(se))throw new Error(`Source language code "${se}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const $e of ue.post_processor.config.single)if("SpecialToken"in $e&&ue.languageRegex.test($e.SpecialToken.id)){$e.SpecialToken.id=ue.lang_to_token(se);break}}return ee.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(Me)])[0],ue._call($,U)}class Hr extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class rs extends ft{constructor($,U){super($,U),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)).map(ee=>ee.slice(2,-2)),this.lang_to_token=ee=>`__${ee}__`}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class Rs extends ft{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:U=!1,return_language:ee=!1,time_precision:se=null,force_full_sequences:Me=!0}={}){if(se===null)throw Error("Must specify time_precision");let $e=null;const Xe=U==="word";function Je(){return{language:$e,timestamp:[null,null],text:""}}const Ye=[];let Ke=Je(),$t=0;const Et=this.timestamp_begin,br=Et+1500;let Xt=[],sr=[],Ht=!1,qr=null;const ns=new Set(this.all_special_ids);for(const Yt of $){const hr=Yt.tokens,Ir=Xe?Yt.token_timestamps:null;let Xr=null,ps=Et;if("stride"in Yt){const[vr,Zt,_r]=Yt.stride;if($t-=Zt,qr=vr-_r,Zt&&(ps=Zt/se+Et),_r)for(let lr=hr.length-1;lr>=0;--lr){const Ur=Number(hr[lr]);if(Ur>=Et){if(Xr!==null&&(Ur-Et)*se=Et&&Zt<=br){const _r=(Zt-Et)*se+$t,lr=(0,i.round)(_r,2);if(Xr!==null&&Zt>=Xr)Ht=!0;else if(Ht||Xt.length>0&&Zt0?(Xt.push(yr),Xe&&sr.push(os)):Xt.every(vr=>vr.length===0)&&(Ke=Je(),Xt=[],yr=[],sr=[],os=[])}if(Xt.length>0){if(Me&&U)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[Yt,hr]=this.findLongestCommonSequence(Xt,sr),Ir=this.decode(Yt);Ke.text=Ir,Xe&&(Ke.words=this.collateWordTimestamps(Yt,hr,$e)),Ye.push(Ke)}let Er=Object.create(null);const ds=Ye.map(Yt=>Yt.text).join("");if(U||ee){for(let Yt=0;Yt0;let Xe=$e?[]:null,Je=$e?U[0]:null;for(let Ye=1;Ye<$.length;++Ye){const Ke=$[Ye];let $t=0,Et=[se,se,0,0];const rr=Ke.length;for(let Er=1;ErZt===ps[_r]&&Je[ds+_r]<=U[Ye][Ir+_r]).length:yr=hr.filter((Zt,_r)=>Zt===ps[_r]).length;const os=Er/1e4,vr=yr/Er+os;yr>1&&vr>$t&&($t=vr,Et=[ds,Yt,Ir,Xr])}const[br,Xt,sr,Ht]=Et,qr=Math.floor((Xt+br)/2),ns=Math.floor((Ht+sr)/2);Me.push(...ee.slice(0,qr)),ee=Ke.slice(ns),se=ee.length,$e&&(Xe.push(...Je.slice(0,qr)),Je=U[Ye].slice(ns))}return Me.push(...ee),$e?(Xe.push(...Je),[Me,Xe]):[Me,[]]}collateWordTimestamps($,U,ee){const[se,Me,$e]=this.combineTokensIntoWords($,ee),Xe=[];for(let Je=0;Je=se){const Xe=(($e-se)*ee).toFixed(2);Me.push(`<|${Xe}|>`),Me.push([])}else Me[Me.length-1].push($e);return Me=Me.map($e=>typeof $e=="string"?$e:super.decode($e,U)),Me.join("")}splitTokensOnUnicode($){const U=this.decode($,{decode_with_timestamps:!0}),ee="�",se=[],Me=[],$e=[];let Xe=[],Je=[],Ye=0;for(let Ke=0;Ke<$.length;++Ke){const $t=$[Ke];Xe.push($t),Je.push(Ke);const Et=this.decode(Xe,{decode_with_timestamps:!0});(!Et.includes(ee)||U[Ye+Et.indexOf(ee)]===ee)&&(se.push(Et),Me.push(Xe),$e.push(Je),Xe=[],Je=[],Ye+=Et.length)}return[se,Me,$e]}splitTokensOnSpaces($){const[U,ee,se]=this.splitTokensOnUnicode($),Me=[],$e=[],Xe=[],Je=new RegExp(`^[${E}]$`,"gu");for(let Ye=0;Ye=this.model.tokens_to_ids.get("<|endoftext|>"),br=Ke.startsWith(" "),Xt=Ke.trim(),sr=Je.test(Xt);if(rr||br||sr||Me.length===0)Me.push(Ke),$e.push($t),Xe.push(Et);else{const Ht=Me.length-1;Me[Ht]+=Ke,$e[Ht].push(...$t),Xe[Ht].push(...Et)}}return[Me,$e,Xe]}mergePunctuations($,U,ee,se,Me){const $e=structuredClone($),Xe=structuredClone(U),Je=structuredClone(ee);let Ye=$e.length-2,Ke=$e.length-1;for(;Ye>=0;)$e[Ye].startsWith(" ")&&se.includes($e[Ye].trim())?($e[Ke]=$e[Ye]+$e[Ke],Xe[Ke]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ke]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ye]="",Xe[Ye]=[],Je[Ye]=[]):Ke=Ye,--Ye;for(Ye=0,Ke=1;Ke<$e.length;)!$e[Ye].endsWith(" ")&&Me.includes($e[Ke])?($e[Ye]+=$e[Ke],Xe[Ye]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ye]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ke]="",Xe[Ke]=[],Je[Ke]=[]):Ye=Ke,++Ke;return[$e.filter($t=>$t),Xe.filter($t=>$t.length>0),Je.filter($t=>$t.length>0)]}}class ks extends ft{}class As extends ft{}class Fs extends ft{}class ss extends ft{constructor($,U){super($,U),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ee=>this.languageRegex.test(ee)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[U,...ee]=$.trim().split(this.languageRegex);if(ee.length===0)return super._encode_text(U);if(ee.length===2){const[se,Me]=ee;return this.supported_language_codes.includes(se)||console.warn(`Unsupported language code "${se}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,n.mergeArrays)([se],super._encode_text(Me))}}}class Nr extends ft{}class ze extends ft{}class Ue extends ft{}class nt extends ft{}class Kt extends ft{}class Ns extends ft{constructor($,U){super($,U),this.decoder=new It({})}}class Os extends ft{}class js extends ft{}class Dn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:et,DistilBertTokenizer:G,CamembertTokenizer:Z,DebertaTokenizer:yt,DebertaV2Tokenizer:Ss,BertTokenizer:qt,HerbertTokenizer:C,ConvBertTokenizer:q,RoFormerTokenizer:R,XLMTokenizer:ce,ElectraTokenizer:ye,MobileBertTokenizer:Cs,SqueezeBertTokenizer:Kr,AlbertTokenizer:Ps,GPT2Tokenizer:ut,BartTokenizer:He,MBartTokenizer:Mt,MBart50Tokenizer:qe,RobertaTokenizer:Tt,WhisperTokenizer:Rs,CodeGenTokenizer:ks,CLIPTokenizer:As,SiglipTokenizer:Fs,MarianTokenizer:ss,BloomTokenizer:kt,NllbTokenizer:Hr,M2M100Tokenizer:rs,LlamaTokenizer:dr,CodeLlamaTokenizer:ar,XLMRobertaTokenizer:Tr,MPNetTokenizer:Is,FalconTokenizer:Dr,GPTNeoXTokenizer:$s,EsmTokenizer:Lr,Wav2Vec2CTCTokenizer:Nr,BlenderbotTokenizer:ze,BlenderbotSmallTokenizer:Ue,SpeechT5Tokenizer:nt,NougatTokenizer:Kt,VitsTokenizer:Ns,Qwen2Tokenizer:zr,GemmaTokenizer:ts,Grok1Tokenizer:wr,CohereTokenizer:Os,MgpstrTokenizer:js,PreTrainedTokenizer:ft};static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const[Je,Ye]=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe}),Ke=Ye.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let $t=this.TOKENIZER_CLASS_MAPPING[Ke];return $t||(console.warn(`Unknown tokenizer class "${Ke}", attempting to construct from base class.`),$t=ft),new $t(Je,Ye)}}}),"./src/utils/audio.js":((e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>W,hamming:()=>u,hanning:()=>d,mel_filter_bank:()=>I,read_audio:()=>c,spectrogram:()=>S,window_function:()=>O});var s=t("./src/utils/hub.js"),n=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("./src/utils/tensor.js"),l=t("?7992");async function c(B,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const X=await(await(0,s.getFile)(B)).arrayBuffer(),J=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const re=await J.decodeAudioData(X);let ne;if(re.numberOfChannels===2){const le=Math.sqrt(2),pe=re.getChannelData(0),oe=re.getChannelData(1);ne=new Float32Array(pe.length);for(let K=0;K2595*Math.log10(1+B/700),kaldi:B=>1127*Math.log(1+B/700),slaney:(B,Y=1e3,X=15,J=27/Math.log(6.4))=>B>=Y?X+Math.log(B/Y)*J:3*B/200};function _(B,Y="htk"){const X=f[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}const y={htk:B=>700*(10**(B/2595)-1),kaldi:B=>700*(Math.exp(B/1127)-1),slaney:(B,Y=1e3,X=15,J=Math.log(6.4)/27)=>B>=X?Y*Math.exp(J*(B-X)):200*B/3};function k(B,Y="htk"){const X=y[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}function w(B,Y){const X=Float64Array.from({length:Y.length-1},(le,pe)=>Y[pe+1]-Y[pe]),J=Array.from({length:B.length},()=>new Array(Y.length));for(let le=0;lenew Array(B.length));for(let le=0;leB+J*ne)}function I(B,Y,X,J,re,ne=null,le="htk",pe=!1){if(ne!==null&&ne!=="slaney")throw new Error('norm must be one of null or "slaney"');if(B<2)throw new Error(`Require num_frequency_bins: ${B} >= 2`);if(X>J)throw new Error(`Require min_frequency: ${X} <= max_frequency: ${J}`);const oe=_(X,le),K=_(J,le),N=v(oe,K,Y+2);let D=k(N,le),te;if(pe){const Ae=re/((B-1)*2);te=_(Float64Array.from({length:B},(Ie,je)=>je*Ae),le),D=N}else te=v(0,Math.floor(re/2),B);const he=w(te,D);if(ne!==null&&ne==="slaney")for(let Ae=0;Aere)throw Error(`frame_length (${X}) may not be larger than fft_length (${re})`);if(xe!==X)throw new Error(`Length of the window (${xe}) must equal frame_length (${X})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(ne===null&&D!==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(!N)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(le)switch(pe){case"reflect":{const Ne=Math.floor((re-1)/2)+1;B=T(B,Ne,Ne);break}case"constant":{const Ne=Math.floor(re/2),Oe=new B.constructor(B.length+2*Ne);Oe.set(B,Ne),B=Oe;break}default:throw new Error(`pad_mode="${pe}" not implemented yet.`)}let Ce=Math.floor(1+Math.floor((B.length-X)/J));Q!==null&&CeCe?de&&(fe=z):fe=De=z);const Ee=new n.FFT(re),We=new Float64Array(re),Fe=new Float64Array(Ee.outputBufferSize),tt=new Float32Array(ge*fe);for(let Ne=0;Ne=1;--ht)We[ht]-=K*We[ht-1];We[0]*=1-K}for(let ht=0;htMath.pow(pe,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(X&&(le=le.subarray(0,B)),J===null)return le;if(B>J)throw new Error(`Length of the window (${B}) may not be larger than frame_length (${J})`);return le}function F(B,Y){let X=44;const J=new ArrayBuffer(X+B.length*4),re=new DataView(J);H(re,0,"RIFF"),re.setUint32(4,36+B.length*4,!0),H(re,8,"WAVE"),H(re,12,"fmt "),re.setUint32(16,16,!0),re.setUint16(20,3,!0),re.setUint16(22,1,!0),re.setUint32(24,Y,!0),re.setUint32(28,Y*4,!0),re.setUint16(32,4,!0),re.setUint16(34,32,!0),H(re,36,"data"),re.setUint32(40,B.length*4,!0);for(let ne=0;ne{let ne=await re.arrayBuffer();l.writeFileSync(J,Buffer.from(ne))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await X(Y,this.toBlob())}}}),"./src/utils/constants.js":((e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>n,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",i=o,a="processor_config.json",l="chat_template.jinja",c="generation_config.json"}),"./src/utils/core.js":((e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>o,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>y,pop:()=>p,product:()=>u,reverseDictionary:()=>n,saveBlob:()=>_});function s(v,I){v&&v(I)}function n(v){return Object.fromEntries(Object.entries(v).map(([I,T])=>[T,I]))}function o(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(v){return v?.prototype?.__proto__?.constructor?.name==="TypedArray"}function a(v){return Number.isInteger(v)||typeof v=="bigint"}function l(v){return v==null||v===-1}function c(v){const I=[];let T=v;for(;Array.isArray(T);)I.push(T.length),T=T[0];return I}function p(v,I,T=void 0){const b=v[I];if(b!==void 0)return delete v[I],b;if(T===void 0)throw Error(`Key ${I} does not exist in object.`);return T}function d(...v){return Array.prototype.concat.apply([],v)}function u(...v){return v.reduce((I,T)=>I.flatMap(b=>T.map(E=>[b,E])))}function f(v,I){return Math.abs((v+I)%(2*I)-I)}function _(v,I){const T=URL.createObjectURL(I),b=document.createElement("a");b.href=T,b.download=v,b.click(),b.remove(),URL.revokeObjectURL(T)}function y(v,I){return Object.assign({},...I.map(T=>{if(v[T]!==void 0)return{[T]:v[T]}}))}function k(v){let I=0;for(const T of v)++I;return I}function w(v,I){let T=0;for(const b of v)b===I&&++T;return T}}),"./src/utils/data-structures.js":((e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>n,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,u=1/0){this._heap=[],this._comparator=d,this._maxSize=u}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const u of d)if(this.size0&&this._swap(0,u),this._heap.pop(),this._siftDown(),d}replace(d){const u=this.peek();return this._heap[0]=d,this._siftDown(),u}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,u){return this._comparator(this._heap[d],this._heap[u])}_swap(d,u){const f=this._heap[d];this._heap[d]=this._heap[u],this._heap[u]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),y=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(y.clone()),this.beginNodes[this.len].push(y),this.endNodes[0].push(_)}insert(d,u,f,_){const y=this.nodes.length,k=new a(_,y,d,u,f);this.beginNodes[d].push(k),this.endNodes[d+u].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let u=0;for(;u<=d;){if(this.beginNodes[u].length==0)return[];for(let w of this.beginNodes[u]){w.prev=null;let v=0,I=null;for(let T of this.endNodes[u]){const b=T.backtraceScore+w.score;(I===null||b>v)&&(I=T.clone(),v=b)}if(I!==null)w.prev=I,w.backtraceScore=v;else return[]}++u}const f=[],y=this.beginNodes[d][0].prev;if(y===null)return[];let k=y.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class a{constructor(d,u,f,_,y){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=y,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){const u=Object.create(null);for(const f of d){let _=u;for(let y=0;y_&&u.push(d.slice(_,y)),u.push(w),y+=w.length,_=y):++y}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}}),"./src/utils/devices.js":((e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})}),"./src/utils/dtypes.js":((e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>o});var s=t("./src/env.js"),n=t("./src/utils/devices.js");const o=(function(){let c;return async function(){if(c===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)c=!1;else try{c=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{c=!1}return c}})(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[n.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})}),"./src/utils/generic.js":((e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let n=function(...o){return n._call(...o)};return Object.setPrototypeOf(n,new.target.prototype)}_call(...n){throw Error("Must implement _call method in subclass")}}}),"./src/utils/hub.js":((e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>v,getModelJSON:()=>T,getModelText:()=>I});var s=t("?7992"),n=t("?5af5"),o=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(S){if(this.filePath=S,this.headers=new Headers,this.exists=s.existsSync(S),this.exists){this.status=200,this.statusText="OK";let O=s.statSync(S);this.headers.set("content-length",O.size.toString()),this.updateContentType();const F=s.createReadStream(S);this.body=new ReadableStream({start(H){F.on("data",W=>H.enqueue(W)),F.on("end",()=>H.close()),F.on("error",W=>H.error(W))},cancel(){F.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const S=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[S]??"application/octet-stream")}clone(){let S=new c(this.filePath);return S.exists=this.exists,S.status=this.status,S.statusText=this.statusText,S.headers=new Headers(this.headers),S}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const S=await s.promises.readFile(this.filePath);return new Blob([S],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,S=null,O=null){let F;try{F=new URL(x)}catch{return!1}return!(S&&!S.includes(F.protocol)||O&&!O.includes(F.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(x){return!(!d.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function f(x){if(o.env.useFS&&!p(x,["http:","https:","blob:"]))return new c(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&process?.release?.name==="node"){const S=!!qc?.TESTING_REMOTELY,O=o.env.version,F=new Headers;if(F.set("User-Agent",`transformers.js/${O}; is_ci/${S};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const W=qc?.HF_TOKEN??qc?.HF_ACCESS_TOKEN;W&&F.set("Authorization",`Bearer ${W}`)}return fetch(x,{headers:F})}else return fetch(x)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function y(x,S,O){if(!O)return null;const F=_[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${F}: "${S}".`)}class k{constructor(S){this.path=S}async match(S){let O=n.join(this.path,S),F=new c(O);if(F.exists)return F}async put(S,O,F=void 0){let H=n.join(this.path,S);try{const W=O.headers.get("Content-Length"),B=parseInt(W??"0");let Y=0;await s.promises.mkdir(n.dirname(H),{recursive:!0});const X=s.createWriteStream(H),J=O.body.getReader();for(;;){const{done:re,value:ne}=await J.read();if(re)break;await new Promise((pe,oe)=>{X.write(ne,K=>{if(K){oe(K);return}pe()})}),Y+=ne.length;const le=B?Y/B*100:0;F?.({progress:le,loaded:Y,total:B})}X.close()}catch(W){try{await s.promises.unlink(H)}catch{}throw W}}}async function w(x,...S){for(let O of S)try{let F=await x.match(O);if(F)return F}catch{continue}}async function v(x,S,O=!0,F={},H=!1){if(!o.env.allowLocalModels){if(F.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!o.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(F.progress_callback,{status:"initiate",name:x,file:S});let W;if(!W&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");W=o.env.customCache}if(!W&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{W=await caches.open("transformers-cache")}catch(te){console.warn("An error occurred while opening the browser cache:",te)}}if(!W&&o.env.useFSCache){if(!o.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");W=new k(F.cache_dir??o.env.cacheDir)}const B=F.revision??"main",Y=E(x,S),X=u(x),J=X?E(o.env.localModelPath,Y):Y,re=E(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(B)),S);let ne;const le=W instanceof k?B==="main"?Y:E(x,B,S):re;let pe=!1,oe;W&&(oe=await w(W,J,le));const K=oe!==void 0;if(oe===void 0){if(o.env.allowLocalModels)if(p(Y,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}else try{oe=await f(J),ne=J}catch(he){console.warn(`Unable to load from local path "${J}": "${he}"`)}if(oe===void 0||oe.status===404){if(F.local_files_only||!o.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(!X)throw Error(`Local file missing at "${J}" and download aborted due to invalid model ID "${x}".`);if(oe=await f(re),oe.status!==200)return y(oe.status,re,O);ne=le}pe=W&&typeof Response<"u"&&oe instanceof Response&&oe.status===200}(0,i.dispatchCallback)(F.progress_callback,{status:"download",name:x,file:S});let N;if(!(o.apis.IS_NODE_ENV&&H)){let te;F.progress_callback?K&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(te=new Uint8Array(await oe.arrayBuffer()),(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,progress:100,loaded:te.length,total:te.length})):te=await b(oe,he=>{(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he})}):te=new Uint8Array(await oe.arrayBuffer()),N=te}if(pe&&ne&&await W.match(ne)===void 0)if(N)await W.put(ne,new Response(N,{headers:oe.headers})).catch(te=>{console.warn(`Unable to add response to browser cache: ${te}.`)});else{const te=F.progress_callback?he=>(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he}):void 0;await W.put(ne,oe,te)}if((0,i.dispatchCallback)(F.progress_callback,{status:"done",name:x,file:S}),N){if(!o.apis.IS_NODE_ENV&&H)throw new Error("Cannot return path in a browser environment.");return N}if(oe instanceof c)return oe.filePath;const D=await W?.match(ne);if(D instanceof c)return D.filePath;if(D instanceof Response)return new Uint8Array(await D.arrayBuffer());if(typeof D=="string")return D;throw new Error("Unable to get model file path or buffer.")}async function I(x,S,O=!0,F={}){const H=await v(x,S,O,F,!1);return H===null?null:new TextDecoder("utf-8").decode(H)}async function T(x,S,O=!0,F={}){const H=await I(x,S,O,F);return H===null?{}:JSON.parse(H)}async function b(x,S){const O=x.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(O??"0"),H=new Uint8Array(F),W=0;const B=x.body.getReader();async function Y(){const{done:X,value:J}=await B.read();if(X)return;const re=W+J.length;if(re>F){F=re;const le=new Uint8Array(F);le.set(H),H=le}H.set(J,W),W=re;const ne=W/F*100;return S({progress:ne,loaded:W,total:F}),Y()}return await Y(),H}function E(...x){return x=x.map((S,O)=>(O&&(S=S.replace(new RegExp("^/"),"")),O!==x.length-1&&(S=S.replace(new RegExp("/$"),"")),S)),x.join("/")}}),"./src/utils/image.js":((e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>y});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,c,p;const d=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(d)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async k=>{const v=(await k.metadata()).channels,{data:I,info:T}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),b=new _(new Uint8ClampedArray(I),T.width,T.height,T.channels);return v!==void 0&&v!==T.channels&&b.convert(v),b};else throw new Error("Unable to load image processing library.");const u={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(w,v,I,T){this.data=w,this.width=v,this.height=I,this.channels=T}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const I=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _(I,w.width,w.height,4)}static async fromURL(w){const v=await(0,n.getFile)(w);if(v.status!==200)throw new Error(`Unable to read image from "${w}" (${v.status} ${v.statusText})`);const I=await v.blob();return this.fromBlob(I)}static async fromBlob(w){if(d){const v=await p(w),I=l(v.width,v.height).getContext("2d");return I.drawImage(v,0,0),new this(I.getImageData(0,0,v.width,v.height).data,v.width,v.height,4)}else{const v=a(await w.arrayBuffer());return await p(v)}}static fromTensor(w,v="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(v==="CHW")w=w.transpose(1,2,0);else if(v!=="HWC")throw new Error(`Unsupported channel format: ${v}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let v=0,I=0;v=0?S=I:F=-I,T>=0?O=T:H=-T,x.drawImage(E,S,O,w,v,F,H,w,v),new _(x.getImageData(0,0,w,v).data,w,v,4).convert(b)}else{let b=this.toSharp();if(I>=0&&T>=0)b=b.extract({left:Math.floor(I),top:Math.floor(T),width:w,height:v});else if(I<=0&&T<=0){const E=Math.floor(-T),x=Math.floor(-I);b=b.extend({top:E,left:x,right:w-this.width-x,bottom:v-this.height-E})}else{let E=[0,0],x=0;T<0?(E[0]=Math.floor(-T),E[1]=v-this.height-E[0]):x=Math.floor(T);let S=[0,0],O=0;I<0?(S[0]=Math.floor(-I),S[1]=w-this.width-S[0]):O=Math.floor(I),b=b.extend({top:E[0],bottom:E[1],left:S[0],right:S[1]}).extract({left:O,top:x,width:w,height:v})}return await p(b)}}async toBlob(w="image/png",v=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:v})}toTensor(w="CHW"){let v=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")v=v.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return v}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),v=l(w.width,w.height),I=new c(w.data,w.width,w.height);return v.getContext("2d").putImageData(I,0,0),v}split(){const{data:w,width:v,height:I,channels:T}=this,b=w.constructor,E=w.length/T,x=Array.from({length:T},()=>new b(E));for(let S=0;Snew _(S,v,I,1))}_update(w,v,I,T=null){return this.data=w,this.width=v,this.height=I,T!==null&&(this.channels=T),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(w){if(d){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const v=w.split(".").pop().toLowerCase(),I=f.get(v)??"image/png",T=await this.toBlob(I);(0,s.saveBlob)(w,T)}else{if(o.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const y=_.read.bind(_)}),"./src/utils/maths.js":((e,r,t)=>{t.r(r),t.d(r,{FFT:()=>y,bankers_round:()=>v,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>I,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>c,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>n,round:()=>w,softmax:()=>o});function s(T,[b,E,x],[S,O],F="bilinear",H=!1){const W=O/x,B=S/E,Y=new T.constructor(S*O*b),X=E*x,J=S*O;for(let re=0;re=0;--H)S[H]=W,x[H]=b[E[H]],W*=x[H];const O=E.map((H,W)=>S[E.indexOf(W)]),F=new T.constructor(T.length);for(let H=0;H=0;--B)W+=Y%b[B]*O[B],Y=Math.floor(Y/b[B]);F[W]=T[H]}return[F,x]}function o(T){const b=d(T)[0],E=T.map(O=>Math.exp(O-b)),x=E.reduce((O,F)=>O+F,0);return E.map(O=>O/x)}function i(T){const b=d(T)[0];let E=0;for(let O=0;OO-b-x)}function a(T,b){let E=0;for(let x=0;xb+E*E,0))}function p(T){if(T.length===0)throw Error("Array must not be empty");let b=T[0],E=0;for(let x=1;xb&&(b=T[x],E=x);return[b,E]}function u(T){return T>0&&(T&T-1)===0}class f{constructor(b){if(this.size=b|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=b<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++E;this._width=E%2===0?E-1:E,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=b[S];return x}toComplexArray(b,E){const x=E||this.createComplexArray();for(let S=0;S>>1],x[S+1]=0;return x}transform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._transform4(b,E,1)}realTransform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._realTransform4(b,E,1)}inverseTransform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._transform4(b,E,-1);for(let x=0;x>=2;F>=2;F>>=2){H=S/F<<1;const J=H>>>2;for(W=0;W>>1,F>>>1)}else for(W=0,B=0;W>>1,F>>>1,x)}const X=this.table;for(F>>=2;F>=2;F>>=2){H=S/F<<1;const re=H>>>1,ne=re>>>1,le=ne>>>1;for(W=0;W>>1;for(let re=2;re>1;++Y){const X=(Y+1-b)**2/2,J=Math.sqrt(W**2+B**2)**X,re=X*Math.atan2(B,W),ne=2*Y;O[ne]=J*Math.cos(re),O[ne+1]=J*Math.sin(re),F[ne]=O[ne],F[ne+1]=-O[ne+1]}this._slicedChirpBuffer=O.subarray(E,x),this._f=new f(S>>1),this._f.transform(this._chirpBuffer,F)}_transform(b,E,x){const S=this._buffer1,O=this._buffer2,F=this._outBuffer1,H=this._outBuffer2,W=this._chirpBuffer,B=this._slicedChirpBuffer,Y=this._a;if(x)for(let X=0;X>1,ne=E[re];S[X]=ne*B[X],S[J]=ne*B[J]}else for(let X=0;X=T.length&&(W=2*(T.length-1)-W),x[F++]=T[W]}x.sort(),E[O]=x[S]}return E}function w(T,b){const E=Math.pow(10,b);return Math.round(T*E)/E}function v(T){const b=Math.round(T);return Math.abs(T)%1===.5?b%2===0?b:b-1:b}function I(T){const b=T.length,E=T[0].length,x=[b+1,E+1],S=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));S[0][0]=0;const O=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let Y=1;Y0||H>0;)switch(W.push(F-1),B.push(H-1),O[F][H]){case 0:--F,--H;break;case 1:--F;break;case 2:--H;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${F}, ${H}]. Please file a bug report.`)}return W.reverse(),B.reverse(),[W,B]}}),"./src/utils/tensor.js":((e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>E,full:()=>B,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>v,matmul:()=>u,mean:()=>F,mean_pooling:()=>w,ones:()=>X,ones_like:()=>J,permute:()=>c,quantize_embeddings:()=>oe,rand:()=>le,randn:()=>pe,rfft:()=>f,slice:()=>k,stack:()=>x,std_mean:()=>O,topk:()=>_,zeros:()=>re,zeros_like:()=>ne});var s=t("./src/utils/maths.js"),n=t("./src/backends/onnx.js"),o=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{get dims(){return this.ort_tensor.dims}set dims(N){this.ort_tensor.dims=N}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...N){return(0,n.isONNXTensor)(N[0])?this.ort_tensor=N[0]:this.ort_tensor=new n.Tensor(N[0],N[1],N[2]),new Proxy(this,{get:(D,te)=>{if(typeof te=="string"){let he=Number(te);if(Number.isInteger(he))return D._getitem(he)}return D[te]},set:(D,te,he)=>D[te]=he})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[N,...D]=this.dims;if(D.length>0){const te=D.reduce((he,Ae)=>he*Ae);for(let he=0;he0){const he=te.reduce((Ae,Ie)=>Ae*Ie);return this._subarray(N,he,te)}else return new a(this.type,[this.data[N]],te)}indexOf(N){const D=this.data;for(let te=0;teve)throw new Error(`Invalid slice: ${de}`);const xe=[Math.max(be,0),Math.min(ve,this.dims[z])];te.push(xe),D.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${de}`)}const he=te.map(([z,de])=>de-z),Ae=he.reduce((z,de)=>z*de),Ie=this.data,je=new Ie.constructor(Ae),Te=this.stride();let Q=!0;for(let z=1;z=0;--be){const xe=he[be];de+=(ve%xe+te[be][0])*Te[be],ve=Math.floor(ve/xe)}je[z]=Ie[de]}return new a(this.type,je,D)}permute(...N){return c(this,N)}transpose(...N){return this.permute(...N)}sum(N=null,D=!1){return this.norm(1,N,D)}norm(N="fro",D=null,te=!1){if(N==="fro")N=2;else if(typeof N=="string")throw Error(`Unsupported norm: ${N}`);const he=this.data,Ae=(Q,z)=>Q+z**N;if(D===null){const Q=he.reduce(Ae,0)**(1/N);return new a(this.type,[Q],[])}const[Ie,je,Te]=S(Ae,this,D,te);if(N!==1)for(let Q=0;Q=0;--Te){const de=this.dims[Te];if(Te!==D){const be=Q%de;je+=be*z,z*=this.dims[Te]}Q=Math.floor(Q/de)}he[Ie]/=Ae[je]}return this}normalize(N=2,D=1){return this.clone().normalize_(N,D)}stride(){return H(this.dims)}squeeze(N=null){return new a(this.type,this.data,I(this.dims,N))}squeeze_(N=null){return this.dims=I(this.dims,N),this}unsqueeze(N=null){return new a(this.type,this.data,T(this.dims,N))}unsqueeze_(N=null){return this.dims=T(this.dims,N),this}flatten_(N=0,D=-1){D=(D+this.dims.length)%this.dims.length;let te=this.dims.slice(0,N),he=this.dims.slice(N,D+1),Ae=this.dims.slice(D+1);return this.dims=[...te,he.reduce((Ie,je)=>Ie*je,1),...Ae],this}flatten(N=0,D=-1){return this.clone().flatten_(N,D)}view(...N){let D=-1;for(let he=0;heje!==D?Ae*Ie:Ae,1);N[D]=te.length/he}return new a(this.type,te,N)}neg_(){const N=this.data;for(let D=0;DN?1:0;return new a("bool",D,this.dims)}lt(N){const D=new Uint8Array(this.data.length),te=this.data;for(let he=0;heMath.min(Ie,je),this,N,D,1/0);return new a(te,he,Ae)}max(N=null,D=!1){if(N===null){const Ie=(0,s.max)(this.data)[0];return new a(this.type,[Ie],[])}const[te,he,Ae]=S((Ie,je)=>Math.max(Ie,je),this,N,D,-1/0);return new a(te,he,Ae)}argmin(N=null,D=!1){if(N!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.min)(this.data)[1];return new a("int64",[BigInt(te)],[])}argmax(N=null,D=!1){if(N!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.max)(this.data)[1];return new a("int64",[BigInt(te)],[])}to(N){if(this.type===N)return this;if(!i.hasOwnProperty(N))throw new Error(`Unsupported type: ${N}`);let D;const te=["int64","uint64"].includes(this.type),he=["int64","uint64"].includes(N);return te&&!he?D=Number:!te&&he&&(["float16","float32","float64"].includes(this.type)?D=Ae=>BigInt(Math.floor(Ae)):D=BigInt),new a(N,i[N].from(this.data,D),this.dims)}}function l(K,N){const D=K.length,te=N.reduce((Ae,Ie)=>Ae*Ie);if(D!==te)throw Error(`cannot reshape array of size ${D} into shape (${N})`);let he=K;for(let Ae=N.length-1;Ae>=0;Ae--)he=he.reduce((Ie,je)=>{let Te=Ie[Ie.length-1];return Te.lengthnew a("int64",K,[K.length]);async function k(K,N,D,te,he){return await(await o.TensorOpRegistry.slice)({x:K,s:y(N),e:y(D),a:y(te),t:y(he??new Array(te.length).fill(1))})}function w(K,N){const D=K.data,te=N.data,he=[K.dims[0],K.dims[2]],Ae=new D.constructor(he[0]*he[1]),[Ie,je,Te]=K.dims;let Q=0;for(let z=0;zD!==1):typeof N=="number"?K[N]===1&&K.splice(N,1):Array.isArray(N)&&(K=K.filter((D,te)=>D!==1||!N.includes(te))),K}function T(K,N){return N=b(N,K.length+1),K=K.slice(),K.splice(N,0,1),K}function b(K,N,D=null,te=!0){if(K<-N||K>=N){if(te)throw new Error(`IndexError: index ${K} is out of bounds for dimension${D===null?"":" "+D} with size ${N}`);return K<-N?0:N}return K<0&&(K=(K%N+N)%N),K}function E(K,N=0){N=b(N,K[0].dims.length);const D=K[0].dims.slice();D[N]=K.reduce((Ie,je)=>Ie+je.dims[N],0);const te=D.reduce((Ie,je)=>Ie*je,1),he=new K[0].data.constructor(te),Ae=K[0].type;if(N===0){let Ie=0;for(const je of K){const Te=je.data;he.set(Te,Ie),Ie+=Te.length}}else{let Ie=0;for(let je=0;je=0;--be){const Ce=Q[be];let ge=ve%Ce;be===N&&(ge+=Ie),de+=ge*xe,xe*=D[be],ve=Math.floor(ve/Ce)}he[de]=Te[z]}Ie+=Q[N]}}return new a(Ae,he,D)}function x(K,N=0){return E(K.map(D=>D.unsqueeze(N)),N)}function S(K,N,D=null,te=!1,he=null){const Ae=N.data,Ie=N.dims;D=b(D,Ie.length);const je=Ie.slice();je[D]=1;const Te=new Ae.constructor(Ae.length/Ie[D]);he!==null&&Te.fill(he);for(let Q=0;Q=0;--de){const xe=Ie[de];if(de!==D){const Ce=be%xe;z+=Ce*ve,ve*=je[de]}be=Math.floor(be/xe)}Te[z]=K(Te[z],Ae[Q],Q,z)}return te||je.splice(D,1),[N.type,Te,je]}function O(K,N=null,D=1,te=!1){const he=K.data,Ae=K.dims;if(N===null){const ve=he.reduce((De,fe)=>De+fe,0)/he.length,xe=Math.sqrt(he.reduce((De,fe)=>De+(fe-ve)**2,0)/(he.length-D)),Ce=new a(K.type,[ve],[]);return[new a(K.type,[xe],[]),Ce]}N=b(N,Ae.length);const Ie=F(K,N,te),je=Ie.data,[Te,Q,z]=S((be,ve,xe,Ce)=>be+(ve-je[Ce])**2,K,N,te);for(let be=0;beQ+z,0);return new a(K.type,[Te/he.length],[])}N=b(N,te.length);const[Ae,Ie,je]=S((Te,Q)=>Te+Q,K,N,D);if(te[N]!==1)for(let Te=0;Te=0;--D)N[D]=te,te*=K[D];return N}function W(K,N,D,te){const he=K.reduce((Ae,Ie)=>Ae*Ie,1);return new a(D,new te(he).fill(N),K)}function B(K,N){let D,te;if(typeof N=="number")D="float32",te=Float32Array;else if(typeof N=="bigint")D="int64",te=BigInt64Array;else if(typeof N=="boolean")D="bool",te=Uint8Array;else throw new Error(`Unsupported data type: ${typeof N}`);return W(K,N,D,te)}function Y(K,N){return B(K.dims,N)}function X(K){return W(K,1n,"int64",BigInt64Array)}function J(K){return X(K.dims)}function re(K){return W(K,0n,"int64",BigInt64Array)}function ne(K){return re(K.dims)}function le(K){const N=K.reduce((D,te)=>D*te,1);return new a("float32",Float32Array.from({length:N},()=>Math.random()),K)}function pe(K){const N=K.reduce((te,he)=>te*he,1);function D(){const te=1-Math.random(),he=1-Math.random();return Math.sqrt(-2*Math.log(te))*Math.cos(2*Math.PI*he)}return new a("float32",Float32Array.from({length:N},()=>D()),K)}function oe(K,N){if(K.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(K.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(N))throw new Error("The precision must be either 'binary' or 'ubinary'");const D=N==="binary",te=D?"int8":"uint8",he=D?Int8Array:Uint8Array,Ae=K.data,Ie=new he(Ae.length/8);for(let je=0;je0?1:0,Q=Math.floor(je/8),z=je%8;Ie[Q]|=Te<<7-z,D&&z===0&&(Ie[Q]-=128)}return new a(te,Ie,[K.dims[0],K.dims[1]/8])}}),"./src/utils/video.js":((e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>o,load_video:()=>a});var s=t("./src/utils/image.js"),n=t("./src/env.js");class o{constructor(c,p){this.image=c,this.timestamp=p}}class i{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((d,u)=>new o(d,(u+1)/(c.length+1)*p))),this.frames=c,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:c=null,fps:p=null}={}){if(!n.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(c==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],u=document.createElement("video");if(u.crossOrigin="anonymous",u.muted=!0,typeof l=="string")u.src=l;else if(l instanceof Blob)u.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)u.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(I=>u.onloadedmetadata=I),u.seekable.start(0)===u.seekable.end(0)){const T=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(T),await new Promise(b=>u.onloadedmetadata=b)}const f=u.duration;let _,y;c!=null?(_=c,y=c===1?0:f/(c-1)):(y=1/p,_=Math.floor(f/y));let k=[];for(let I=0;I<_;++I)k.push(c===1?f/2:I*y);const w=document.createElement("canvas");w.width=u.videoWidth,w.height=u.videoHeight;const v=w.getContext("2d",{willReadFrequently:!0});for(const I of k){u.currentTime=I,await new Promise(x=>{u.onseeked=x}),v.drawImage(u,0,0,w.width,w.height);const T=v.getImageData(0,0,w.width,w.height),b=new s.RawImage(T.data,w.width,w.height,4),E=new o(b,I);d.push(E)}return u.remove(),new i(d,f)}})},Fw={};function Nt(e){var r=Fw[e];if(r!==void 0)return r.exports;var t=Fw[e]={exports:{}};return i1[e](t,t.exports,Nt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Nt.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var n=Object.create(null);Nt.r(n);var o={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>o[a]=()=>t[a]);return o.default=()=>t,Nt.d(n,o),n}})();Nt.d=(e,r)=>{for(var t in r)Nt.o(r,t)&&!Nt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};Nt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);Nt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{Nt.r(m),Nt.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,ArceeForCausalLM:()=>t.ArceeForCausalLM,ArceeModel:()=>t.ArceeModel,ArceePreTrainedModel:()=>t.ArceePreTrainedModel,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>n.AutoConfig,AutoFeatureExtractor:()=>u.AutoFeatureExtractor,AutoImageProcessor:()=>y.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>v.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>I.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>b.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,DINOv3ConvNextModel:()=>t.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>t.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>_.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>t.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>t.DINOv3ViTPreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EdgeTamModel:()=>t.EdgeTamModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>T.EosTokenCriteria,Ernie4_5ForCausalLM:()=>t.Ernie4_5ForCausalLM,Ernie4_5Model:()=>t.Ernie4_5Model,Ernie4_5PreTrainedModel:()=>t.Ernie4_5PreTrainedModel,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>b.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>b.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>d.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>t.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>t.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>w.Gemma3nProcessor,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GraniteMoeHybridForCausalLM:()=>t.GraniteMoeHybridForCausalLM,GraniteMoeHybridModel:()=>t.GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel:()=>t.GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>T.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,Llama4ForCausalLM:()=>t.Llama4ForCausalLM,Llama4PreTrainedModel:()=>t.Llama4PreTrainedModel,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>w.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>b.LogitsProcessor,LogitsProcessorList:()=>b.LogitsProcessorList,LogitsWarper:()=>b.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>T.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>b.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>b.MinNewTokensLengthLogitsProcessor,Ministral3ForCausalLM:()=>t.Ministral3ForCausalLM,Ministral3Model:()=>t.Ministral3Model,Ministral3PreTrainedModel:()=>t.Ministral3PreTrainedModel,MinistralForCausalLM:()=>t.MinistralForCausalLM,MinistralModel:()=>t.MinistralModel,MinistralPreTrainedModel:()=>t.MinistralPreTrainedModel,Mistral3ForConditionalGeneration:()=>t.Mistral3ForConditionalGeneration,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertDecoderForCausalLM:()=>t.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>t.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>t.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NanoChatForCausalLM:()=>t.NanoChatForCausalLM,NanoChatModel:()=>t.NanoChatModel,NanoChatPreTrainedModel:()=>t.NanoChatPreTrainedModel,NeoBertForMaskedLM:()=>t.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>t.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>t.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>t.NeoBertForTokenClassification,NeoBertModel:()=>t.NeoBertModel,NeoBertPreTrainedModel:()=>t.NeoBertPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>b.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>b.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,ParakeetFeatureExtractor:()=>d.ParakeetFeatureExtractor,ParakeetForCTC:()=>t.ParakeetForCTC,ParakeetPreTrainedModel:()=>t.ParakeetPreTrainedModel,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PixtralImageProcessor:()=>_.PixtralImageProcessor,PixtralProcessor:()=>w.PixtralProcessor,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>n.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>o.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>b.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,Sam2ImageProcessor:()=>_.Sam2ImageProcessor,Sam2ImageSegmentationOutput:()=>t.Sam2ImageSegmentationOutput,Sam2Model:()=>t.Sam2Model,Sam2PreTrainedModel:()=>t.Sam2PreTrainedModel,Sam2Processor:()=>w.Sam2Processor,Sam2VideoProcessor:()=>w.Sam2VideoProcessor,Sam3ImageProcessor:()=>_.Sam3ImageProcessor,Sam3TrackerModel:()=>t.Sam3TrackerModel,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolLM3ForCausalLM:()=>t.SmolLM3ForCausalLM,SmolLM3Model:()=>t.SmolLM3Model,SmolLM3PreTrainedModel:()=>t.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>T.StoppingCriteria,StoppingCriteriaList:()=>T.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SupertonicForConditionalGeneration:()=>t.SupertonicForConditionalGeneration,SupertonicPreTrainedModel:()=>t.SupertonicPreTrainedModel,SuppressTokensAtBeginLogitsProcessor:()=>b.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>b.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>I.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>b.TopKLogitsWarper,TopPLogitsWarper:()=>b.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,VaultGemmaForCausalLM:()=>t.VaultGemmaForCausalLM,VaultGemmaModel:()=>t.VaultGemmaModel,VaultGemmaPreTrainedModel:()=>t.VaultGemmaPreTrainedModel,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,VoxtralForConditionalGeneration:()=>t.VoxtralForConditionalGeneration,VoxtralProcessor:()=>w.VoxtralProcessor,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>I.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>b.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>l.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>n.getCacheShapes,hamming:()=>o.hamming,hanning:()=>o.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>l.matmul,max:()=>c.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>o.mel_filter_bank,min:()=>c.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>c.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,randn:()=>l.randn,read_audio:()=>o.read_audio,rfft:()=>l.rfft,round:()=>c.round,slice:()=>l.slice,softmax:()=>c.softmax,spectrogram:()=>o.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>o.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Nt("./src/env.js"),r=Nt("./src/pipelines.js"),t=Nt("./src/models.js"),s=Nt("./src/tokenizers.js"),n=Nt("./src/configs.js"),o=Nt("./src/utils/audio.js"),i=Nt("./src/utils/image.js"),a=Nt("./src/utils/video.js"),l=Nt("./src/utils/tensor.js"),c=Nt("./src/utils/maths.js"),p=Nt("./src/base/feature_extraction_utils.js"),d=Nt("./src/models/feature_extractors.js"),u=Nt("./src/models/auto/feature_extraction_auto.js"),f=Nt("./src/base/image_processors_utils.js"),_=Nt("./src/models/image_processors.js"),y=Nt("./src/models/auto/image_processing_auto.js"),k=Nt("./src/base/processing_utils.js"),w=Nt("./src/models/processors.js"),v=Nt("./src/models/auto/processing_auto.js"),I=Nt("./src/generation/streamers.js"),T=Nt("./src/generation/stopping_criteria.js"),b=Nt("./src/generation/logits_process.js")})();m.ASTFeatureExtractor;m.ASTForAudioClassification;m.ASTModel;m.ASTPreTrainedModel;m.AlbertForMaskedLM;m.AlbertForQuestionAnswering;m.AlbertForSequenceClassification;m.AlbertModel;m.AlbertPreTrainedModel;m.AlbertTokenizer;m.ArceeForCausalLM;m.ArceeModel;m.ArceePreTrainedModel;m.AudioClassificationPipeline;m.AutoConfig;m.AutoFeatureExtractor;m.AutoImageProcessor;m.AutoModel;m.AutoModelForAudioClassification;m.AutoModelForAudioFrameClassification;m.AutoModelForAudioTextToText;m.AutoModelForCTC;m.AutoModelForCausalLM;m.AutoModelForDepthEstimation;m.AutoModelForDocumentQuestionAnswering;m.AutoModelForImageClassification;m.AutoModelForImageFeatureExtraction;m.AutoModelForImageMatting;m.AutoModelForImageSegmentation;m.AutoModelForImageTextToText;m.AutoModelForImageToImage;m.AutoModelForMaskGeneration;m.AutoModelForMaskedLM;m.AutoModelForNormalEstimation;m.AutoModelForObjectDetection;m.AutoModelForPoseEstimation;m.AutoModelForQuestionAnswering;m.AutoModelForSemanticSegmentation;m.AutoModelForSeq2SeqLM;m.AutoModelForSequenceClassification;m.AutoModelForSpeechSeq2Seq;m.AutoModelForTextToSpectrogram;m.AutoModelForTextToWaveform;m.AutoModelForTokenClassification;m.AutoModelForUniversalSegmentation;m.AutoModelForVision2Seq;m.AutoModelForXVector;m.AutoModelForZeroShotObjectDetection;m.AutoProcessor;m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline;m.BackgroundRemovalPipeline;m.BartForConditionalGeneration;m.BartForSequenceClassification;m.BartModel;m.BartPretrainedModel;m.BartTokenizer;m.BaseModelOutput;m.BaseStreamer;m.BeitFeatureExtractor;m.BeitForImageClassification;m.BeitModel;m.BeitPreTrainedModel;m.BertForMaskedLM;m.BertForQuestionAnswering;m.BertForSequenceClassification;m.BertForTokenClassification;m.BertModel;m.BertPreTrainedModel;m.BertTokenizer;m.BitImageProcessor;m.BlenderbotForConditionalGeneration;m.BlenderbotModel;m.BlenderbotPreTrainedModel;m.BlenderbotSmallForConditionalGeneration;m.BlenderbotSmallModel;m.BlenderbotSmallPreTrainedModel;m.BlenderbotSmallTokenizer;m.BlenderbotTokenizer;m.BloomForCausalLM;m.BloomModel;m.BloomPreTrainedModel;m.BloomTokenizer;m.CLIPFeatureExtractor;m.CLIPImageProcessor;m.CLIPModel;m.CLIPPreTrainedModel;m.CLIPSegForImageSegmentation;m.CLIPSegModel;m.CLIPSegPreTrainedModel;m.CLIPTextModel;m.CLIPTextModelWithProjection;m.CLIPTokenizer;m.CLIPVisionModel;m.CLIPVisionModelWithProjection;m.CamembertForMaskedLM;m.CamembertForQuestionAnswering;m.CamembertForSequenceClassification;m.CamembertForTokenClassification;m.CamembertModel;m.CamembertPreTrainedModel;m.CamembertTokenizer;m.CausalLMOutput;m.CausalLMOutputWithPast;m.ChineseCLIPFeatureExtractor;m.ChineseCLIPModel;m.ChineseCLIPPreTrainedModel;m.ClapAudioModelWithProjection;m.ClapFeatureExtractor;m.ClapModel;m.ClapPreTrainedModel;m.ClapTextModelWithProjection;m.ClassifierFreeGuidanceLogitsProcessor;m.CodeGenForCausalLM;m.CodeGenModel;m.CodeGenPreTrainedModel;m.CodeGenTokenizer;m.CodeLlamaTokenizer;m.CohereForCausalLM;m.CohereModel;m.CoherePreTrainedModel;m.CohereTokenizer;m.ConvBertForMaskedLM;m.ConvBertForQuestionAnswering;m.ConvBertForSequenceClassification;m.ConvBertForTokenClassification;m.ConvBertModel;m.ConvBertPreTrainedModel;m.ConvBertTokenizer;m.ConvNextFeatureExtractor;m.ConvNextForImageClassification;m.ConvNextImageProcessor;m.ConvNextModel;m.ConvNextPreTrainedModel;m.ConvNextV2ForImageClassification;m.ConvNextV2Model;m.ConvNextV2PreTrainedModel;m.DFineForObjectDetection;m.DFineModel;m.DFinePreTrainedModel;m.DINOv3ConvNextModel;m.DINOv3ConvNextPreTrainedModel;m.DINOv3ViTImageProcessor;m.DINOv3ViTModel;m.DINOv3ViTPreTrainedModel;m.DPTFeatureExtractor;m.DPTForDepthEstimation;m.DPTImageProcessor;m.DPTModel;m.DPTPreTrainedModel;m.DacDecoderModel;m.DacDecoderOutput;m.DacEncoderModel;m.DacEncoderOutput;m.DacFeatureExtractor;m.DacModel;m.DacPreTrainedModel;m.DataTypeMap;m.DebertaForMaskedLM;m.DebertaForQuestionAnswering;m.DebertaForSequenceClassification;m.DebertaForTokenClassification;m.DebertaModel;m.DebertaPreTrainedModel;m.DebertaTokenizer;m.DebertaV2ForMaskedLM;m.DebertaV2ForQuestionAnswering;m.DebertaV2ForSequenceClassification;m.DebertaV2ForTokenClassification;m.DebertaV2Model;m.DebertaV2PreTrainedModel;m.DebertaV2Tokenizer;m.DecisionTransformerModel;m.DecisionTransformerPreTrainedModel;m.DeiTFeatureExtractor;m.DeiTForImageClassification;m.DeiTImageProcessor;m.DeiTModel;m.DeiTPreTrainedModel;m.DepthAnythingForDepthEstimation;m.DepthAnythingPreTrainedModel;m.DepthEstimationPipeline;m.DepthProForDepthEstimation;m.DepthProPreTrainedModel;m.DetrFeatureExtractor;m.DetrForObjectDetection;m.DetrForSegmentation;m.DetrImageProcessor;m.DetrModel;m.DetrObjectDetectionOutput;m.DetrPreTrainedModel;m.DetrSegmentationOutput;m.Dinov2ForImageClassification;m.Dinov2Model;m.Dinov2PreTrainedModel;m.Dinov2WithRegistersForImageClassification;m.Dinov2WithRegistersModel;m.Dinov2WithRegistersPreTrainedModel;m.DistilBertForMaskedLM;m.DistilBertForQuestionAnswering;m.DistilBertForSequenceClassification;m.DistilBertForTokenClassification;m.DistilBertModel;m.DistilBertPreTrainedModel;m.DistilBertTokenizer;m.DocumentQuestionAnsweringPipeline;m.DonutFeatureExtractor;m.DonutImageProcessor;m.DonutSwinModel;m.DonutSwinPreTrainedModel;m.EdgeTamModel;m.EfficientNetForImageClassification;m.EfficientNetImageProcessor;m.EfficientNetModel;m.EfficientNetPreTrainedModel;m.ElectraForMaskedLM;m.ElectraForQuestionAnswering;m.ElectraForSequenceClassification;m.ElectraForTokenClassification;m.ElectraModel;m.ElectraPreTrainedModel;m.ElectraTokenizer;m.EncodecFeatureExtractor;m.EosTokenCriteria;m.Ernie4_5ForCausalLM;m.Ernie4_5Model;m.Ernie4_5PreTrainedModel;m.EsmForMaskedLM;m.EsmForSequenceClassification;m.EsmForTokenClassification;m.EsmModel;m.EsmPreTrainedModel;m.EsmTokenizer;m.ExaoneForCausalLM;m.ExaoneModel;m.ExaonePreTrainedModel;m.FFT;m.FalconForCausalLM;m.FalconModel;m.FalconPreTrainedModel;m.FalconTokenizer;m.FastViTForImageClassification;m.FastViTModel;m.FastViTPreTrainedModel;m.FeatureExtractionPipeline;m.FeatureExtractor;m.FillMaskPipeline;m.Florence2ForConditionalGeneration;m.Florence2PreTrainedModel;m.Florence2Processor;m.ForcedBOSTokenLogitsProcessor;m.ForcedEOSTokenLogitsProcessor;m.GLPNFeatureExtractor;m.GLPNForDepthEstimation;m.GLPNModel;m.GLPNPreTrainedModel;m.GPT2LMHeadModel;m.GPT2Model;m.GPT2PreTrainedModel;m.GPT2Tokenizer;m.GPTBigCodeForCausalLM;m.GPTBigCodeModel;m.GPTBigCodePreTrainedModel;m.GPTJForCausalLM;m.GPTJModel;m.GPTJPreTrainedModel;m.GPTNeoForCausalLM;m.GPTNeoModel;m.GPTNeoPreTrainedModel;m.GPTNeoXForCausalLM;m.GPTNeoXModel;m.GPTNeoXPreTrainedModel;m.GPTNeoXTokenizer;m.Gemma2ForCausalLM;m.Gemma2Model;m.Gemma2PreTrainedModel;m.Gemma3ForCausalLM;m.Gemma3Model;m.Gemma3PreTrainedModel;m.Gemma3nAudioFeatureExtractor;m.Gemma3nForConditionalGeneration;m.Gemma3nPreTrainedModel;m.Gemma3nProcessor;m.GemmaForCausalLM;m.GemmaModel;m.GemmaPreTrainedModel;m.GemmaTokenizer;m.GlmForCausalLM;m.GlmModel;m.GlmPreTrainedModel;m.GraniteForCausalLM;m.GraniteModel;m.GraniteMoeHybridForCausalLM;m.GraniteMoeHybridModel;m.GraniteMoeHybridPreTrainedModel;m.GranitePreTrainedModel;m.Grok1Tokenizer;m.GroundingDinoForObjectDetection;m.GroundingDinoImageProcessor;m.GroundingDinoPreTrainedModel;m.GroundingDinoProcessor;m.GroupViTModel;m.GroupViTPreTrainedModel;m.HeliumForCausalLM;m.HeliumModel;m.HeliumPreTrainedModel;m.HerbertTokenizer;m.HieraForImageClassification;m.HieraModel;m.HieraPreTrainedModel;m.HubertForCTC;m.HubertForSequenceClassification;m.HubertModel;m.HubertPreTrainedModel;m.IJepaForImageClassification;m.IJepaModel;m.IJepaPreTrainedModel;m.Idefics3ForConditionalGeneration;m.Idefics3ImageProcessor;m.Idefics3PreTrainedModel;m.Idefics3Processor;m.ImageClassificationPipeline;m.ImageFeatureExtractionPipeline;m.ImageFeatureExtractor;m.ImageMattingOutput;m.ImageProcessor;m.ImageSegmentationPipeline;m.ImageToImagePipeline;m.ImageToTextPipeline;m.InterruptableStoppingCriteria;m.JAISLMHeadModel;m.JAISModel;m.JAISPreTrainedModel;m.JinaCLIPImageProcessor;m.JinaCLIPModel;m.JinaCLIPPreTrainedModel;m.JinaCLIPProcessor;m.JinaCLIPTextModel;m.JinaCLIPVisionModel;m.Lfm2ForCausalLM;m.Lfm2Model;m.Lfm2PreTrainedModel;m.LiteWhisperForConditionalGeneration;m.Llama4ForCausalLM;m.Llama4PreTrainedModel;m.LlamaForCausalLM;m.LlamaModel;m.LlamaPreTrainedModel;m.LlamaTokenizer;m.LlavaForConditionalGeneration;m.LlavaOnevisionForConditionalGeneration;m.LlavaOnevisionImageProcessor;m.LlavaPreTrainedModel;m.LlavaProcessor;m.LlavaQwen2ForCausalLM;m.LogitsProcessor;m.LogitsProcessorList;m.LogitsWarper;m.LongT5ForConditionalGeneration;m.LongT5Model;m.LongT5PreTrainedModel;m.M2M100ForConditionalGeneration;m.M2M100Model;m.M2M100PreTrainedModel;m.M2M100Tokenizer;m.MBart50Tokenizer;m.MBartForCausalLM;m.MBartForConditionalGeneration;m.MBartForSequenceClassification;m.MBartModel;m.MBartPreTrainedModel;m.MBartTokenizer;m.MPNetForMaskedLM;m.MPNetForQuestionAnswering;m.MPNetForSequenceClassification;m.MPNetForTokenClassification;m.MPNetModel;m.MPNetPreTrainedModel;m.MPNetTokenizer;m.MT5ForConditionalGeneration;m.MT5Model;m.MT5PreTrainedModel;m.MarianMTModel;m.MarianModel;m.MarianPreTrainedModel;m.MarianTokenizer;m.Mask2FormerImageProcessor;m.MaskFormerFeatureExtractor;m.MaskFormerForInstanceSegmentation;m.MaskFormerImageProcessor;m.MaskFormerModel;m.MaskFormerPreTrainedModel;m.MaskedLMOutput;m.MaxLengthCriteria;m.Metric3DForDepthEstimation;m.Metric3DPreTrainedModel;m.Metric3Dv2ForDepthEstimation;m.Metric3Dv2PreTrainedModel;m.MgpstrForSceneTextRecognition;m.MgpstrModelOutput;m.MgpstrPreTrainedModel;m.MgpstrProcessor;m.MgpstrTokenizer;m.MimiDecoderModel;m.MimiDecoderOutput;m.MimiEncoderModel;m.MimiEncoderOutput;m.MimiModel;m.MimiPreTrainedModel;m.MinLengthLogitsProcessor;m.MinNewTokensLengthLogitsProcessor;m.Ministral3ForCausalLM;m.Ministral3Model;m.Ministral3PreTrainedModel;m.MinistralForCausalLM;m.MinistralModel;m.MinistralPreTrainedModel;m.Mistral3ForConditionalGeneration;m.MistralForCausalLM;m.MistralModel;m.MistralPreTrainedModel;m.MobileBertForMaskedLM;m.MobileBertForQuestionAnswering;m.MobileBertForSequenceClassification;m.MobileBertModel;m.MobileBertPreTrainedModel;m.MobileBertTokenizer;m.MobileLLMForCausalLM;m.MobileLLMModel;m.MobileLLMPreTrainedModel;m.MobileNetV1FeatureExtractor;m.MobileNetV1ForImageClassification;m.MobileNetV1ForSemanticSegmentation;m.MobileNetV1ImageProcessor;m.MobileNetV1Model;m.MobileNetV1PreTrainedModel;m.MobileNetV2FeatureExtractor;m.MobileNetV2ForImageClassification;m.MobileNetV2ForSemanticSegmentation;m.MobileNetV2ImageProcessor;m.MobileNetV2Model;m.MobileNetV2PreTrainedModel;m.MobileNetV3FeatureExtractor;m.MobileNetV3ForImageClassification;m.MobileNetV3ForSemanticSegmentation;m.MobileNetV3ImageProcessor;m.MobileNetV3Model;m.MobileNetV3PreTrainedModel;m.MobileNetV4FeatureExtractor;m.MobileNetV4ForImageClassification;m.MobileNetV4ForSemanticSegmentation;m.MobileNetV4ImageProcessor;m.MobileNetV4Model;m.MobileNetV4PreTrainedModel;m.MobileViTFeatureExtractor;m.MobileViTForImageClassification;m.MobileViTImageProcessor;m.MobileViTModel;m.MobileViTPreTrainedModel;m.MobileViTV2ForImageClassification;m.MobileViTV2Model;m.MobileViTV2PreTrainedModel;m.ModelOutput;m.ModernBertDecoderForCausalLM;m.ModernBertDecoderModel;m.ModernBertDecoderPreTrainedModel;m.ModernBertForMaskedLM;m.ModernBertForSequenceClassification;m.ModernBertForTokenClassification;m.ModernBertModel;m.ModernBertPreTrainedModel;m.Moondream1ForConditionalGeneration;m.MoonshineFeatureExtractor;m.MoonshineForConditionalGeneration;m.MoonshineModel;m.MoonshinePreTrainedModel;m.MoonshineProcessor;m.MptForCausalLM;m.MptModel;m.MptPreTrainedModel;m.MultiModalityCausalLM;m.MultiModalityPreTrainedModel;m.MusicgenForCausalLM;m.MusicgenForConditionalGeneration;m.MusicgenModel;m.MusicgenPreTrainedModel;m.NanoChatForCausalLM;m.NanoChatModel;m.NanoChatPreTrainedModel;m.NeoBertForMaskedLM;m.NeoBertForQuestionAnswering;m.NeoBertForSequenceClassification;m.NeoBertForTokenClassification;m.NeoBertModel;m.NeoBertPreTrainedModel;m.NllbTokenizer;m.NoBadWordsLogitsProcessor;m.NoRepeatNGramLogitsProcessor;m.NomicBertModel;m.NomicBertPreTrainedModel;m.NougatImageProcessor;m.NougatTokenizer;m.OPTForCausalLM;m.OPTModel;m.OPTPreTrainedModel;m.ObjectDetectionPipeline;m.Olmo2ForCausalLM;m.Olmo2Model;m.Olmo2PreTrainedModel;m.OlmoForCausalLM;m.OlmoModel;m.OlmoPreTrainedModel;m.OpenELMForCausalLM;m.OpenELMModel;m.OpenELMPreTrainedModel;m.OwlViTFeatureExtractor;m.OwlViTForObjectDetection;m.OwlViTImageProcessor;m.OwlViTModel;m.OwlViTPreTrainedModel;m.OwlViTProcessor;m.Owlv2ForObjectDetection;m.Owlv2ImageProcessor;m.Owlv2Model;m.Owlv2PreTrainedModel;m.PaliGemmaForConditionalGeneration;m.PaliGemmaPreTrainedModel;m.PaliGemmaProcessor;m.ParakeetFeatureExtractor;m.ParakeetForCTC;m.ParakeetPreTrainedModel;m.PatchTSMixerForPrediction;m.PatchTSMixerModel;m.PatchTSMixerPreTrainedModel;m.PatchTSTForPrediction;m.PatchTSTModel;m.PatchTSTPreTrainedModel;m.Phi3ForCausalLM;m.Phi3Model;m.Phi3PreTrainedModel;m.Phi3VForCausalLM;m.Phi3VImageProcessor;m.Phi3VPreTrainedModel;m.Phi3VProcessor;m.PhiForCausalLM;m.PhiModel;m.PhiPreTrainedModel;m.Pipeline;m.PixtralImageProcessor;m.PixtralProcessor;m.PreTrainedModel;m.PreTrainedTokenizer;m.PretrainedConfig;m.PretrainedMixin;m.Processor;m.PvtForImageClassification;m.PvtImageProcessor;m.PvtModel;m.PvtPreTrainedModel;m.PyAnnoteFeatureExtractor;m.PyAnnoteForAudioFrameClassification;m.PyAnnoteModel;m.PyAnnotePreTrainedModel;m.PyAnnoteProcessor;m.QuestionAnsweringModelOutput;m.QuestionAnsweringPipeline;m.Qwen2ForCausalLM;m.Qwen2Model;m.Qwen2PreTrainedModel;m.Qwen2Tokenizer;m.Qwen2VLForConditionalGeneration;m.Qwen2VLImageProcessor;m.Qwen2VLPreTrainedModel;m.Qwen2VLProcessor;m.Qwen3ForCausalLM;m.Qwen3Model;m.Qwen3PreTrainedModel;m.RFDetrForObjectDetection;m.RFDetrModel;m.RFDetrObjectDetectionOutput;m.RFDetrPreTrainedModel;m.RTDetrForObjectDetection;m.RTDetrImageProcessor;m.RTDetrModel;m.RTDetrObjectDetectionOutput;m.RTDetrPreTrainedModel;m.RTDetrV2ForObjectDetection;m.RTDetrV2Model;m.RTDetrV2ObjectDetectionOutput;m.RTDetrV2PreTrainedModel;m.RawAudio;m.RawImage;m.RawVideo;m.RawVideoFrame;m.RepetitionPenaltyLogitsProcessor;m.ResNetForImageClassification;m.ResNetModel;m.ResNetPreTrainedModel;m.RoFormerForMaskedLM;m.RoFormerForQuestionAnswering;m.RoFormerForSequenceClassification;m.RoFormerForTokenClassification;m.RoFormerModel;m.RoFormerPreTrainedModel;m.RoFormerTokenizer;m.RobertaForMaskedLM;m.RobertaForQuestionAnswering;m.RobertaForSequenceClassification;m.RobertaForTokenClassification;m.RobertaModel;m.RobertaPreTrainedModel;m.RobertaTokenizer;m.Sam2ImageProcessor;m.Sam2ImageSegmentationOutput;m.Sam2Model;m.Sam2PreTrainedModel;m.Sam2Processor;m.Sam2VideoProcessor;m.Sam3ImageProcessor;m.Sam3TrackerModel;m.SamImageProcessor;m.SamImageSegmentationOutput;m.SamModel;m.SamPreTrainedModel;m.SamProcessor;m.SapiensForDepthEstimation;m.SapiensForNormalEstimation;m.SapiensForSemanticSegmentation;m.SapiensPreTrainedModel;m.SeamlessM4TFeatureExtractor;m.SegformerFeatureExtractor;m.SegformerForImageClassification;m.SegformerForSemanticSegmentation;m.SegformerImageProcessor;m.SegformerModel;m.SegformerPreTrainedModel;m.Seq2SeqLMOutput;m.SequenceClassifierOutput;m.SiglipImageProcessor;m.SiglipModel;m.SiglipPreTrainedModel;m.SiglipTextModel;m.SiglipTokenizer;m.SiglipVisionModel;m.SmolLM3ForCausalLM;m.SmolLM3Model;m.SmolLM3PreTrainedModel;m.SmolVLMForConditionalGeneration;m.SmolVLMImageProcessor;m.SmolVLMProcessor;m.SnacDecoderModel;m.SnacEncoderModel;m.SnacFeatureExtractor;m.SnacModel;m.SnacPreTrainedModel;m.SpeechT5FeatureExtractor;m.SpeechT5ForSpeechToText;m.SpeechT5ForTextToSpeech;m.SpeechT5HifiGan;m.SpeechT5Model;m.SpeechT5PreTrainedModel;m.SpeechT5Processor;m.SpeechT5Tokenizer;m.SqueezeBertForMaskedLM;m.SqueezeBertForQuestionAnswering;m.SqueezeBertForSequenceClassification;m.SqueezeBertModel;m.SqueezeBertPreTrainedModel;m.SqueezeBertTokenizer;m.StableLmForCausalLM;m.StableLmModel;m.StableLmPreTrainedModel;m.Starcoder2ForCausalLM;m.Starcoder2Model;m.Starcoder2PreTrainedModel;m.StoppingCriteria;m.StoppingCriteriaList;m.StyleTextToSpeech2Model;m.StyleTextToSpeech2PreTrainedModel;m.SummarizationPipeline;m.SupertonicForConditionalGeneration;m.SupertonicPreTrainedModel;m.SuppressTokensAtBeginLogitsProcessor;m.Swin2SRForImageSuperResolution;m.Swin2SRImageProcessor;m.Swin2SRModel;m.Swin2SRPreTrainedModel;m.SwinForImageClassification;m.SwinForSemanticSegmentation;m.SwinModel;m.SwinPreTrainedModel;m.T5ForConditionalGeneration;m.T5Model;m.T5PreTrainedModel;m.T5Tokenizer;m.TableTransformerForObjectDetection;m.TableTransformerModel;m.TableTransformerObjectDetectionOutput;m.TableTransformerPreTrainedModel;m.TemperatureLogitsWarper;m.Tensor;m.Text2TextGenerationPipeline;m.TextClassificationPipeline;m.TextGenerationPipeline;m.TextStreamer;m.TextToAudioPipeline;m.TokenClassificationPipeline;m.TokenClassifierOutput;m.TokenizerModel;m.TopKLogitsWarper;m.TopPLogitsWarper;m.TrOCRForCausalLM;m.TrOCRPreTrainedModel;m.TranslationPipeline;m.UltravoxModel;m.UltravoxPreTrainedModel;m.UltravoxProcessor;m.UniSpeechForCTC;m.UniSpeechForSequenceClassification;m.UniSpeechModel;m.UniSpeechPreTrainedModel;m.UniSpeechSatForAudioFrameClassification;m.UniSpeechSatForCTC;m.UniSpeechSatForSequenceClassification;m.UniSpeechSatModel;m.UniSpeechSatPreTrainedModel;m.VLChatProcessor;m.VLMImageProcessor;m.VaultGemmaForCausalLM;m.VaultGemmaModel;m.VaultGemmaPreTrainedModel;m.ViTFeatureExtractor;m.ViTForImageClassification;m.ViTImageProcessor;m.ViTMAEModel;m.ViTMAEPreTrainedModel;m.ViTMSNForImageClassification;m.ViTMSNModel;m.ViTMSNPreTrainedModel;m.ViTModel;m.ViTPreTrainedModel;m.VisionEncoderDecoderModel;m.VitMatteForImageMatting;m.VitMatteImageProcessor;m.VitMattePreTrainedModel;m.VitPoseForPoseEstimation;m.VitPoseImageProcessor;m.VitPosePreTrainedModel;m.VitsModel;m.VitsModelOutput;m.VitsPreTrainedModel;m.VitsTokenizer;m.VoxtralForConditionalGeneration;m.VoxtralProcessor;m.Wav2Vec2BertForCTC;m.Wav2Vec2BertForSequenceClassification;m.Wav2Vec2BertModel;m.Wav2Vec2BertPreTrainedModel;m.Wav2Vec2CTCTokenizer;m.Wav2Vec2FeatureExtractor;m.Wav2Vec2ForAudioFrameClassification;m.Wav2Vec2ForCTC;m.Wav2Vec2ForSequenceClassification;m.Wav2Vec2Model;m.Wav2Vec2PreTrainedModel;m.Wav2Vec2Processor;m.Wav2Vec2ProcessorWithLM;m.WavLMForAudioFrameClassification;m.WavLMForCTC;m.WavLMForSequenceClassification;m.WavLMForXVector;m.WavLMModel;m.WavLMPreTrainedModel;m.WeSpeakerFeatureExtractor;m.WeSpeakerResNetModel;m.WeSpeakerResNetPreTrainedModel;m.WhisperFeatureExtractor;m.WhisperForConditionalGeneration;m.WhisperModel;m.WhisperPreTrainedModel;m.WhisperProcessor;m.WhisperTextStreamer;m.WhisperTimeStampLogitsProcessor;m.WhisperTokenizer;m.XLMForQuestionAnswering;m.XLMForSequenceClassification;m.XLMForTokenClassification;m.XLMModel;m.XLMPreTrainedModel;m.XLMRobertaForMaskedLM;m.XLMRobertaForQuestionAnswering;m.XLMRobertaForSequenceClassification;m.XLMRobertaForTokenClassification;m.XLMRobertaModel;m.XLMRobertaPreTrainedModel;m.XLMRobertaTokenizer;m.XLMTokenizer;m.XLMWithLMHeadModel;m.XVectorOutput;m.YolosFeatureExtractor;m.YolosForObjectDetection;m.YolosImageProcessor;m.YolosModel;m.YolosObjectDetectionOutput;m.YolosPreTrainedModel;m.ZeroShotAudioClassificationPipeline;m.ZeroShotClassificationPipeline;m.ZeroShotImageClassificationPipeline;m.ZeroShotObjectDetectionPipeline;m.bankers_round;m.cat;m.cos_sim;m.dot;m.dynamic_time_warping;var bv=m.env;m.full;m.full_like;m.getCacheShapes;m.hamming;m.hanning;m.interpolate;m.interpolate_4d;m.interpolate_data;m.is_chinese_char;m.layer_norm;m.load_image;m.load_video;m.log_softmax;m.magnitude;m.matmul;m.max;m.mean;m.mean_pooling;m.medianFilter;m.mel_filter_bank;m.min;m.ones;m.ones_like;m.permute;m.permute_data;var l1=m.pipeline;m.quantize_embeddings;m.rand;m.randn;m.read_audio;m.rfft;m.round;m.slice;m.softmax;m.spectrogram;m.stack;m.std_mean;m.topk;m.window_function;m.zeros;m.zeros_like;const yv=[{id:"whisper-tiny-multilingual-wasm",label:"Whisper Tiny (multilingual)",modelId:"onnx-community/whisper-tiny",revision:"ff4177021cc41f7db950912b73ea4fdf7d01d8e7",multilingual:!0,approximateDownloadBytes:77e6,devices:["wasm","webgpu"],dtypeByDevice:{wasm:"q8",webgpu:"fp32"},chunkLengthSeconds:30,strideLengthSeconds:5,maxDurationSeconds:10800}];yv[0].id;function Mi(e){return yv.find(r=>r.id===e)}bv.allowLocalModels=!1;bv.useBrowserCache=!0;const c1="0.1.0-prototype",u1="0d8c0a8b93e2",vv="3.x";let Vr=null,oo=null,ea=new Set;function cs(e){self.postMessage(e)}function Gs(e,r){ea.has(e)||cs({protocol:1,type:"PROGRESS",requestId:e,progress:r})}function Uu(e,r){if(ea.has(e)){cs({protocol:1,type:"CANCELLED",requestId:e});return}cs({protocol:1,type:"ERROR",requestId:e,error:r})}function wi(e={}){return{appVersion:c1,buildId:u1,transformersVersion:vv,cacheState:"unknown",...e}}function ta(e){return ea.has(e)}async function d1(e,r,t){const s=Mi(e);if(!s)throw xs("PROFILE_UNKNOWN","prepare",!1);const n=performance.now();let o="wasm",i;Gs(t,{phase:"manifest",status:"completed",ratio:1}),Gs(t,{phase:"runtime-init",status:"started"});const a=typeof navigator<"u"&&"gpu"in navigator,l=r==="webgpu"||r==="auto"&&a;if(r==="webgpu"&&!a)throw xs("RUNTIME_UNSUPPORTED","prepare",!0,!0);const c=async u=>{const f=s.dtypeByDevice[u]??(u==="webgpu"?"fp32":"q8");return l1("automatic-speech-recognition",s.modelId,{revision:s.revision,device:u,dtype:f,progress_callback:_=>{ta(t)||(_.status==="progress"||_.status==="download")&&Gs(t,{phase:"download",status:"running",fileId:_.file,loadedBytes:_.loaded,totalBytes:_.total,ratio:typeof _.progress=="number"?_.progress/100:_.total?(_.loaded??0)/_.total:void 0})}})};let p;if(l)try{Gs(t,{phase:"model-init",status:"started"}),p=await c("webgpu"),o="webgpu"}catch{i="WEBGPU_INIT_FAILED",Gs(t,{phase:"runtime-init",status:"started"}),p=await c("wasm"),o="wasm"}else Gs(t,{phase:"model-init",status:"started"}),p=await c("wasm"),o="wasm";if(ta(t))throw xs("CANCELLED","prepare",!0);return Gs(t,{phase:"warmup",status:"completed",ratio:1}),{fingerprint:[s.modelId,s.revision,o,s.dtypeByDevice[o]??"default",vv].join("|"),pipeline:p,effectiveRuntime:o,profileId:s.id,modelRevision:s.revision,preparationMs:Math.round(performance.now()-n),fallbackReasonCode:i}}async function xv(e,r,t){const s=Mi(e);if(!s)throw xs("PROFILE_UNKNOWN","prepare",!1);const n=r==="wasm"?"wasm":r==="webgpu"?"webgpu":Vr?.effectiveRuntime??"auto",o=`${s.modelId}|${s.revision}|`;return Vr&&Vr.profileId===e&&Vr.fingerprint.startsWith(o)&&(r==="auto"||Vr.effectiveRuntime===n||r==="webgpu"&&Vr.effectiveRuntime==="wasm"&&Vr.fallbackReasonCode)?Vr:(oo||(oo=d1(e,r,t).then(i=>(Vr=i,oo=null,i)).catch(i=>{throw oo=null,Vr=null,i})),oo)}function p1(e,r){const t=[],s=e??{},n=(s.text??"").trim(),o=[];if(Array.isArray(s.chunks))for(const i of s.chunks){const a=i.timestamp?.[0],l=i.timestamp?.[1];typeof a!="number"||typeof l!="number"||!Number.isFinite(a)||!Number.isFinite(l)||li.text).join(" ").trim(),segments:o,durationSeconds:r,warnings:t}}function xs(e,r,t,s){return{code:e,phase:r,recoverable:t,fallbackAvailable:s}}function m1(e){if(!(e instanceof Float32Array)||e.length===0)throw xs("AUDIO_INVALID","infer",!0);for(let r=0;r{const r=e.data;if(!r||r.protocol!==1){cs({protocol:1,type:"ERROR",requestId:r?.requestId??"unknown",error:xs("PROTOCOL_UNSUPPORTED","prepare",!1)});return}switch(r.type){case"PREPARE":h1(r);break;case"TRANSCRIBE":_1(r);break;case"CANCEL":ea.add(r.targetRequestId),cs({protocol:1,type:"CANCELLED",requestId:r.requestId});break;case"DISPOSE":Vr=null,oo=null,ea=new Set,cs({protocol:1,type:"DIAGNOSTICS",requestId:r.requestId,diagnostics:wi()});break;case"GET_DIAGNOSTICS":cs({protocol:1,type:"DIAGNOSTICS",requestId:r.requestId,diagnostics:wi({modelProfileId:Vr?.profileId,modelRevision:Vr?.modelRevision,effectiveRuntime:Vr?.effectiveRuntime,preparationMs:Vr?.preparationMs,fallbackReasonCode:Vr?.fallbackReasonCode})});break;default:Uu(r.requestId,xs("INTERNAL","prepare",!1))}}; +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const U=[];for(const ee of $){const se=ee.charCodeAt(0);se===0||se===65533||this._is_control(ee)||(/^\s$/.test(ee)?U.push(" "):U.push(ee))}return U.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class Q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new z($);case"Sequence":return new Rr($);case"Whitespace":return new qs($);case"WhitespaceSplit":return new Qs($);case"Metaspace":return new gr($);case"ByteLevel":return new de($);case"Split":return new be($);case"Punctuation":return new ve($);case"Digits":return new xe($);case"Replace":return new Xs($);case"FixedLength":return new or($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,U){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,U){return(Array.isArray($)?$.map(ee=>this.pre_tokenize_text(ee,U)):this.pre_tokenize_text($,U)).flat()}_call($,U){return this.pre_tokenize($,U)}}class z extends Q{constructor($){super(),this.pattern=new RegExp(`[^\\s${E}]+|[${E}]`,"gu")}pre_tokenize_text($,U){return $.trim().match(this.pattern)||[]}}class de extends Q{constructor($){super(),this.config=$,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text($,U){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(se=>Array.from(this.text_encoder.encode(se),Me=>this.byte_encoder[Me]).join(""))}}class be extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text($,U){return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?$.split(this.pattern).filter(ee=>ee):u($,this.pattern)}}class ve extends Q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${E}]+|[${E}]+`,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class xe extends Q{constructor($){super(),this.config=$;const U=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(U,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class Ce extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new fe($);case"ByteLevel":return new Ee($);case"RobertaProcessing":return new De($);case"BertProcessing":return new ge($);case"Sequence":return new We($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...U){throw Error("post_process should be implemented in subclass.")}_call($,...U){return this.post_process($,...U)}}class ge extends Ce{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,U=null,{add_special_tokens:ee=!0}={}){ee&&($=(0,n.mergeArrays)([this.cls],$,[this.sep]));let se=new Array($.length).fill(0);if(U!==null){const Me=ee&&this instanceof De?[this.sep]:[],$e=ee?[this.sep]:[];$=(0,n.mergeArrays)($,Me,U,$e),se=(0,n.mergeArrays)(se,new Array(U.length+Me.length+$e.length).fill(1))}return{tokens:$,token_type_ids:se}}}class De extends ge{}class fe extends Ce{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,U=null,{add_special_tokens:ee=!0}={}){const se=U===null?this.single:this.pair;let Me=[],$e=[];for(const Xe of se)"SpecialToken"in Xe?ee&&(Me.push(Xe.SpecialToken.id),$e.push(Xe.SpecialToken.type_id)):"Sequence"in Xe&&(Xe.Sequence.id==="A"?(Me=(0,n.mergeArrays)(Me,$),$e=(0,n.mergeArrays)($e,new Array($.length).fill(Xe.Sequence.type_id))):Xe.Sequence.id==="B"&&(Me=(0,n.mergeArrays)(Me,U),$e=(0,n.mergeArrays)($e,new Array(U.length).fill(Xe.Sequence.type_id))));return{tokens:Me,token_type_ids:$e}}}class Ee extends Ce{post_process($,U=null){return U&&($=(0,n.mergeArrays)($,U)),{tokens:$}}}class We extends Ce{constructor($){super($),this.processors=$.processors.map(U=>Ce.fromConfig(U))}post_process($,U=null,ee={}){let se;for(const Me of this.processors)if(Me instanceof Ee)$=Me.post_process($).tokens,U&&(U=Me.post_process(U).tokens);else{const $e=Me.post_process($,U,ee);$=$e.tokens,se=$e.token_type_ids}return{tokens:$,token_type_ids:se}}}class Fe extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new Ne($);case"Metaspace":return new Or($);case"ByteLevel":return new Oe($);case"Replace":return new tt($);case"ByteFallback":return new Re($);case"Fuse":return new rt($);case"Strip":return new Ze($);case"Sequence":return new ht($);case"CTC":return new ot($);case"BPEDecoder":return new Rt($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class tt extends Fe{decode_chain($){const U=f(this.config.pattern);return U===null?$:$.map(ee=>ee.replaceAll(U,this.config.content))}}class Re extends Fe{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const U=[];let ee=[];for(const se of $){let Me=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const $e=parseInt(se.slice(3,5),16);isNaN($e)||(Me=$e)}if(Me!==null)ee.push(Me);else{if(ee.length>0){const $e=this.text_decoder.decode(Uint8Array.from(ee));U.push($e),ee=[]}U.push(se)}}if(ee.length>0){const se=this.text_decoder.decode(Uint8Array.from(ee));U.push(se),ee=[]}return U}}class rt extends Fe{decode_chain($){return[$.join("")]}}class Ze extends Fe{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(U=>{let ee=0;for(let Me=0;Me(ee!==0&&(U.startsWith(this.config.prefix)?U=U.replace(this.config.prefix,""):U=" "+U),this.cleanup&&(U=k(U)),U))}}class Oe extends Fe{constructor($){super($),this.byte_decoder=X,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string($){const U=$.join(""),ee=new Uint8Array([...U].map(Me=>this.byte_decoder[Me]));return this.text_decoder.decode(ee)}decode_chain($){const U=[];let ee=[];for(const se of $)this.added_tokens.find(Me=>Me.content===se)!==void 0?(ee.length>0&&(U.push(this.convert_tokens_to_string(ee)),ee=[]),U.push(se)):ee.push(se);return ee.length>0&&U.push(this.convert_tokens_to_string(ee)),U}}class ot extends Fe{constructor($){super($),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string($){if($.length===0)return"";const U=[$[0]];for(let Me=1;Me<$.length;++Me)$[Me]!==U.at(-1)&&U.push($[Me]);let se=U.filter(Me=>Me!==this.pad_token).join("");return this.cleanup&&(se=k(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain($){return[this.convert_tokens_to_string($)]}}class ht extends Fe{constructor($){super($),this.decoders=$.decoders.map(U=>Fe.fromConfig(U))}decode_chain($){return this.decoders.reduce((U,ee)=>ee.decode_chain(U),$)}}class Rt extends Fe{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((U,ee)=>U.replaceAll(this.suffix,ee===$.length-1?"":" "))}}class It extends Fe{decode_chain($){let U="";for(let ee=1;ee<$.length;ee+=2)U+=$[ee];return[U]}}class gr extends Q{constructor($){super(),this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:U=void 0}={}){let ee=$.replaceAll(" ",this.strRep);return!ee.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&U===0)&&(ee=this.strRep+ee),[ee]}}class Or extends Fe{constructor($){super($),this.replacement=$.replacement}decode_chain($){const U=[];for(let ee=0;ee<$.length;++ee){let se=$[ee].replaceAll(this.replacement," ");ee==0&&se.startsWith(" ")&&(se=se.substring(1)),U.push(se)}return U}}class zt extends ne{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(ee=>ee.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class Rr extends Q{constructor($){super(),this.tokenizers=$.pretokenizers.map(U=>Q.fromConfig(U))}pre_tokenize_text($,U){return this.tokenizers.reduce((ee,se)=>se.pre_tokenize(ee,U),[$])}}class qs extends Q{constructor($){super()}pre_tokenize_text($,U){return $.match(/\w+|[^\w\s]+/g)||[]}}class Qs extends Q{constructor($){super()}pre_tokenize_text($,U){return b($)}}class Xs extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,U){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}class or extends Q{constructor($){super(),this._length=$.length}pre_tokenize_text($,U){const ee=[];for(let se=0;se<$.length;se+=this._length)ee.push($.slice(se,se+this._length));return ee}}const Sr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Qr(ue,$,U,ee){for(const se of Object.keys(ue)){const Me=$-ue[se].length,$e=U(se),Xe=new Array(Me).fill($e);ue[se]=ee==="right"?(0,n.mergeArrays)(ue[se],Xe):(0,n.mergeArrays)(Xe,ue[se])}}function Bs(ue,$){for(const U of Object.keys(ue))ue[U].length=$}class ft extends s.Callable{return_token_type_ids=!1;padding_side="right";constructor($,U){super(),this.config=U,this.normalizer=ne.fromConfig($.normalizer),this.pre_tokenizer=Q.fromConfig($.pre_tokenizer),this.model=H.fromConfig($.model,U),this.post_processor=Ce.fromConfig($.post_processor),this.decoder=Fe.fromConfig($.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ee of $.added_tokens){const se=new F(ee);this.added_tokens.push(se),this.model.tokens_to_ids.set(se.content,se.id),this.model.vocab[se.id]=se.content,se.special&&(this.special_tokens.push(se.content),this.all_special_ids.push(se.id))}if(this.additional_special_tokens=U.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(ee=>ee.content)),this.added_tokens_map=new Map(this.added_tokens.map(ee=>[ee.content,ee])),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=U.model_max_length,this.remove_space=U.remove_space,this.clean_up_tokenization_spaces=U.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=U.do_lowercase_and_remove_accent??!1,U.padding_side&&(this.padding_side=U.padding_side),this.add_bos_token=U.add_bos_token,this.add_eos_token=U.add_eos_token,this.legacy=!1,this.chat_template=U.chat_template??null,Array.isArray(this.chat_template)){const ee=Object.create(null);for(const{name:se,template:Me}of this.chat_template){if(typeof se!="string"||typeof Me!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ee[se]=Me}this.chat_template=ee}this._compiled_template_cache=new Map}getToken(...$){for(const U of $){const ee=this.config[U];if(ee)if(typeof ee=="object"){if(ee.__type==="AddedToken")return ee.content;throw Error(`Unknown token: ${ee}`)}else return ee}return null}static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const Je=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe});return new this(...Je)}_call($,{text_pair:U=null,add_special_tokens:ee=!0,padding:se=!1,truncation:Me=null,max_length:$e=null,return_tensor:Xe=!0,return_token_type_ids:Je=null}={}){const Ye=Array.isArray($);let Ke;if(Ye){if($.length===0)throw Error("text array must be non-empty");if(U!==null){if(Array.isArray(U)){if($.length!==U.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ke=$.map((Et,rr)=>this._encode_plus(Et,{text_pair:U[rr],add_special_tokens:ee,return_token_type_ids:Je}))}else Ke=$.map(Et=>this._encode_plus(Et,{add_special_tokens:ee,return_token_type_ids:Je}))}else{if($==null)throw Error("text may not be null or undefined");if(Array.isArray(U))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ke=[this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:Je})]}if($e===null?$e=this.model_max_length:Me===null&&(se===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),$e=this.model_max_length):se===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),Me=!0)),se===!0&&($e=Math.min((0,i.max)(Ke.map(Et=>Et.input_ids.length))[0],$e??1/0)),$e=Math.min($e,this.model_max_length??1/0),se||Me)for(let Et=0;Et$e?Me&&Bs(Ke[Et],$e):se&&Qr(Ke[Et],$e,rr=>rr==="input_ids"?this.pad_token_id:0,this.padding_side));const $t={};if(Xe){if(!(se&&Me)&&Ke.some(rr=>{for(const br of Object.keys(rr))if(rr[br].length!==Ke[0][br]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Et=[Ke.length,Ke[0].input_ids.length];for(const rr of Object.keys(Ke[0]))$t[rr]=new a.Tensor("int64",BigInt64Array.from(Ke.flatMap(br=>br[rr]).map(BigInt)),Et)}else{for(const Et of Object.keys(Ke[0]))$t[Et]=Ke.map(rr=>rr[Et]);if(!Ye)for(const Et of Object.keys($t))$t[Et]=$t[Et][0]}return $t}_encode_text($){if($===null)return null;const U=this.added_tokens_splitter.split($);for(let se=0;se0&&(U[se-1]=U[se-1].trimEnd()),Me.rstrip&&se{if(se.length===0)return[];if(this.added_tokens_map.has(se))return[se];if(this.remove_space===!0&&(se=se.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(se=v(se)),this.normalizer!==null&&(se=this.normalizer(se)),se.length===0)return[];const $e=this.pre_tokenizer!==null?this.pre_tokenizer(se,{section_index:Me}):[se];return this.model($e)})}_encode_plus($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){const{tokens:Me,token_type_ids:$e}=this._tokenize_helper($,{pair:U,add_special_tokens:ee}),Xe=this.model.convert_tokens_to_ids(Me),Je={input_ids:Xe,attention_mask:new Array(Xe.length).fill(1)};return(se??this.return_token_type_ids)&&$e&&(Je.token_type_ids=$e),Je}_tokenize_helper($,{pair:U=null,add_special_tokens:ee=!1}={}){const se=this._encode_text($),Me=this._encode_text(U);return this.post_processor?this.post_processor(se,Me,{add_special_tokens:ee}):{tokens:(0,n.mergeArrays)(se??[],Me??[])}}tokenize($,{pair:U=null,add_special_tokens:ee=!1}={}){return this._tokenize_helper($,{pair:U,add_special_tokens:ee}).tokens}encode($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){return this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:se}).input_ids}batch_decode($,U={}){return $ instanceof a.Tensor&&($=$.tolist()),$.map(ee=>this.decode(ee,U))}decode($,U={}){if($ instanceof a.Tensor&&($=y($)),!Array.isArray($)||$.length===0||!(0,n.isIntegralNumber)($[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single($,U)}decode_single($,{skip_special_tokens:U=!1,clean_up_tokenization_spaces:ee=null}){let se=this.model.convert_ids_to_tokens($);U&&(se=se.filter($e=>!this.special_tokens.includes($e)));let Me=this.decoder?this.decoder(se):se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Me=Me.replaceAll(this.decoder.end_of_word_suffix," "),U&&(Me=Me.trim())),(ee??this.clean_up_tokenization_spaces)&&(Me=k(Me)),Me}get_chat_template({chat_template:$=null,tools:U=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ee=this.chat_template;if($!==null&&Object.hasOwn(ee,$))$=ee[$];else if($===null)if(U!==null&&"tool_use"in ee)$=ee.tool_use;else if("default"in ee)$=ee.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(ee).sort()}.`)}else if($===null)if(this.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 $}apply_chat_template($,{tools:U=null,documents:ee=null,chat_template:se=null,add_generation_prompt:Me=!1,tokenize:$e=!0,padding:Xe=!1,truncation:Je=!1,max_length:Ye=null,return_tensor:Ke=!0,return_dict:$t=!1,tokenizer_kwargs:Et={},...rr}={}){if(se=this.get_chat_template({chat_template:se,tools:U}),typeof se!="string")throw Error(`chat_template must be a string, but got ${typeof se}`);let br=this._compiled_template_cache.get(se);br===void 0&&(br=new c.Template(se),this._compiled_template_cache.set(se,br));const Xt=Object.create(null);for(const Ht of Sr){const qr=this.getToken(Ht);qr&&(Xt[Ht]=qr)}const sr=br.render({messages:$,add_generation_prompt:Me,tools:U,documents:ee,...Xt,...rr});if($e){const Ht=this._call(sr,{add_special_tokens:!1,padding:Xe,truncation:Je,max_length:Ye,return_tensor:Ke,...Et});return $t?Ht:Ht.input_ids}return sr}}class qt extends ft{return_token_type_ids=!0}class Ps extends ft{return_token_type_ids=!0}class Cs extends ft{return_token_type_ids=!0}class Kr extends ft{return_token_type_ids=!0}class yt extends ft{return_token_type_ids=!0}class Ss extends ft{return_token_type_ids=!0}class C extends ft{return_token_type_ids=!0}class q extends ft{return_token_type_ids=!0}class R extends ft{return_token_type_ids=!0}class G extends ft{}class Z extends ft{}class ce extends ft{return_token_type_ids=!0;constructor($,U){super($,U),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ye extends ft{return_token_type_ids=!0}class et extends ft{}class ut extends ft{}class He extends ft{}class Mt extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class qe extends Mt{}class Tt extends ft{}class kt extends ft{}const Mr="▁";class dr extends ft{padding_side="left";constructor($,U){super($,U),this.legacy=U.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gr({replacement:Mr,prepend_scheme:"first"}))}_encode_text($){if($===null)return null;if(this.legacy||$.length===0)return super._encode_text($);let U=super._encode_text(Mr+$.replaceAll(Mr," "));return U.length>1&&U[0]===Mr&&this.special_tokens.includes(U[1])&&(U=U.slice(1)),U}}class ar extends ft{}class Tr extends ft{}class Is extends ft{}class Dr extends ft{}class $s extends ft{}class Lr extends ft{}class zr extends ft{}class ts extends ft{}class wr extends ft{}function ir(ue,$,U,ee){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const se=ee.src_lang,Me=ee.tgt_lang;if(!ue.language_codes.includes(Me))throw new Error(`Target language code "${Me}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(se!==void 0){if(!ue.language_codes.includes(se))throw new Error(`Source language code "${se}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const $e of ue.post_processor.config.single)if("SpecialToken"in $e&&ue.languageRegex.test($e.SpecialToken.id)){$e.SpecialToken.id=ue.lang_to_token(se);break}}return ee.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(Me)])[0],ue._call($,U)}class Hr extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class rs extends ft{constructor($,U){super($,U),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)).map(ee=>ee.slice(2,-2)),this.lang_to_token=ee=>`__${ee}__`}_build_translation_inputs($,U,ee){return ir(this,$,U,ee)}}class Rs extends ft{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:U=!1,return_language:ee=!1,time_precision:se=null,force_full_sequences:Me=!0}={}){if(se===null)throw Error("Must specify time_precision");let $e=null;const Xe=U==="word";function Je(){return{language:$e,timestamp:[null,null],text:""}}const Ye=[];let Ke=Je(),$t=0;const Et=this.timestamp_begin,br=Et+1500;let Xt=[],sr=[],Ht=!1,qr=null;const ns=new Set(this.all_special_ids);for(const Yt of $){const hr=Yt.tokens,Ir=Xe?Yt.token_timestamps:null;let Xr=null,ps=Et;if("stride"in Yt){const[vr,Zt,_r]=Yt.stride;if($t-=Zt,qr=vr-_r,Zt&&(ps=Zt/se+Et),_r)for(let lr=hr.length-1;lr>=0;--lr){const Ur=Number(hr[lr]);if(Ur>=Et){if(Xr!==null&&(Ur-Et)*se=Et&&Zt<=br){const _r=(Zt-Et)*se+$t,lr=(0,i.round)(_r,2);if(Xr!==null&&Zt>=Xr)Ht=!0;else if(Ht||Xt.length>0&&Zt0?(Xt.push(yr),Xe&&sr.push(os)):Xt.every(vr=>vr.length===0)&&(Ke=Je(),Xt=[],yr=[],sr=[],os=[])}if(Xt.length>0){if(Me&&U)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[Yt,hr]=this.findLongestCommonSequence(Xt,sr),Ir=this.decode(Yt);Ke.text=Ir,Xe&&(Ke.words=this.collateWordTimestamps(Yt,hr,$e)),Ye.push(Ke)}let Er=Object.create(null);const ds=Ye.map(Yt=>Yt.text).join("");if(U||ee){for(let Yt=0;Yt0;let Xe=$e?[]:null,Je=$e?U[0]:null;for(let Ye=1;Ye<$.length;++Ye){const Ke=$[Ye];let $t=0,Et=[se,se,0,0];const rr=Ke.length;for(let Er=1;ErZt===ps[_r]&&Je[ds+_r]<=U[Ye][Ir+_r]).length:yr=hr.filter((Zt,_r)=>Zt===ps[_r]).length;const os=Er/1e4,vr=yr/Er+os;yr>1&&vr>$t&&($t=vr,Et=[ds,Yt,Ir,Xr])}const[br,Xt,sr,Ht]=Et,qr=Math.floor((Xt+br)/2),ns=Math.floor((Ht+sr)/2);Me.push(...ee.slice(0,qr)),ee=Ke.slice(ns),se=ee.length,$e&&(Xe.push(...Je.slice(0,qr)),Je=U[Ye].slice(ns))}return Me.push(...ee),$e?(Xe.push(...Je),[Me,Xe]):[Me,[]]}collateWordTimestamps($,U,ee){const[se,Me,$e]=this.combineTokensIntoWords($,ee),Xe=[];for(let Je=0;Je=se){const Xe=(($e-se)*ee).toFixed(2);Me.push(`<|${Xe}|>`),Me.push([])}else Me[Me.length-1].push($e);return Me=Me.map($e=>typeof $e=="string"?$e:super.decode($e,U)),Me.join("")}splitTokensOnUnicode($){const U=this.decode($,{decode_with_timestamps:!0}),ee="�",se=[],Me=[],$e=[];let Xe=[],Je=[],Ye=0;for(let Ke=0;Ke<$.length;++Ke){const $t=$[Ke];Xe.push($t),Je.push(Ke);const Et=this.decode(Xe,{decode_with_timestamps:!0});(!Et.includes(ee)||U[Ye+Et.indexOf(ee)]===ee)&&(se.push(Et),Me.push(Xe),$e.push(Je),Xe=[],Je=[],Ye+=Et.length)}return[se,Me,$e]}splitTokensOnSpaces($){const[U,ee,se]=this.splitTokensOnUnicode($),Me=[],$e=[],Xe=[],Je=new RegExp(`^[${E}]$`,"gu");for(let Ye=0;Ye=this.model.tokens_to_ids.get("<|endoftext|>"),br=Ke.startsWith(" "),Xt=Ke.trim(),sr=Je.test(Xt);if(rr||br||sr||Me.length===0)Me.push(Ke),$e.push($t),Xe.push(Et);else{const Ht=Me.length-1;Me[Ht]+=Ke,$e[Ht].push(...$t),Xe[Ht].push(...Et)}}return[Me,$e,Xe]}mergePunctuations($,U,ee,se,Me){const $e=structuredClone($),Xe=structuredClone(U),Je=structuredClone(ee);let Ye=$e.length-2,Ke=$e.length-1;for(;Ye>=0;)$e[Ye].startsWith(" ")&&se.includes($e[Ye].trim())?($e[Ke]=$e[Ye]+$e[Ke],Xe[Ke]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ke]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ye]="",Xe[Ye]=[],Je[Ye]=[]):Ke=Ye,--Ye;for(Ye=0,Ke=1;Ke<$e.length;)!$e[Ye].endsWith(" ")&&Me.includes($e[Ke])?($e[Ye]+=$e[Ke],Xe[Ye]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ye]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ke]="",Xe[Ke]=[],Je[Ke]=[]):Ye=Ke,++Ke;return[$e.filter($t=>$t),Xe.filter($t=>$t.length>0),Je.filter($t=>$t.length>0)]}}class ks extends ft{}class As extends ft{}class Fs extends ft{}class ss extends ft{constructor($,U){super($,U),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ee=>this.languageRegex.test(ee)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[U,...ee]=$.trim().split(this.languageRegex);if(ee.length===0)return super._encode_text(U);if(ee.length===2){const[se,Me]=ee;return this.supported_language_codes.includes(se)||console.warn(`Unsupported language code "${se}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,n.mergeArrays)([se],super._encode_text(Me))}}}class Nr extends ft{}class ze extends ft{}class Ue extends ft{}class nt extends ft{}class Kt extends ft{}class Ns extends ft{constructor($,U){super($,U),this.decoder=new It({})}}class Os extends ft{}class js extends ft{}class Dn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:et,DistilBertTokenizer:G,CamembertTokenizer:Z,DebertaTokenizer:yt,DebertaV2Tokenizer:Ss,BertTokenizer:qt,HerbertTokenizer:C,ConvBertTokenizer:q,RoFormerTokenizer:R,XLMTokenizer:ce,ElectraTokenizer:ye,MobileBertTokenizer:Cs,SqueezeBertTokenizer:Kr,AlbertTokenizer:Ps,GPT2Tokenizer:ut,BartTokenizer:He,MBartTokenizer:Mt,MBart50Tokenizer:qe,RobertaTokenizer:Tt,WhisperTokenizer:Rs,CodeGenTokenizer:ks,CLIPTokenizer:As,SiglipTokenizer:Fs,MarianTokenizer:ss,BloomTokenizer:kt,NllbTokenizer:Hr,M2M100Tokenizer:rs,LlamaTokenizer:dr,CodeLlamaTokenizer:ar,XLMRobertaTokenizer:Tr,MPNetTokenizer:Is,FalconTokenizer:Dr,GPTNeoXTokenizer:$s,EsmTokenizer:Lr,Wav2Vec2CTCTokenizer:Nr,BlenderbotTokenizer:ze,BlenderbotSmallTokenizer:Ue,SpeechT5Tokenizer:nt,NougatTokenizer:Kt,VitsTokenizer:Ns,Qwen2Tokenizer:zr,GemmaTokenizer:ts,Grok1Tokenizer:wr,CohereTokenizer:Os,MgpstrTokenizer:js,PreTrainedTokenizer:ft};static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const[Je,Ye]=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe}),Ke=Ye.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let $t=this.TOKENIZER_CLASS_MAPPING[Ke];return $t||(console.warn(`Unknown tokenizer class "${Ke}", attempting to construct from base class.`),$t=ft),new $t(Je,Ye)}}}),"./src/utils/audio.js":((e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>W,hamming:()=>u,hanning:()=>d,mel_filter_bank:()=>I,read_audio:()=>c,spectrogram:()=>S,window_function:()=>O});var s=t("./src/utils/hub.js"),n=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("./src/utils/tensor.js"),l=t("?7992");async function c(B,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const X=await(await(0,s.getFile)(B)).arrayBuffer(),J=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const re=await J.decodeAudioData(X);let ne;if(re.numberOfChannels===2){const le=Math.sqrt(2),pe=re.getChannelData(0),oe=re.getChannelData(1);ne=new Float32Array(pe.length);for(let K=0;K2595*Math.log10(1+B/700),kaldi:B=>1127*Math.log(1+B/700),slaney:(B,Y=1e3,X=15,J=27/Math.log(6.4))=>B>=Y?X+Math.log(B/Y)*J:3*B/200};function _(B,Y="htk"){const X=f[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}const y={htk:B=>700*(10**(B/2595)-1),kaldi:B=>700*(Math.exp(B/1127)-1),slaney:(B,Y=1e3,X=15,J=Math.log(6.4)/27)=>B>=X?Y*Math.exp(J*(B-X)):200*B/3};function k(B,Y="htk"){const X=y[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}function w(B,Y){const X=Float64Array.from({length:Y.length-1},(le,pe)=>Y[pe+1]-Y[pe]),J=Array.from({length:B.length},()=>new Array(Y.length));for(let le=0;lenew Array(B.length));for(let le=0;leB+J*ne)}function I(B,Y,X,J,re,ne=null,le="htk",pe=!1){if(ne!==null&&ne!=="slaney")throw new Error('norm must be one of null or "slaney"');if(B<2)throw new Error(`Require num_frequency_bins: ${B} >= 2`);if(X>J)throw new Error(`Require min_frequency: ${X} <= max_frequency: ${J}`);const oe=_(X,le),K=_(J,le),N=v(oe,K,Y+2);let D=k(N,le),te;if(pe){const Ae=re/((B-1)*2);te=_(Float64Array.from({length:B},(Ie,je)=>je*Ae),le),D=N}else te=v(0,Math.floor(re/2),B);const he=w(te,D);if(ne!==null&&ne==="slaney")for(let Ae=0;Aere)throw Error(`frame_length (${X}) may not be larger than fft_length (${re})`);if(xe!==X)throw new Error(`Length of the window (${xe}) must equal frame_length (${X})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(ne===null&&D!==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(!N)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(le)switch(pe){case"reflect":{const Ne=Math.floor((re-1)/2)+1;B=T(B,Ne,Ne);break}case"constant":{const Ne=Math.floor(re/2),Oe=new B.constructor(B.length+2*Ne);Oe.set(B,Ne),B=Oe;break}default:throw new Error(`pad_mode="${pe}" not implemented yet.`)}let Ce=Math.floor(1+Math.floor((B.length-X)/J));Q!==null&&CeCe?de&&(fe=z):fe=De=z);const Ee=new n.FFT(re),We=new Float64Array(re),Fe=new Float64Array(Ee.outputBufferSize),tt=new Float32Array(ge*fe);for(let Ne=0;Ne=1;--ht)We[ht]-=K*We[ht-1];We[0]*=1-K}for(let ht=0;htMath.pow(pe,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(X&&(le=le.subarray(0,B)),J===null)return le;if(B>J)throw new Error(`Length of the window (${B}) may not be larger than frame_length (${J})`);return le}function F(B,Y){let X=44;const J=new ArrayBuffer(X+B.length*4),re=new DataView(J);H(re,0,"RIFF"),re.setUint32(4,36+B.length*4,!0),H(re,8,"WAVE"),H(re,12,"fmt "),re.setUint32(16,16,!0),re.setUint16(20,3,!0),re.setUint16(22,1,!0),re.setUint32(24,Y,!0),re.setUint32(28,Y*4,!0),re.setUint16(32,4,!0),re.setUint16(34,32,!0),H(re,36,"data"),re.setUint32(40,B.length*4,!0);for(let ne=0;ne{let ne=await re.arrayBuffer();l.writeFileSync(J,Buffer.from(ne))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await X(Y,this.toBlob())}}}),"./src/utils/constants.js":((e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>n,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",i=o,a="processor_config.json",l="chat_template.jinja",c="generation_config.json"}),"./src/utils/core.js":((e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>o,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>y,pop:()=>p,product:()=>u,reverseDictionary:()=>n,saveBlob:()=>_});function s(v,I){v&&v(I)}function n(v){return Object.fromEntries(Object.entries(v).map(([I,T])=>[T,I]))}function o(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(v){return v?.prototype?.__proto__?.constructor?.name==="TypedArray"}function a(v){return Number.isInteger(v)||typeof v=="bigint"}function l(v){return v==null||v===-1}function c(v){const I=[];let T=v;for(;Array.isArray(T);)I.push(T.length),T=T[0];return I}function p(v,I,T=void 0){const b=v[I];if(b!==void 0)return delete v[I],b;if(T===void 0)throw Error(`Key ${I} does not exist in object.`);return T}function d(...v){return Array.prototype.concat.apply([],v)}function u(...v){return v.reduce((I,T)=>I.flatMap(b=>T.map(E=>[b,E])))}function f(v,I){return Math.abs((v+I)%(2*I)-I)}function _(v,I){const T=URL.createObjectURL(I),b=document.createElement("a");b.href=T,b.download=v,b.click(),b.remove(),URL.revokeObjectURL(T)}function y(v,I){return Object.assign({},...I.map(T=>{if(v[T]!==void 0)return{[T]:v[T]}}))}function k(v){let I=0;for(const T of v)++I;return I}function w(v,I){let T=0;for(const b of v)b===I&&++T;return T}}),"./src/utils/data-structures.js":((e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>n,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,u=1/0){this._heap=[],this._comparator=d,this._maxSize=u}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const u of d)if(this.size0&&this._swap(0,u),this._heap.pop(),this._siftDown(),d}replace(d){const u=this.peek();return this._heap[0]=d,this._siftDown(),u}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,u){return this._comparator(this._heap[d],this._heap[u])}_swap(d,u){const f=this._heap[d];this._heap[d]=this._heap[u],this._heap[u]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),y=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(y.clone()),this.beginNodes[this.len].push(y),this.endNodes[0].push(_)}insert(d,u,f,_){const y=this.nodes.length,k=new a(_,y,d,u,f);this.beginNodes[d].push(k),this.endNodes[d+u].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let u=0;for(;u<=d;){if(this.beginNodes[u].length==0)return[];for(let w of this.beginNodes[u]){w.prev=null;let v=0,I=null;for(let T of this.endNodes[u]){const b=T.backtraceScore+w.score;(I===null||b>v)&&(I=T.clone(),v=b)}if(I!==null)w.prev=I,w.backtraceScore=v;else return[]}++u}const f=[],y=this.beginNodes[d][0].prev;if(y===null)return[];let k=y.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class a{constructor(d,u,f,_,y){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=y,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){const u=Object.create(null);for(const f of d){let _=u;for(let y=0;y_&&u.push(d.slice(_,y)),u.push(w),y+=w.length,_=y):++y}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}}),"./src/utils/devices.js":((e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})}),"./src/utils/dtypes.js":((e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>o});var s=t("./src/env.js"),n=t("./src/utils/devices.js");const o=(function(){let c;return async function(){if(c===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)c=!1;else try{c=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{c=!1}return c}})(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[n.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})}),"./src/utils/generic.js":((e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let n=function(...o){return n._call(...o)};return Object.setPrototypeOf(n,new.target.prototype)}_call(...n){throw Error("Must implement _call method in subclass")}}}),"./src/utils/hub.js":((e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>v,getModelJSON:()=>T,getModelText:()=>I});var s=t("?7992"),n=t("?5af5"),o=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(S){if(this.filePath=S,this.headers=new Headers,this.exists=s.existsSync(S),this.exists){this.status=200,this.statusText="OK";let O=s.statSync(S);this.headers.set("content-length",O.size.toString()),this.updateContentType();const F=s.createReadStream(S);this.body=new ReadableStream({start(H){F.on("data",W=>H.enqueue(W)),F.on("end",()=>H.close()),F.on("error",W=>H.error(W))},cancel(){F.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const S=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[S]??"application/octet-stream")}clone(){let S=new c(this.filePath);return S.exists=this.exists,S.status=this.status,S.statusText=this.statusText,S.headers=new Headers(this.headers),S}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const S=await s.promises.readFile(this.filePath);return new Blob([S],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,S=null,O=null){let F;try{F=new URL(x)}catch{return!1}return!(S&&!S.includes(F.protocol)||O&&!O.includes(F.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(x){return!(!d.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function f(x){if(o.env.useFS&&!p(x,["http:","https:","blob:"]))return new c(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&process?.release?.name==="node"){const S=!!Qc?.TESTING_REMOTELY,O=o.env.version,F=new Headers;if(F.set("User-Agent",`transformers.js/${O}; is_ci/${S};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const W=Qc?.HF_TOKEN??Qc?.HF_ACCESS_TOKEN;W&&F.set("Authorization",`Bearer ${W}`)}return fetch(x,{headers:F})}else return fetch(x)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function y(x,S,O){if(!O)return null;const F=_[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${F}: "${S}".`)}class k{constructor(S){this.path=S}async match(S){let O=n.join(this.path,S),F=new c(O);if(F.exists)return F}async put(S,O,F=void 0){let H=n.join(this.path,S);try{const W=O.headers.get("Content-Length"),B=parseInt(W??"0");let Y=0;await s.promises.mkdir(n.dirname(H),{recursive:!0});const X=s.createWriteStream(H),J=O.body.getReader();for(;;){const{done:re,value:ne}=await J.read();if(re)break;await new Promise((pe,oe)=>{X.write(ne,K=>{if(K){oe(K);return}pe()})}),Y+=ne.length;const le=B?Y/B*100:0;F?.({progress:le,loaded:Y,total:B})}X.close()}catch(W){try{await s.promises.unlink(H)}catch{}throw W}}}async function w(x,...S){for(let O of S)try{let F=await x.match(O);if(F)return F}catch{continue}}async function v(x,S,O=!0,F={},H=!1){if(!o.env.allowLocalModels){if(F.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!o.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(F.progress_callback,{status:"initiate",name:x,file:S});let W;if(!W&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");W=o.env.customCache}if(!W&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{W=await caches.open("transformers-cache")}catch(te){console.warn("An error occurred while opening the browser cache:",te)}}if(!W&&o.env.useFSCache){if(!o.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");W=new k(F.cache_dir??o.env.cacheDir)}const B=F.revision??"main",Y=E(x,S),X=u(x),J=X?E(o.env.localModelPath,Y):Y,re=E(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(B)),S);let ne;const le=W instanceof k?B==="main"?Y:E(x,B,S):re;let pe=!1,oe;W&&(oe=await w(W,J,le));const K=oe!==void 0;if(oe===void 0){if(o.env.allowLocalModels)if(p(Y,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}else try{oe=await f(J),ne=J}catch(he){console.warn(`Unable to load from local path "${J}": "${he}"`)}if(oe===void 0||oe.status===404){if(F.local_files_only||!o.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(!X)throw Error(`Local file missing at "${J}" and download aborted due to invalid model ID "${x}".`);if(oe=await f(re),oe.status!==200)return y(oe.status,re,O);ne=le}pe=W&&typeof Response<"u"&&oe instanceof Response&&oe.status===200}(0,i.dispatchCallback)(F.progress_callback,{status:"download",name:x,file:S});let N;if(!(o.apis.IS_NODE_ENV&&H)){let te;F.progress_callback?K&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(te=new Uint8Array(await oe.arrayBuffer()),(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,progress:100,loaded:te.length,total:te.length})):te=await b(oe,he=>{(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he})}):te=new Uint8Array(await oe.arrayBuffer()),N=te}if(pe&&ne&&await W.match(ne)===void 0)if(N)await W.put(ne,new Response(N,{headers:oe.headers})).catch(te=>{console.warn(`Unable to add response to browser cache: ${te}.`)});else{const te=F.progress_callback?he=>(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he}):void 0;await W.put(ne,oe,te)}if((0,i.dispatchCallback)(F.progress_callback,{status:"done",name:x,file:S}),N){if(!o.apis.IS_NODE_ENV&&H)throw new Error("Cannot return path in a browser environment.");return N}if(oe instanceof c)return oe.filePath;const D=await W?.match(ne);if(D instanceof c)return D.filePath;if(D instanceof Response)return new Uint8Array(await D.arrayBuffer());if(typeof D=="string")return D;throw new Error("Unable to get model file path or buffer.")}async function I(x,S,O=!0,F={}){const H=await v(x,S,O,F,!1);return H===null?null:new TextDecoder("utf-8").decode(H)}async function T(x,S,O=!0,F={}){const H=await I(x,S,O,F);return H===null?{}:JSON.parse(H)}async function b(x,S){const O=x.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(O??"0"),H=new Uint8Array(F),W=0;const B=x.body.getReader();async function Y(){const{done:X,value:J}=await B.read();if(X)return;const re=W+J.length;if(re>F){F=re;const le=new Uint8Array(F);le.set(H),H=le}H.set(J,W),W=re;const ne=W/F*100;return S({progress:ne,loaded:W,total:F}),Y()}return await Y(),H}function E(...x){return x=x.map((S,O)=>(O&&(S=S.replace(new RegExp("^/"),"")),O!==x.length-1&&(S=S.replace(new RegExp("/$"),"")),S)),x.join("/")}}),"./src/utils/image.js":((e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>y});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,c,p;const d=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(d)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async k=>{const v=(await k.metadata()).channels,{data:I,info:T}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),b=new _(new Uint8ClampedArray(I),T.width,T.height,T.channels);return v!==void 0&&v!==T.channels&&b.convert(v),b};else throw new Error("Unable to load image processing library.");const u={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(w,v,I,T){this.data=w,this.width=v,this.height=I,this.channels=T}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const I=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _(I,w.width,w.height,4)}static async fromURL(w){const v=await(0,n.getFile)(w);if(v.status!==200)throw new Error(`Unable to read image from "${w}" (${v.status} ${v.statusText})`);const I=await v.blob();return this.fromBlob(I)}static async fromBlob(w){if(d){const v=await p(w),I=l(v.width,v.height).getContext("2d");return I.drawImage(v,0,0),new this(I.getImageData(0,0,v.width,v.height).data,v.width,v.height,4)}else{const v=a(await w.arrayBuffer());return await p(v)}}static fromTensor(w,v="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(v==="CHW")w=w.transpose(1,2,0);else if(v!=="HWC")throw new Error(`Unsupported channel format: ${v}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let v=0,I=0;v=0?S=I:F=-I,T>=0?O=T:H=-T,x.drawImage(E,S,O,w,v,F,H,w,v),new _(x.getImageData(0,0,w,v).data,w,v,4).convert(b)}else{let b=this.toSharp();if(I>=0&&T>=0)b=b.extract({left:Math.floor(I),top:Math.floor(T),width:w,height:v});else if(I<=0&&T<=0){const E=Math.floor(-T),x=Math.floor(-I);b=b.extend({top:E,left:x,right:w-this.width-x,bottom:v-this.height-E})}else{let E=[0,0],x=0;T<0?(E[0]=Math.floor(-T),E[1]=v-this.height-E[0]):x=Math.floor(T);let S=[0,0],O=0;I<0?(S[0]=Math.floor(-I),S[1]=w-this.width-S[0]):O=Math.floor(I),b=b.extend({top:E[0],bottom:E[1],left:S[0],right:S[1]}).extract({left:O,top:x,width:w,height:v})}return await p(b)}}async toBlob(w="image/png",v=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:v})}toTensor(w="CHW"){let v=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")v=v.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return v}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),v=l(w.width,w.height),I=new c(w.data,w.width,w.height);return v.getContext("2d").putImageData(I,0,0),v}split(){const{data:w,width:v,height:I,channels:T}=this,b=w.constructor,E=w.length/T,x=Array.from({length:T},()=>new b(E));for(let S=0;Snew _(S,v,I,1))}_update(w,v,I,T=null){return this.data=w,this.width=v,this.height=I,T!==null&&(this.channels=T),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(w){if(d){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const v=w.split(".").pop().toLowerCase(),I=f.get(v)??"image/png",T=await this.toBlob(I);(0,s.saveBlob)(w,T)}else{if(o.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const y=_.read.bind(_)}),"./src/utils/maths.js":((e,r,t)=>{t.r(r),t.d(r,{FFT:()=>y,bankers_round:()=>v,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>I,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>c,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>n,round:()=>w,softmax:()=>o});function s(T,[b,E,x],[S,O],F="bilinear",H=!1){const W=O/x,B=S/E,Y=new T.constructor(S*O*b),X=E*x,J=S*O;for(let re=0;re=0;--H)S[H]=W,x[H]=b[E[H]],W*=x[H];const O=E.map((H,W)=>S[E.indexOf(W)]),F=new T.constructor(T.length);for(let H=0;H=0;--B)W+=Y%b[B]*O[B],Y=Math.floor(Y/b[B]);F[W]=T[H]}return[F,x]}function o(T){const b=d(T)[0],E=T.map(O=>Math.exp(O-b)),x=E.reduce((O,F)=>O+F,0);return E.map(O=>O/x)}function i(T){const b=d(T)[0];let E=0;for(let O=0;OO-b-x)}function a(T,b){let E=0;for(let x=0;xb+E*E,0))}function p(T){if(T.length===0)throw Error("Array must not be empty");let b=T[0],E=0;for(let x=1;xb&&(b=T[x],E=x);return[b,E]}function u(T){return T>0&&(T&T-1)===0}class f{constructor(b){if(this.size=b|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=b<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++E;this._width=E%2===0?E-1:E,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=b[S];return x}toComplexArray(b,E){const x=E||this.createComplexArray();for(let S=0;S>>1],x[S+1]=0;return x}transform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._transform4(b,E,1)}realTransform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._realTransform4(b,E,1)}inverseTransform(b,E){if(b===E)throw new Error("Input and output buffers must be different");this._transform4(b,E,-1);for(let x=0;x>=2;F>=2;F>>=2){H=S/F<<1;const J=H>>>2;for(W=0;W>>1,F>>>1)}else for(W=0,B=0;W>>1,F>>>1,x)}const X=this.table;for(F>>=2;F>=2;F>>=2){H=S/F<<1;const re=H>>>1,ne=re>>>1,le=ne>>>1;for(W=0;W>>1;for(let re=2;re>1;++Y){const X=(Y+1-b)**2/2,J=Math.sqrt(W**2+B**2)**X,re=X*Math.atan2(B,W),ne=2*Y;O[ne]=J*Math.cos(re),O[ne+1]=J*Math.sin(re),F[ne]=O[ne],F[ne+1]=-O[ne+1]}this._slicedChirpBuffer=O.subarray(E,x),this._f=new f(S>>1),this._f.transform(this._chirpBuffer,F)}_transform(b,E,x){const S=this._buffer1,O=this._buffer2,F=this._outBuffer1,H=this._outBuffer2,W=this._chirpBuffer,B=this._slicedChirpBuffer,Y=this._a;if(x)for(let X=0;X>1,ne=E[re];S[X]=ne*B[X],S[J]=ne*B[J]}else for(let X=0;X=T.length&&(W=2*(T.length-1)-W),x[F++]=T[W]}x.sort(),E[O]=x[S]}return E}function w(T,b){const E=Math.pow(10,b);return Math.round(T*E)/E}function v(T){const b=Math.round(T);return Math.abs(T)%1===.5?b%2===0?b:b-1:b}function I(T){const b=T.length,E=T[0].length,x=[b+1,E+1],S=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));S[0][0]=0;const O=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let Y=1;Y0||H>0;)switch(W.push(F-1),B.push(H-1),O[F][H]){case 0:--F,--H;break;case 1:--F;break;case 2:--H;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${F}, ${H}]. Please file a bug report.`)}return W.reverse(),B.reverse(),[W,B]}}),"./src/utils/tensor.js":((e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>E,full:()=>B,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>v,matmul:()=>u,mean:()=>F,mean_pooling:()=>w,ones:()=>X,ones_like:()=>J,permute:()=>c,quantize_embeddings:()=>oe,rand:()=>le,randn:()=>pe,rfft:()=>f,slice:()=>k,stack:()=>x,std_mean:()=>O,topk:()=>_,zeros:()=>re,zeros_like:()=>ne});var s=t("./src/utils/maths.js"),n=t("./src/backends/onnx.js"),o=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{get dims(){return this.ort_tensor.dims}set dims(N){this.ort_tensor.dims=N}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...N){return(0,n.isONNXTensor)(N[0])?this.ort_tensor=N[0]:this.ort_tensor=new n.Tensor(N[0],N[1],N[2]),new Proxy(this,{get:(D,te)=>{if(typeof te=="string"){let he=Number(te);if(Number.isInteger(he))return D._getitem(he)}return D[te]},set:(D,te,he)=>D[te]=he})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[N,...D]=this.dims;if(D.length>0){const te=D.reduce((he,Ae)=>he*Ae);for(let he=0;he0){const he=te.reduce((Ae,Ie)=>Ae*Ie);return this._subarray(N,he,te)}else return new a(this.type,[this.data[N]],te)}indexOf(N){const D=this.data;for(let te=0;teve)throw new Error(`Invalid slice: ${de}`);const xe=[Math.max(be,0),Math.min(ve,this.dims[z])];te.push(xe),D.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${de}`)}const he=te.map(([z,de])=>de-z),Ae=he.reduce((z,de)=>z*de),Ie=this.data,je=new Ie.constructor(Ae),Te=this.stride();let Q=!0;for(let z=1;z=0;--be){const xe=he[be];de+=(ve%xe+te[be][0])*Te[be],ve=Math.floor(ve/xe)}je[z]=Ie[de]}return new a(this.type,je,D)}permute(...N){return c(this,N)}transpose(...N){return this.permute(...N)}sum(N=null,D=!1){return this.norm(1,N,D)}norm(N="fro",D=null,te=!1){if(N==="fro")N=2;else if(typeof N=="string")throw Error(`Unsupported norm: ${N}`);const he=this.data,Ae=(Q,z)=>Q+z**N;if(D===null){const Q=he.reduce(Ae,0)**(1/N);return new a(this.type,[Q],[])}const[Ie,je,Te]=S(Ae,this,D,te);if(N!==1)for(let Q=0;Q=0;--Te){const de=this.dims[Te];if(Te!==D){const be=Q%de;je+=be*z,z*=this.dims[Te]}Q=Math.floor(Q/de)}he[Ie]/=Ae[je]}return this}normalize(N=2,D=1){return this.clone().normalize_(N,D)}stride(){return H(this.dims)}squeeze(N=null){return new a(this.type,this.data,I(this.dims,N))}squeeze_(N=null){return this.dims=I(this.dims,N),this}unsqueeze(N=null){return new a(this.type,this.data,T(this.dims,N))}unsqueeze_(N=null){return this.dims=T(this.dims,N),this}flatten_(N=0,D=-1){D=(D+this.dims.length)%this.dims.length;let te=this.dims.slice(0,N),he=this.dims.slice(N,D+1),Ae=this.dims.slice(D+1);return this.dims=[...te,he.reduce((Ie,je)=>Ie*je,1),...Ae],this}flatten(N=0,D=-1){return this.clone().flatten_(N,D)}view(...N){let D=-1;for(let he=0;heje!==D?Ae*Ie:Ae,1);N[D]=te.length/he}return new a(this.type,te,N)}neg_(){const N=this.data;for(let D=0;DN?1:0;return new a("bool",D,this.dims)}lt(N){const D=new Uint8Array(this.data.length),te=this.data;for(let he=0;heMath.min(Ie,je),this,N,D,1/0);return new a(te,he,Ae)}max(N=null,D=!1){if(N===null){const Ie=(0,s.max)(this.data)[0];return new a(this.type,[Ie],[])}const[te,he,Ae]=S((Ie,je)=>Math.max(Ie,je),this,N,D,-1/0);return new a(te,he,Ae)}argmin(N=null,D=!1){if(N!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.min)(this.data)[1];return new a("int64",[BigInt(te)],[])}argmax(N=null,D=!1){if(N!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.max)(this.data)[1];return new a("int64",[BigInt(te)],[])}to(N){if(this.type===N)return this;if(!i.hasOwnProperty(N))throw new Error(`Unsupported type: ${N}`);let D;const te=["int64","uint64"].includes(this.type),he=["int64","uint64"].includes(N);return te&&!he?D=Number:!te&&he&&(["float16","float32","float64"].includes(this.type)?D=Ae=>BigInt(Math.floor(Ae)):D=BigInt),new a(N,i[N].from(this.data,D),this.dims)}}function l(K,N){const D=K.length,te=N.reduce((Ae,Ie)=>Ae*Ie);if(D!==te)throw Error(`cannot reshape array of size ${D} into shape (${N})`);let he=K;for(let Ae=N.length-1;Ae>=0;Ae--)he=he.reduce((Ie,je)=>{let Te=Ie[Ie.length-1];return Te.lengthnew a("int64",K,[K.length]);async function k(K,N,D,te,he){return await(await o.TensorOpRegistry.slice)({x:K,s:y(N),e:y(D),a:y(te),t:y(he??new Array(te.length).fill(1))})}function w(K,N){const D=K.data,te=N.data,he=[K.dims[0],K.dims[2]],Ae=new D.constructor(he[0]*he[1]),[Ie,je,Te]=K.dims;let Q=0;for(let z=0;zD!==1):typeof N=="number"?K[N]===1&&K.splice(N,1):Array.isArray(N)&&(K=K.filter((D,te)=>D!==1||!N.includes(te))),K}function T(K,N){return N=b(N,K.length+1),K=K.slice(),K.splice(N,0,1),K}function b(K,N,D=null,te=!0){if(K<-N||K>=N){if(te)throw new Error(`IndexError: index ${K} is out of bounds for dimension${D===null?"":" "+D} with size ${N}`);return K<-N?0:N}return K<0&&(K=(K%N+N)%N),K}function E(K,N=0){N=b(N,K[0].dims.length);const D=K[0].dims.slice();D[N]=K.reduce((Ie,je)=>Ie+je.dims[N],0);const te=D.reduce((Ie,je)=>Ie*je,1),he=new K[0].data.constructor(te),Ae=K[0].type;if(N===0){let Ie=0;for(const je of K){const Te=je.data;he.set(Te,Ie),Ie+=Te.length}}else{let Ie=0;for(let je=0;je=0;--be){const Ce=Q[be];let ge=ve%Ce;be===N&&(ge+=Ie),de+=ge*xe,xe*=D[be],ve=Math.floor(ve/Ce)}he[de]=Te[z]}Ie+=Q[N]}}return new a(Ae,he,D)}function x(K,N=0){return E(K.map(D=>D.unsqueeze(N)),N)}function S(K,N,D=null,te=!1,he=null){const Ae=N.data,Ie=N.dims;D=b(D,Ie.length);const je=Ie.slice();je[D]=1;const Te=new Ae.constructor(Ae.length/Ie[D]);he!==null&&Te.fill(he);for(let Q=0;Q=0;--de){const xe=Ie[de];if(de!==D){const Ce=be%xe;z+=Ce*ve,ve*=je[de]}be=Math.floor(be/xe)}Te[z]=K(Te[z],Ae[Q],Q,z)}return te||je.splice(D,1),[N.type,Te,je]}function O(K,N=null,D=1,te=!1){const he=K.data,Ae=K.dims;if(N===null){const ve=he.reduce((De,fe)=>De+fe,0)/he.length,xe=Math.sqrt(he.reduce((De,fe)=>De+(fe-ve)**2,0)/(he.length-D)),Ce=new a(K.type,[ve],[]);return[new a(K.type,[xe],[]),Ce]}N=b(N,Ae.length);const Ie=F(K,N,te),je=Ie.data,[Te,Q,z]=S((be,ve,xe,Ce)=>be+(ve-je[Ce])**2,K,N,te);for(let be=0;beQ+z,0);return new a(K.type,[Te/he.length],[])}N=b(N,te.length);const[Ae,Ie,je]=S((Te,Q)=>Te+Q,K,N,D);if(te[N]!==1)for(let Te=0;Te=0;--D)N[D]=te,te*=K[D];return N}function W(K,N,D,te){const he=K.reduce((Ae,Ie)=>Ae*Ie,1);return new a(D,new te(he).fill(N),K)}function B(K,N){let D,te;if(typeof N=="number")D="float32",te=Float32Array;else if(typeof N=="bigint")D="int64",te=BigInt64Array;else if(typeof N=="boolean")D="bool",te=Uint8Array;else throw new Error(`Unsupported data type: ${typeof N}`);return W(K,N,D,te)}function Y(K,N){return B(K.dims,N)}function X(K){return W(K,1n,"int64",BigInt64Array)}function J(K){return X(K.dims)}function re(K){return W(K,0n,"int64",BigInt64Array)}function ne(K){return re(K.dims)}function le(K){const N=K.reduce((D,te)=>D*te,1);return new a("float32",Float32Array.from({length:N},()=>Math.random()),K)}function pe(K){const N=K.reduce((te,he)=>te*he,1);function D(){const te=1-Math.random(),he=1-Math.random();return Math.sqrt(-2*Math.log(te))*Math.cos(2*Math.PI*he)}return new a("float32",Float32Array.from({length:N},()=>D()),K)}function oe(K,N){if(K.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(K.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(N))throw new Error("The precision must be either 'binary' or 'ubinary'");const D=N==="binary",te=D?"int8":"uint8",he=D?Int8Array:Uint8Array,Ae=K.data,Ie=new he(Ae.length/8);for(let je=0;je0?1:0,Q=Math.floor(je/8),z=je%8;Ie[Q]|=Te<<7-z,D&&z===0&&(Ie[Q]-=128)}return new a(te,Ie,[K.dims[0],K.dims[1]/8])}}),"./src/utils/video.js":((e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>o,load_video:()=>a});var s=t("./src/utils/image.js"),n=t("./src/env.js");class o{constructor(c,p){this.image=c,this.timestamp=p}}class i{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((d,u)=>new o(d,(u+1)/(c.length+1)*p))),this.frames=c,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:c=null,fps:p=null}={}){if(!n.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(c==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],u=document.createElement("video");if(u.crossOrigin="anonymous",u.muted=!0,typeof l=="string")u.src=l;else if(l instanceof Blob)u.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)u.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(I=>u.onloadedmetadata=I),u.seekable.start(0)===u.seekable.end(0)){const T=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(T),await new Promise(b=>u.onloadedmetadata=b)}const f=u.duration;let _,y;c!=null?(_=c,y=c===1?0:f/(c-1)):(y=1/p,_=Math.floor(f/y));let k=[];for(let I=0;I<_;++I)k.push(c===1?f/2:I*y);const w=document.createElement("canvas");w.width=u.videoWidth,w.height=u.videoHeight;const v=w.getContext("2d",{willReadFrequently:!0});for(const I of k){u.currentTime=I,await new Promise(x=>{u.onseeked=x}),v.drawImage(u,0,0,w.width,w.height);const T=v.getImageData(0,0,w.width,w.height),b=new s.RawImage(T.data,w.width,w.height,4),E=new o(b,I);d.push(E)}return u.remove(),new i(d,f)}})},Ow={};function Nt(e){var r=Ow[e];if(r!==void 0)return r.exports;var t=Ow[e]={exports:{}};return i1[e](t,t.exports,Nt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Nt.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var n=Object.create(null);Nt.r(n);var o={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>o[a]=()=>t[a]);return o.default=()=>t,Nt.d(n,o),n}})();Nt.d=(e,r)=>{for(var t in r)Nt.o(r,t)&&!Nt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};Nt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);Nt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{Nt.r(m),Nt.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,ArceeForCausalLM:()=>t.ArceeForCausalLM,ArceeModel:()=>t.ArceeModel,ArceePreTrainedModel:()=>t.ArceePreTrainedModel,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>n.AutoConfig,AutoFeatureExtractor:()=>u.AutoFeatureExtractor,AutoImageProcessor:()=>y.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>v.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>I.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>b.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,DINOv3ConvNextModel:()=>t.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>t.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>_.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>t.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>t.DINOv3ViTPreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EdgeTamModel:()=>t.EdgeTamModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>T.EosTokenCriteria,Ernie4_5ForCausalLM:()=>t.Ernie4_5ForCausalLM,Ernie4_5Model:()=>t.Ernie4_5Model,Ernie4_5PreTrainedModel:()=>t.Ernie4_5PreTrainedModel,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>b.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>b.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>d.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>t.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>t.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>w.Gemma3nProcessor,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GraniteMoeHybridForCausalLM:()=>t.GraniteMoeHybridForCausalLM,GraniteMoeHybridModel:()=>t.GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel:()=>t.GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>T.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,Llama4ForCausalLM:()=>t.Llama4ForCausalLM,Llama4PreTrainedModel:()=>t.Llama4PreTrainedModel,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>w.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>b.LogitsProcessor,LogitsProcessorList:()=>b.LogitsProcessorList,LogitsWarper:()=>b.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>T.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>b.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>b.MinNewTokensLengthLogitsProcessor,Ministral3ForCausalLM:()=>t.Ministral3ForCausalLM,Ministral3Model:()=>t.Ministral3Model,Ministral3PreTrainedModel:()=>t.Ministral3PreTrainedModel,MinistralForCausalLM:()=>t.MinistralForCausalLM,MinistralModel:()=>t.MinistralModel,MinistralPreTrainedModel:()=>t.MinistralPreTrainedModel,Mistral3ForConditionalGeneration:()=>t.Mistral3ForConditionalGeneration,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertDecoderForCausalLM:()=>t.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>t.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>t.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NanoChatForCausalLM:()=>t.NanoChatForCausalLM,NanoChatModel:()=>t.NanoChatModel,NanoChatPreTrainedModel:()=>t.NanoChatPreTrainedModel,NeoBertForMaskedLM:()=>t.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>t.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>t.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>t.NeoBertForTokenClassification,NeoBertModel:()=>t.NeoBertModel,NeoBertPreTrainedModel:()=>t.NeoBertPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>b.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>b.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,ParakeetFeatureExtractor:()=>d.ParakeetFeatureExtractor,ParakeetForCTC:()=>t.ParakeetForCTC,ParakeetPreTrainedModel:()=>t.ParakeetPreTrainedModel,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PixtralImageProcessor:()=>_.PixtralImageProcessor,PixtralProcessor:()=>w.PixtralProcessor,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>n.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>o.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>b.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,Sam2ImageProcessor:()=>_.Sam2ImageProcessor,Sam2ImageSegmentationOutput:()=>t.Sam2ImageSegmentationOutput,Sam2Model:()=>t.Sam2Model,Sam2PreTrainedModel:()=>t.Sam2PreTrainedModel,Sam2Processor:()=>w.Sam2Processor,Sam2VideoProcessor:()=>w.Sam2VideoProcessor,Sam3ImageProcessor:()=>_.Sam3ImageProcessor,Sam3TrackerModel:()=>t.Sam3TrackerModel,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolLM3ForCausalLM:()=>t.SmolLM3ForCausalLM,SmolLM3Model:()=>t.SmolLM3Model,SmolLM3PreTrainedModel:()=>t.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>T.StoppingCriteria,StoppingCriteriaList:()=>T.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SupertonicForConditionalGeneration:()=>t.SupertonicForConditionalGeneration,SupertonicPreTrainedModel:()=>t.SupertonicPreTrainedModel,SuppressTokensAtBeginLogitsProcessor:()=>b.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>b.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>I.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>b.TopKLogitsWarper,TopPLogitsWarper:()=>b.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,VaultGemmaForCausalLM:()=>t.VaultGemmaForCausalLM,VaultGemmaModel:()=>t.VaultGemmaModel,VaultGemmaPreTrainedModel:()=>t.VaultGemmaPreTrainedModel,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,VoxtralForConditionalGeneration:()=>t.VoxtralForConditionalGeneration,VoxtralProcessor:()=>w.VoxtralProcessor,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>I.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>b.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>l.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>n.getCacheShapes,hamming:()=>o.hamming,hanning:()=>o.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>l.matmul,max:()=>c.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>o.mel_filter_bank,min:()=>c.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>c.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,randn:()=>l.randn,read_audio:()=>o.read_audio,rfft:()=>l.rfft,round:()=>c.round,slice:()=>l.slice,softmax:()=>c.softmax,spectrogram:()=>o.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>o.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Nt("./src/env.js"),r=Nt("./src/pipelines.js"),t=Nt("./src/models.js"),s=Nt("./src/tokenizers.js"),n=Nt("./src/configs.js"),o=Nt("./src/utils/audio.js"),i=Nt("./src/utils/image.js"),a=Nt("./src/utils/video.js"),l=Nt("./src/utils/tensor.js"),c=Nt("./src/utils/maths.js"),p=Nt("./src/base/feature_extraction_utils.js"),d=Nt("./src/models/feature_extractors.js"),u=Nt("./src/models/auto/feature_extraction_auto.js"),f=Nt("./src/base/image_processors_utils.js"),_=Nt("./src/models/image_processors.js"),y=Nt("./src/models/auto/image_processing_auto.js"),k=Nt("./src/base/processing_utils.js"),w=Nt("./src/models/processors.js"),v=Nt("./src/models/auto/processing_auto.js"),I=Nt("./src/generation/streamers.js"),T=Nt("./src/generation/stopping_criteria.js"),b=Nt("./src/generation/logits_process.js")})();m.ASTFeatureExtractor;m.ASTForAudioClassification;m.ASTModel;m.ASTPreTrainedModel;m.AlbertForMaskedLM;m.AlbertForQuestionAnswering;m.AlbertForSequenceClassification;m.AlbertModel;m.AlbertPreTrainedModel;m.AlbertTokenizer;m.ArceeForCausalLM;m.ArceeModel;m.ArceePreTrainedModel;m.AudioClassificationPipeline;m.AutoConfig;m.AutoFeatureExtractor;m.AutoImageProcessor;m.AutoModel;m.AutoModelForAudioClassification;m.AutoModelForAudioFrameClassification;m.AutoModelForAudioTextToText;m.AutoModelForCTC;m.AutoModelForCausalLM;m.AutoModelForDepthEstimation;m.AutoModelForDocumentQuestionAnswering;m.AutoModelForImageClassification;m.AutoModelForImageFeatureExtraction;m.AutoModelForImageMatting;m.AutoModelForImageSegmentation;m.AutoModelForImageTextToText;m.AutoModelForImageToImage;m.AutoModelForMaskGeneration;m.AutoModelForMaskedLM;m.AutoModelForNormalEstimation;m.AutoModelForObjectDetection;m.AutoModelForPoseEstimation;m.AutoModelForQuestionAnswering;m.AutoModelForSemanticSegmentation;m.AutoModelForSeq2SeqLM;m.AutoModelForSequenceClassification;m.AutoModelForSpeechSeq2Seq;m.AutoModelForTextToSpectrogram;m.AutoModelForTextToWaveform;m.AutoModelForTokenClassification;m.AutoModelForUniversalSegmentation;m.AutoModelForVision2Seq;m.AutoModelForXVector;m.AutoModelForZeroShotObjectDetection;m.AutoProcessor;m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline;m.BackgroundRemovalPipeline;m.BartForConditionalGeneration;m.BartForSequenceClassification;m.BartModel;m.BartPretrainedModel;m.BartTokenizer;m.BaseModelOutput;m.BaseStreamer;m.BeitFeatureExtractor;m.BeitForImageClassification;m.BeitModel;m.BeitPreTrainedModel;m.BertForMaskedLM;m.BertForQuestionAnswering;m.BertForSequenceClassification;m.BertForTokenClassification;m.BertModel;m.BertPreTrainedModel;m.BertTokenizer;m.BitImageProcessor;m.BlenderbotForConditionalGeneration;m.BlenderbotModel;m.BlenderbotPreTrainedModel;m.BlenderbotSmallForConditionalGeneration;m.BlenderbotSmallModel;m.BlenderbotSmallPreTrainedModel;m.BlenderbotSmallTokenizer;m.BlenderbotTokenizer;m.BloomForCausalLM;m.BloomModel;m.BloomPreTrainedModel;m.BloomTokenizer;m.CLIPFeatureExtractor;m.CLIPImageProcessor;m.CLIPModel;m.CLIPPreTrainedModel;m.CLIPSegForImageSegmentation;m.CLIPSegModel;m.CLIPSegPreTrainedModel;m.CLIPTextModel;m.CLIPTextModelWithProjection;m.CLIPTokenizer;m.CLIPVisionModel;m.CLIPVisionModelWithProjection;m.CamembertForMaskedLM;m.CamembertForQuestionAnswering;m.CamembertForSequenceClassification;m.CamembertForTokenClassification;m.CamembertModel;m.CamembertPreTrainedModel;m.CamembertTokenizer;m.CausalLMOutput;m.CausalLMOutputWithPast;m.ChineseCLIPFeatureExtractor;m.ChineseCLIPModel;m.ChineseCLIPPreTrainedModel;m.ClapAudioModelWithProjection;m.ClapFeatureExtractor;m.ClapModel;m.ClapPreTrainedModel;m.ClapTextModelWithProjection;m.ClassifierFreeGuidanceLogitsProcessor;m.CodeGenForCausalLM;m.CodeGenModel;m.CodeGenPreTrainedModel;m.CodeGenTokenizer;m.CodeLlamaTokenizer;m.CohereForCausalLM;m.CohereModel;m.CoherePreTrainedModel;m.CohereTokenizer;m.ConvBertForMaskedLM;m.ConvBertForQuestionAnswering;m.ConvBertForSequenceClassification;m.ConvBertForTokenClassification;m.ConvBertModel;m.ConvBertPreTrainedModel;m.ConvBertTokenizer;m.ConvNextFeatureExtractor;m.ConvNextForImageClassification;m.ConvNextImageProcessor;m.ConvNextModel;m.ConvNextPreTrainedModel;m.ConvNextV2ForImageClassification;m.ConvNextV2Model;m.ConvNextV2PreTrainedModel;m.DFineForObjectDetection;m.DFineModel;m.DFinePreTrainedModel;m.DINOv3ConvNextModel;m.DINOv3ConvNextPreTrainedModel;m.DINOv3ViTImageProcessor;m.DINOv3ViTModel;m.DINOv3ViTPreTrainedModel;m.DPTFeatureExtractor;m.DPTForDepthEstimation;m.DPTImageProcessor;m.DPTModel;m.DPTPreTrainedModel;m.DacDecoderModel;m.DacDecoderOutput;m.DacEncoderModel;m.DacEncoderOutput;m.DacFeatureExtractor;m.DacModel;m.DacPreTrainedModel;m.DataTypeMap;m.DebertaForMaskedLM;m.DebertaForQuestionAnswering;m.DebertaForSequenceClassification;m.DebertaForTokenClassification;m.DebertaModel;m.DebertaPreTrainedModel;m.DebertaTokenizer;m.DebertaV2ForMaskedLM;m.DebertaV2ForQuestionAnswering;m.DebertaV2ForSequenceClassification;m.DebertaV2ForTokenClassification;m.DebertaV2Model;m.DebertaV2PreTrainedModel;m.DebertaV2Tokenizer;m.DecisionTransformerModel;m.DecisionTransformerPreTrainedModel;m.DeiTFeatureExtractor;m.DeiTForImageClassification;m.DeiTImageProcessor;m.DeiTModel;m.DeiTPreTrainedModel;m.DepthAnythingForDepthEstimation;m.DepthAnythingPreTrainedModel;m.DepthEstimationPipeline;m.DepthProForDepthEstimation;m.DepthProPreTrainedModel;m.DetrFeatureExtractor;m.DetrForObjectDetection;m.DetrForSegmentation;m.DetrImageProcessor;m.DetrModel;m.DetrObjectDetectionOutput;m.DetrPreTrainedModel;m.DetrSegmentationOutput;m.Dinov2ForImageClassification;m.Dinov2Model;m.Dinov2PreTrainedModel;m.Dinov2WithRegistersForImageClassification;m.Dinov2WithRegistersModel;m.Dinov2WithRegistersPreTrainedModel;m.DistilBertForMaskedLM;m.DistilBertForQuestionAnswering;m.DistilBertForSequenceClassification;m.DistilBertForTokenClassification;m.DistilBertModel;m.DistilBertPreTrainedModel;m.DistilBertTokenizer;m.DocumentQuestionAnsweringPipeline;m.DonutFeatureExtractor;m.DonutImageProcessor;m.DonutSwinModel;m.DonutSwinPreTrainedModel;m.EdgeTamModel;m.EfficientNetForImageClassification;m.EfficientNetImageProcessor;m.EfficientNetModel;m.EfficientNetPreTrainedModel;m.ElectraForMaskedLM;m.ElectraForQuestionAnswering;m.ElectraForSequenceClassification;m.ElectraForTokenClassification;m.ElectraModel;m.ElectraPreTrainedModel;m.ElectraTokenizer;m.EncodecFeatureExtractor;m.EosTokenCriteria;m.Ernie4_5ForCausalLM;m.Ernie4_5Model;m.Ernie4_5PreTrainedModel;m.EsmForMaskedLM;m.EsmForSequenceClassification;m.EsmForTokenClassification;m.EsmModel;m.EsmPreTrainedModel;m.EsmTokenizer;m.ExaoneForCausalLM;m.ExaoneModel;m.ExaonePreTrainedModel;m.FFT;m.FalconForCausalLM;m.FalconModel;m.FalconPreTrainedModel;m.FalconTokenizer;m.FastViTForImageClassification;m.FastViTModel;m.FastViTPreTrainedModel;m.FeatureExtractionPipeline;m.FeatureExtractor;m.FillMaskPipeline;m.Florence2ForConditionalGeneration;m.Florence2PreTrainedModel;m.Florence2Processor;m.ForcedBOSTokenLogitsProcessor;m.ForcedEOSTokenLogitsProcessor;m.GLPNFeatureExtractor;m.GLPNForDepthEstimation;m.GLPNModel;m.GLPNPreTrainedModel;m.GPT2LMHeadModel;m.GPT2Model;m.GPT2PreTrainedModel;m.GPT2Tokenizer;m.GPTBigCodeForCausalLM;m.GPTBigCodeModel;m.GPTBigCodePreTrainedModel;m.GPTJForCausalLM;m.GPTJModel;m.GPTJPreTrainedModel;m.GPTNeoForCausalLM;m.GPTNeoModel;m.GPTNeoPreTrainedModel;m.GPTNeoXForCausalLM;m.GPTNeoXModel;m.GPTNeoXPreTrainedModel;m.GPTNeoXTokenizer;m.Gemma2ForCausalLM;m.Gemma2Model;m.Gemma2PreTrainedModel;m.Gemma3ForCausalLM;m.Gemma3Model;m.Gemma3PreTrainedModel;m.Gemma3nAudioFeatureExtractor;m.Gemma3nForConditionalGeneration;m.Gemma3nPreTrainedModel;m.Gemma3nProcessor;m.GemmaForCausalLM;m.GemmaModel;m.GemmaPreTrainedModel;m.GemmaTokenizer;m.GlmForCausalLM;m.GlmModel;m.GlmPreTrainedModel;m.GraniteForCausalLM;m.GraniteModel;m.GraniteMoeHybridForCausalLM;m.GraniteMoeHybridModel;m.GraniteMoeHybridPreTrainedModel;m.GranitePreTrainedModel;m.Grok1Tokenizer;m.GroundingDinoForObjectDetection;m.GroundingDinoImageProcessor;m.GroundingDinoPreTrainedModel;m.GroundingDinoProcessor;m.GroupViTModel;m.GroupViTPreTrainedModel;m.HeliumForCausalLM;m.HeliumModel;m.HeliumPreTrainedModel;m.HerbertTokenizer;m.HieraForImageClassification;m.HieraModel;m.HieraPreTrainedModel;m.HubertForCTC;m.HubertForSequenceClassification;m.HubertModel;m.HubertPreTrainedModel;m.IJepaForImageClassification;m.IJepaModel;m.IJepaPreTrainedModel;m.Idefics3ForConditionalGeneration;m.Idefics3ImageProcessor;m.Idefics3PreTrainedModel;m.Idefics3Processor;m.ImageClassificationPipeline;m.ImageFeatureExtractionPipeline;m.ImageFeatureExtractor;m.ImageMattingOutput;m.ImageProcessor;m.ImageSegmentationPipeline;m.ImageToImagePipeline;m.ImageToTextPipeline;m.InterruptableStoppingCriteria;m.JAISLMHeadModel;m.JAISModel;m.JAISPreTrainedModel;m.JinaCLIPImageProcessor;m.JinaCLIPModel;m.JinaCLIPPreTrainedModel;m.JinaCLIPProcessor;m.JinaCLIPTextModel;m.JinaCLIPVisionModel;m.Lfm2ForCausalLM;m.Lfm2Model;m.Lfm2PreTrainedModel;m.LiteWhisperForConditionalGeneration;m.Llama4ForCausalLM;m.Llama4PreTrainedModel;m.LlamaForCausalLM;m.LlamaModel;m.LlamaPreTrainedModel;m.LlamaTokenizer;m.LlavaForConditionalGeneration;m.LlavaOnevisionForConditionalGeneration;m.LlavaOnevisionImageProcessor;m.LlavaPreTrainedModel;m.LlavaProcessor;m.LlavaQwen2ForCausalLM;m.LogitsProcessor;m.LogitsProcessorList;m.LogitsWarper;m.LongT5ForConditionalGeneration;m.LongT5Model;m.LongT5PreTrainedModel;m.M2M100ForConditionalGeneration;m.M2M100Model;m.M2M100PreTrainedModel;m.M2M100Tokenizer;m.MBart50Tokenizer;m.MBartForCausalLM;m.MBartForConditionalGeneration;m.MBartForSequenceClassification;m.MBartModel;m.MBartPreTrainedModel;m.MBartTokenizer;m.MPNetForMaskedLM;m.MPNetForQuestionAnswering;m.MPNetForSequenceClassification;m.MPNetForTokenClassification;m.MPNetModel;m.MPNetPreTrainedModel;m.MPNetTokenizer;m.MT5ForConditionalGeneration;m.MT5Model;m.MT5PreTrainedModel;m.MarianMTModel;m.MarianModel;m.MarianPreTrainedModel;m.MarianTokenizer;m.Mask2FormerImageProcessor;m.MaskFormerFeatureExtractor;m.MaskFormerForInstanceSegmentation;m.MaskFormerImageProcessor;m.MaskFormerModel;m.MaskFormerPreTrainedModel;m.MaskedLMOutput;m.MaxLengthCriteria;m.Metric3DForDepthEstimation;m.Metric3DPreTrainedModel;m.Metric3Dv2ForDepthEstimation;m.Metric3Dv2PreTrainedModel;m.MgpstrForSceneTextRecognition;m.MgpstrModelOutput;m.MgpstrPreTrainedModel;m.MgpstrProcessor;m.MgpstrTokenizer;m.MimiDecoderModel;m.MimiDecoderOutput;m.MimiEncoderModel;m.MimiEncoderOutput;m.MimiModel;m.MimiPreTrainedModel;m.MinLengthLogitsProcessor;m.MinNewTokensLengthLogitsProcessor;m.Ministral3ForCausalLM;m.Ministral3Model;m.Ministral3PreTrainedModel;m.MinistralForCausalLM;m.MinistralModel;m.MinistralPreTrainedModel;m.Mistral3ForConditionalGeneration;m.MistralForCausalLM;m.MistralModel;m.MistralPreTrainedModel;m.MobileBertForMaskedLM;m.MobileBertForQuestionAnswering;m.MobileBertForSequenceClassification;m.MobileBertModel;m.MobileBertPreTrainedModel;m.MobileBertTokenizer;m.MobileLLMForCausalLM;m.MobileLLMModel;m.MobileLLMPreTrainedModel;m.MobileNetV1FeatureExtractor;m.MobileNetV1ForImageClassification;m.MobileNetV1ForSemanticSegmentation;m.MobileNetV1ImageProcessor;m.MobileNetV1Model;m.MobileNetV1PreTrainedModel;m.MobileNetV2FeatureExtractor;m.MobileNetV2ForImageClassification;m.MobileNetV2ForSemanticSegmentation;m.MobileNetV2ImageProcessor;m.MobileNetV2Model;m.MobileNetV2PreTrainedModel;m.MobileNetV3FeatureExtractor;m.MobileNetV3ForImageClassification;m.MobileNetV3ForSemanticSegmentation;m.MobileNetV3ImageProcessor;m.MobileNetV3Model;m.MobileNetV3PreTrainedModel;m.MobileNetV4FeatureExtractor;m.MobileNetV4ForImageClassification;m.MobileNetV4ForSemanticSegmentation;m.MobileNetV4ImageProcessor;m.MobileNetV4Model;m.MobileNetV4PreTrainedModel;m.MobileViTFeatureExtractor;m.MobileViTForImageClassification;m.MobileViTImageProcessor;m.MobileViTModel;m.MobileViTPreTrainedModel;m.MobileViTV2ForImageClassification;m.MobileViTV2Model;m.MobileViTV2PreTrainedModel;m.ModelOutput;m.ModernBertDecoderForCausalLM;m.ModernBertDecoderModel;m.ModernBertDecoderPreTrainedModel;m.ModernBertForMaskedLM;m.ModernBertForSequenceClassification;m.ModernBertForTokenClassification;m.ModernBertModel;m.ModernBertPreTrainedModel;m.Moondream1ForConditionalGeneration;m.MoonshineFeatureExtractor;m.MoonshineForConditionalGeneration;m.MoonshineModel;m.MoonshinePreTrainedModel;m.MoonshineProcessor;m.MptForCausalLM;m.MptModel;m.MptPreTrainedModel;m.MultiModalityCausalLM;m.MultiModalityPreTrainedModel;m.MusicgenForCausalLM;m.MusicgenForConditionalGeneration;m.MusicgenModel;m.MusicgenPreTrainedModel;m.NanoChatForCausalLM;m.NanoChatModel;m.NanoChatPreTrainedModel;m.NeoBertForMaskedLM;m.NeoBertForQuestionAnswering;m.NeoBertForSequenceClassification;m.NeoBertForTokenClassification;m.NeoBertModel;m.NeoBertPreTrainedModel;m.NllbTokenizer;m.NoBadWordsLogitsProcessor;m.NoRepeatNGramLogitsProcessor;m.NomicBertModel;m.NomicBertPreTrainedModel;m.NougatImageProcessor;m.NougatTokenizer;m.OPTForCausalLM;m.OPTModel;m.OPTPreTrainedModel;m.ObjectDetectionPipeline;m.Olmo2ForCausalLM;m.Olmo2Model;m.Olmo2PreTrainedModel;m.OlmoForCausalLM;m.OlmoModel;m.OlmoPreTrainedModel;m.OpenELMForCausalLM;m.OpenELMModel;m.OpenELMPreTrainedModel;m.OwlViTFeatureExtractor;m.OwlViTForObjectDetection;m.OwlViTImageProcessor;m.OwlViTModel;m.OwlViTPreTrainedModel;m.OwlViTProcessor;m.Owlv2ForObjectDetection;m.Owlv2ImageProcessor;m.Owlv2Model;m.Owlv2PreTrainedModel;m.PaliGemmaForConditionalGeneration;m.PaliGemmaPreTrainedModel;m.PaliGemmaProcessor;m.ParakeetFeatureExtractor;m.ParakeetForCTC;m.ParakeetPreTrainedModel;m.PatchTSMixerForPrediction;m.PatchTSMixerModel;m.PatchTSMixerPreTrainedModel;m.PatchTSTForPrediction;m.PatchTSTModel;m.PatchTSTPreTrainedModel;m.Phi3ForCausalLM;m.Phi3Model;m.Phi3PreTrainedModel;m.Phi3VForCausalLM;m.Phi3VImageProcessor;m.Phi3VPreTrainedModel;m.Phi3VProcessor;m.PhiForCausalLM;m.PhiModel;m.PhiPreTrainedModel;m.Pipeline;m.PixtralImageProcessor;m.PixtralProcessor;m.PreTrainedModel;m.PreTrainedTokenizer;m.PretrainedConfig;m.PretrainedMixin;m.Processor;m.PvtForImageClassification;m.PvtImageProcessor;m.PvtModel;m.PvtPreTrainedModel;m.PyAnnoteFeatureExtractor;m.PyAnnoteForAudioFrameClassification;m.PyAnnoteModel;m.PyAnnotePreTrainedModel;m.PyAnnoteProcessor;m.QuestionAnsweringModelOutput;m.QuestionAnsweringPipeline;m.Qwen2ForCausalLM;m.Qwen2Model;m.Qwen2PreTrainedModel;m.Qwen2Tokenizer;m.Qwen2VLForConditionalGeneration;m.Qwen2VLImageProcessor;m.Qwen2VLPreTrainedModel;m.Qwen2VLProcessor;m.Qwen3ForCausalLM;m.Qwen3Model;m.Qwen3PreTrainedModel;m.RFDetrForObjectDetection;m.RFDetrModel;m.RFDetrObjectDetectionOutput;m.RFDetrPreTrainedModel;m.RTDetrForObjectDetection;m.RTDetrImageProcessor;m.RTDetrModel;m.RTDetrObjectDetectionOutput;m.RTDetrPreTrainedModel;m.RTDetrV2ForObjectDetection;m.RTDetrV2Model;m.RTDetrV2ObjectDetectionOutput;m.RTDetrV2PreTrainedModel;m.RawAudio;m.RawImage;m.RawVideo;m.RawVideoFrame;m.RepetitionPenaltyLogitsProcessor;m.ResNetForImageClassification;m.ResNetModel;m.ResNetPreTrainedModel;m.RoFormerForMaskedLM;m.RoFormerForQuestionAnswering;m.RoFormerForSequenceClassification;m.RoFormerForTokenClassification;m.RoFormerModel;m.RoFormerPreTrainedModel;m.RoFormerTokenizer;m.RobertaForMaskedLM;m.RobertaForQuestionAnswering;m.RobertaForSequenceClassification;m.RobertaForTokenClassification;m.RobertaModel;m.RobertaPreTrainedModel;m.RobertaTokenizer;m.Sam2ImageProcessor;m.Sam2ImageSegmentationOutput;m.Sam2Model;m.Sam2PreTrainedModel;m.Sam2Processor;m.Sam2VideoProcessor;m.Sam3ImageProcessor;m.Sam3TrackerModel;m.SamImageProcessor;m.SamImageSegmentationOutput;m.SamModel;m.SamPreTrainedModel;m.SamProcessor;m.SapiensForDepthEstimation;m.SapiensForNormalEstimation;m.SapiensForSemanticSegmentation;m.SapiensPreTrainedModel;m.SeamlessM4TFeatureExtractor;m.SegformerFeatureExtractor;m.SegformerForImageClassification;m.SegformerForSemanticSegmentation;m.SegformerImageProcessor;m.SegformerModel;m.SegformerPreTrainedModel;m.Seq2SeqLMOutput;m.SequenceClassifierOutput;m.SiglipImageProcessor;m.SiglipModel;m.SiglipPreTrainedModel;m.SiglipTextModel;m.SiglipTokenizer;m.SiglipVisionModel;m.SmolLM3ForCausalLM;m.SmolLM3Model;m.SmolLM3PreTrainedModel;m.SmolVLMForConditionalGeneration;m.SmolVLMImageProcessor;m.SmolVLMProcessor;m.SnacDecoderModel;m.SnacEncoderModel;m.SnacFeatureExtractor;m.SnacModel;m.SnacPreTrainedModel;m.SpeechT5FeatureExtractor;m.SpeechT5ForSpeechToText;m.SpeechT5ForTextToSpeech;m.SpeechT5HifiGan;m.SpeechT5Model;m.SpeechT5PreTrainedModel;m.SpeechT5Processor;m.SpeechT5Tokenizer;m.SqueezeBertForMaskedLM;m.SqueezeBertForQuestionAnswering;m.SqueezeBertForSequenceClassification;m.SqueezeBertModel;m.SqueezeBertPreTrainedModel;m.SqueezeBertTokenizer;m.StableLmForCausalLM;m.StableLmModel;m.StableLmPreTrainedModel;m.Starcoder2ForCausalLM;m.Starcoder2Model;m.Starcoder2PreTrainedModel;m.StoppingCriteria;m.StoppingCriteriaList;m.StyleTextToSpeech2Model;m.StyleTextToSpeech2PreTrainedModel;m.SummarizationPipeline;m.SupertonicForConditionalGeneration;m.SupertonicPreTrainedModel;m.SuppressTokensAtBeginLogitsProcessor;m.Swin2SRForImageSuperResolution;m.Swin2SRImageProcessor;m.Swin2SRModel;m.Swin2SRPreTrainedModel;m.SwinForImageClassification;m.SwinForSemanticSegmentation;m.SwinModel;m.SwinPreTrainedModel;m.T5ForConditionalGeneration;m.T5Model;m.T5PreTrainedModel;m.T5Tokenizer;m.TableTransformerForObjectDetection;m.TableTransformerModel;m.TableTransformerObjectDetectionOutput;m.TableTransformerPreTrainedModel;m.TemperatureLogitsWarper;m.Tensor;m.Text2TextGenerationPipeline;m.TextClassificationPipeline;m.TextGenerationPipeline;m.TextStreamer;m.TextToAudioPipeline;m.TokenClassificationPipeline;m.TokenClassifierOutput;m.TokenizerModel;m.TopKLogitsWarper;m.TopPLogitsWarper;m.TrOCRForCausalLM;m.TrOCRPreTrainedModel;m.TranslationPipeline;m.UltravoxModel;m.UltravoxPreTrainedModel;m.UltravoxProcessor;m.UniSpeechForCTC;m.UniSpeechForSequenceClassification;m.UniSpeechModel;m.UniSpeechPreTrainedModel;m.UniSpeechSatForAudioFrameClassification;m.UniSpeechSatForCTC;m.UniSpeechSatForSequenceClassification;m.UniSpeechSatModel;m.UniSpeechSatPreTrainedModel;m.VLChatProcessor;m.VLMImageProcessor;m.VaultGemmaForCausalLM;m.VaultGemmaModel;m.VaultGemmaPreTrainedModel;m.ViTFeatureExtractor;m.ViTForImageClassification;m.ViTImageProcessor;m.ViTMAEModel;m.ViTMAEPreTrainedModel;m.ViTMSNForImageClassification;m.ViTMSNModel;m.ViTMSNPreTrainedModel;m.ViTModel;m.ViTPreTrainedModel;m.VisionEncoderDecoderModel;m.VitMatteForImageMatting;m.VitMatteImageProcessor;m.VitMattePreTrainedModel;m.VitPoseForPoseEstimation;m.VitPoseImageProcessor;m.VitPosePreTrainedModel;m.VitsModel;m.VitsModelOutput;m.VitsPreTrainedModel;m.VitsTokenizer;m.VoxtralForConditionalGeneration;m.VoxtralProcessor;m.Wav2Vec2BertForCTC;m.Wav2Vec2BertForSequenceClassification;m.Wav2Vec2BertModel;m.Wav2Vec2BertPreTrainedModel;m.Wav2Vec2CTCTokenizer;m.Wav2Vec2FeatureExtractor;m.Wav2Vec2ForAudioFrameClassification;m.Wav2Vec2ForCTC;m.Wav2Vec2ForSequenceClassification;m.Wav2Vec2Model;m.Wav2Vec2PreTrainedModel;m.Wav2Vec2Processor;m.Wav2Vec2ProcessorWithLM;m.WavLMForAudioFrameClassification;m.WavLMForCTC;m.WavLMForSequenceClassification;m.WavLMForXVector;m.WavLMModel;m.WavLMPreTrainedModel;m.WeSpeakerFeatureExtractor;m.WeSpeakerResNetModel;m.WeSpeakerResNetPreTrainedModel;m.WhisperFeatureExtractor;m.WhisperForConditionalGeneration;m.WhisperModel;m.WhisperPreTrainedModel;m.WhisperProcessor;m.WhisperTextStreamer;m.WhisperTimeStampLogitsProcessor;m.WhisperTokenizer;m.XLMForQuestionAnswering;m.XLMForSequenceClassification;m.XLMForTokenClassification;m.XLMModel;m.XLMPreTrainedModel;m.XLMRobertaForMaskedLM;m.XLMRobertaForQuestionAnswering;m.XLMRobertaForSequenceClassification;m.XLMRobertaForTokenClassification;m.XLMRobertaModel;m.XLMRobertaPreTrainedModel;m.XLMRobertaTokenizer;m.XLMTokenizer;m.XLMWithLMHeadModel;m.XVectorOutput;m.YolosFeatureExtractor;m.YolosForObjectDetection;m.YolosImageProcessor;m.YolosModel;m.YolosObjectDetectionOutput;m.YolosPreTrainedModel;m.ZeroShotAudioClassificationPipeline;m.ZeroShotClassificationPipeline;m.ZeroShotImageClassificationPipeline;m.ZeroShotObjectDetectionPipeline;m.bankers_round;m.cat;m.cos_sim;m.dot;m.dynamic_time_warping;var Mi=m.env;m.full;m.full_like;m.getCacheShapes;m.hamming;m.hanning;m.interpolate;m.interpolate_4d;m.interpolate_data;m.is_chinese_char;m.layer_norm;m.load_image;m.load_video;m.log_softmax;m.magnitude;m.matmul;m.max;m.mean;m.mean_pooling;m.medianFilter;m.mel_filter_bank;m.min;m.ones;m.ones_like;m.permute;m.permute_data;var l1=m.pipeline;m.quantize_embeddings;m.rand;m.randn;m.read_audio;m.rfft;m.round;m.slice;m.softmax;m.spectrogram;m.stack;m.std_mean;m.topk;m.window_function;m.zeros;m.zeros_like;const yv=[{id:"whisper-tiny-multilingual-wasm",label:"Whisper Tiny (multilingual)",modelId:"onnx-community/whisper-tiny",revision:"ff4177021cc41f7db950912b73ea4fdf7d01d8e7",multilingual:!0,approximateDownloadBytes:77e6,devices:["wasm","webgpu"],dtypeByDevice:{wasm:"q8",webgpu:"fp32"},chunkLengthSeconds:30,strideLengthSeconds:5,maxDurationSeconds:10800}];yv[0].id;function wi(e){return yv.find(r=>r.id===e)}Mi.allowLocalModels=!1;Mi.useBrowserCache=!0;Mi.backends.onnx.wasm&&(Mi.backends.onnx.wasm.wasmPaths=void 0);const c1="0.1.0-prototype",u1="c53387ee8485",vv="3.x";let Vr=null,oo=null,ea=new Set;function cs(e){self.postMessage(e)}function Gs(e,r){ea.has(e)||cs({protocol:1,type:"PROGRESS",requestId:e,progress:r})}function Wu(e,r){if(ea.has(e)){cs({protocol:1,type:"CANCELLED",requestId:e});return}cs({protocol:1,type:"ERROR",requestId:e,error:r})}function bi(e={}){return{appVersion:c1,buildId:u1,transformersVersion:vv,cacheState:"unknown",...e}}function ta(e){return ea.has(e)}async function d1(e,r,t){const s=wi(e);if(!s)throw xs("PROFILE_UNKNOWN","prepare",!1);const n=performance.now();let o="wasm",i;Gs(t,{phase:"manifest",status:"completed",ratio:1}),Gs(t,{phase:"runtime-init",status:"started"});const a=typeof navigator<"u"&&"gpu"in navigator,l=r==="webgpu"||r==="auto"&&a;if(r==="webgpu"&&!a)throw xs("RUNTIME_UNSUPPORTED","prepare",!0,!0);const c=async u=>{const f=s.dtypeByDevice[u]??(u==="webgpu"?"fp32":"q8");return l1("automatic-speech-recognition",s.modelId,{revision:s.revision,device:u,dtype:f,progress_callback:_=>{ta(t)||(_.status==="progress"||_.status==="download")&&Gs(t,{phase:"download",status:"running",fileId:_.file,loadedBytes:_.loaded,totalBytes:_.total,ratio:typeof _.progress=="number"?_.progress/100:_.total?(_.loaded??0)/_.total:void 0})}})};let p;if(l)try{Gs(t,{phase:"model-init",status:"started"}),p=await c("webgpu"),o="webgpu"}catch{i="WEBGPU_INIT_FAILED",Gs(t,{phase:"runtime-init",status:"started"}),p=await c("wasm"),o="wasm"}else Gs(t,{phase:"model-init",status:"started"}),p=await c("wasm"),o="wasm";if(ta(t))throw xs("CANCELLED","prepare",!0);return Gs(t,{phase:"warmup",status:"completed",ratio:1}),{fingerprint:[s.modelId,s.revision,o,s.dtypeByDevice[o]??"default",vv].join("|"),pipeline:p,effectiveRuntime:o,profileId:s.id,modelRevision:s.revision,preparationMs:Math.round(performance.now()-n),fallbackReasonCode:i}}async function xv(e,r,t){const s=wi(e);if(!s)throw xs("PROFILE_UNKNOWN","prepare",!1);const n=r==="wasm"?"wasm":r==="webgpu"?"webgpu":Vr?.effectiveRuntime??"auto",o=`${s.modelId}|${s.revision}|`;return Vr&&Vr.profileId===e&&Vr.fingerprint.startsWith(o)&&(r==="auto"||Vr.effectiveRuntime===n||r==="webgpu"&&Vr.effectiveRuntime==="wasm"&&Vr.fallbackReasonCode)?Vr:(oo||(oo=d1(e,r,t).then(i=>(Vr=i,oo=null,i)).catch(i=>{throw oo=null,Vr=null,i})),oo)}function p1(e,r){const t=[],s=e??{},n=(s.text??"").trim(),o=[];if(Array.isArray(s.chunks))for(const i of s.chunks){const a=i.timestamp?.[0],l=i.timestamp?.[1];typeof a!="number"||typeof l!="number"||!Number.isFinite(a)||!Number.isFinite(l)||li.text).join(" ").trim(),segments:o,durationSeconds:r,warnings:t}}function xs(e,r,t,s){return{code:e,phase:r,recoverable:t,fallbackAvailable:s}}function m1(e){if(!(e instanceof Float32Array)||e.length===0)throw xs("AUDIO_INVALID","infer",!0);for(let r=0;r{const r=e.data;if(!r||r.protocol!==1){cs({protocol:1,type:"ERROR",requestId:r?.requestId??"unknown",error:xs("PROTOCOL_UNSUPPORTED","prepare",!1)});return}switch(r.type){case"PREPARE":h1(r);break;case"TRANSCRIBE":_1(r);break;case"CANCEL":ea.add(r.targetRequestId),cs({protocol:1,type:"CANCELLED",requestId:r.requestId});break;case"DISPOSE":Vr=null,oo=null,ea=new Set,cs({protocol:1,type:"DIAGNOSTICS",requestId:r.requestId,diagnostics:bi()});break;case"GET_DIAGNOSTICS":cs({protocol:1,type:"DIAGNOSTICS",requestId:r.requestId,diagnostics:bi({modelProfileId:Vr?.profileId,modelRevision:Vr?.modelRevision,effectiveRuntime:Vr?.effectiveRuntime,preparationMs:Vr?.preparationMs,fallbackReasonCode:Vr?.fallbackReasonCode})});break;default:Wu(r.requestId,xs("INTERNAL","prepare",!1))}}; diff --git a/static/utility-apps/whisper-transcriber/build-info.json b/static/utility-apps/whisper-transcriber/build-info.json index 84a651e..759126a 100644 --- a/static/utility-apps/whisper-transcriber/build-info.json +++ b/static/utility-apps/whisper-transcriber/build-info.json @@ -1,4 +1,5 @@ { "version": "0.1.0-prototype", - "buildId": "0d8c0a8b93e2" + "buildId": "c53387ee8485", + "buildTime": "2026-07-21T14:03:58.052Z" } diff --git a/static/utility-apps/whisper-transcriber/index.html b/static/utility-apps/whisper-transcriber/index.html index 65ba537..8b21e22 100644 --- a/static/utility-apps/whisper-transcriber/index.html +++ b/static/utility-apps/whisper-transcriber/index.html @@ -8,7 +8,7 @@ content="Private browser speech-to-text. Audio stays on your device." /> Whisper Transcriber - + diff --git a/static/utility-apps/whisper-transcriber/manifest.json b/static/utility-apps/whisper-transcriber/manifest.json index 237da77..8500027 100644 --- a/static/utility-apps/whisper-transcriber/manifest.json +++ b/static/utility-apps/whisper-transcriber/manifest.json @@ -1,23 +1,23 @@ { "name": "whisper-transcriber", "version": "0.1.0-prototype", - "buildId": "0d8c0a8b93e2", - "buildTime": "2026-07-21T11:21:08.856Z", + "buildId": "c53387ee8485", + "buildTime": "2026-07-21T14:03:58.052Z", "entry": "app.html", "assets": [ - "assets/index-B5C8PNiW.js", "assets/index-BWGSeFCx.css", + "assets/index-DA9_-avd.js", "assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm", - "assets/whisper.worker-CA5aZLsj.js", + "assets/whisper.worker-ewvZ1MXN.js", "build-info.json" ], "checksums": { - "assets/index-B5C8PNiW.js": "09b2ad1591b54aa369e7b95594a885f8f613cb766d2466369d3c606c69db6e71", "assets/index-BWGSeFCx.css": "ee3f659b1fd58be6a87f3cce8818dbaed8bbdc0a24d55ac26728081e77303450", + "assets/index-DA9_-avd.js": "d592c23f5aacd987250533abc1175b46e136e7bc65ad3debb5be60eb6252b555", "assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm": "c46655e8a94afc45338d4cb2b840475f88e5012d524509916e505079c00bfa39", - "assets/whisper.worker-CA5aZLsj.js": "0cadb55011ceb1263a570aad4b6c588b17f17af9430466a0a4a69277e1a830dc", - "build-info.json": "16c1ad1b392cc798e8d073cc61dd07dc5791534391966a276fa9ce6976781edb", - "app.html": "2aabc82b640868b67b619de781e7a8616d24fbfab2666005ef9a490b578ddcdb", - "index.html": "2aabc82b640868b67b619de781e7a8616d24fbfab2666005ef9a490b578ddcdb" + "assets/whisper.worker-ewvZ1MXN.js": "18a0e417408fda84c93ee1729cfa2119b28d51440cac9fc7e4ca4791bda6b48e", + "build-info.json": "19d9b68d5db1bf4d937cd87126c5379ee6feca9530a09f38ff9f4b76c9c3e90c", + "app.html": "25c02252bb411f827fe862c30b061d13f52865c3c9ea01910668fef01ff8a449", + "index.html": "25c02252bb411f827fe862c30b061d13f52865c3c9ea01910668fef01ff8a449" } }