@mlx-bun/inference 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1475 -2
- package/THIRD_PARTY_NOTICES.md +3404 -0
- package/dist/native/libmlx_bun_ane.dylib +0 -0
- package/dist/native/libmlx_bun_expert_io.dylib +0 -0
- package/dist/native/mlx-bun-frame-extract +0 -0
- package/examples/fit-model.ts +25 -0
- package/examples/qwen3-forward.ts +42 -0
- package/examples/qwen3-generate.ts +28 -0
- package/examples/trellis-expand.ts +23 -0
- package/package.json +129 -4
- package/src/adapters/available.ts +110 -0
- package/src/adapters/index.ts +3 -0
- package/src/adapters/manager.ts +316 -0
- package/src/artifacts/auxiliary-files.ts +45 -0
- package/src/artifacts/config-dialects.ts +94 -0
- package/src/artifacts/config.ts +341 -0
- package/src/artifacts/draft-vocabulary.ts +30 -0
- package/src/artifacts/expert-offload-build.ts +75 -0
- package/src/artifacts/expert-offload.ts +89 -0
- package/src/artifacts/experts/index.ts +3 -0
- package/src/artifacts/experts/io.ts +386 -0
- package/src/artifacts/experts/residency.ts +1134 -0
- package/src/artifacts/experts/usage.ts +415 -0
- package/src/artifacts/fingerprint.ts +44 -0
- package/src/artifacts/glm52/container.ts +305 -0
- package/src/artifacts/glm52/expert-layout.ts +249 -0
- package/src/artifacts/glm52/index.ts +7 -0
- package/src/artifacts/glm52/kernel-layout.ts +124 -0
- package/src/artifacts/glm52/layout.ts +152 -0
- package/src/artifacts/glm52/memory.ts +500 -0
- package/src/artifacts/glm52/resident-weights.ts +135 -0
- package/src/artifacts/glm52/weights.ts +503 -0
- package/src/artifacts/glm52-config.ts +262 -0
- package/src/artifacts/identity.ts +94 -0
- package/src/artifacts/index.ts +15 -0
- package/src/artifacts/mmap.ts +90 -0
- package/src/artifacts/safetensors-writer.ts +249 -0
- package/src/artifacts/safetensors.ts +164 -0
- package/src/artifacts/turboquant-fold.ts +42 -0
- package/src/artifacts/weight-audit.ts +43 -0
- package/src/artifacts/weights.ts +255 -0
- package/src/contracts/index.ts +2 -0
- package/src/contracts/mlx/attention.ts +8 -0
- package/src/contracts/mlx/cache.ts +510 -0
- package/src/contracts/mlx/checkpoint.ts +10 -0
- package/src/contracts/mlx/draft-checkpoint.ts +14 -0
- package/src/contracts/mlx/draft-projection.ts +27 -0
- package/src/contracts/mlx/draft-target.ts +84 -0
- package/src/contracts/mlx/drafter.ts +176 -0
- package/src/contracts/mlx/forward-work.ts +23 -0
- package/src/contracts/mlx/glm52-weights.ts +25 -0
- package/src/contracts/mlx/graph.ts +309 -0
- package/src/contracts/mlx/head.ts +6 -0
- package/src/contracts/mlx/index.ts +15 -0
- package/src/contracts/mlx/kv-codec.ts +9 -0
- package/src/contracts/mlx/media.ts +113 -0
- package/src/contracts/mlx/positions.ts +16 -0
- package/src/contracts/mlx/row-table.ts +2 -0
- package/src/contracts/mlx/trainable.ts +103 -0
- package/src/contracts/mlx/whisper.ts +96 -0
- package/src/contracts/portable/composition.ts +106 -0
- package/src/contracts/portable/denoising.ts +17 -0
- package/src/contracts/portable/execution.ts +79 -0
- package/src/contracts/portable/generation.ts +103 -0
- package/src/contracts/portable/graph.ts +80 -0
- package/src/contracts/portable/index.ts +15 -0
- package/src/contracts/portable/memory-plan.ts +26 -0
- package/src/contracts/portable/object-cache.ts +8 -0
- package/src/contracts/portable/prefill.ts +63 -0
- package/src/contracts/portable/prefix-cache.ts +33 -0
- package/src/contracts/portable/prompt.ts +2 -0
- package/src/contracts/portable/resources.ts +25 -0
- package/src/contracts/portable/rollback.ts +7 -0
- package/src/contracts/portable/sampling.ts +44 -0
- package/src/contracts/portable/scheduling.ts +54 -0
- package/src/contracts/portable/token-delivery.ts +4 -0
- package/src/contracts/portable/tsconfig.json +14 -0
- package/src/embeddings/index.ts +1 -0
- package/src/embeddings/text.ts +85 -0
- package/src/execution/admission.ts +59 -0
- package/src/execution/batch-group.ts +1240 -0
- package/src/execution/batch-types.ts +225 -0
- package/src/execution/cancellation.ts +38 -0
- package/src/execution/continuation-request.ts +45 -0
- package/src/execution/continuation-types.ts +10 -0
- package/src/execution/coordinator.ts +70 -0
- package/src/execution/denoising-group.ts +180 -0
- package/src/execution/engine.ts +56 -0
- package/src/execution/fill-group.ts +505 -0
- package/src/execution/fit.ts +184 -0
- package/src/execution/gateway-binding.ts +178 -0
- package/src/execution/grammar-group.ts +224 -0
- package/src/execution/index.ts +18 -0
- package/src/execution/methods.ts +75 -0
- package/src/execution/mixed-iteration.ts +96 -0
- package/src/execution/plan.ts +65 -0
- package/src/execution/prefill-cohort.ts +100 -0
- package/src/execution/prefill-rows.ts +263 -0
- package/src/execution/request-policy.ts +19 -0
- package/src/execution/row-sampling.ts +49 -0
- package/src/execution/scheduler.ts +92 -0
- package/src/execution/session.ts +247 -0
- package/src/execution/speculative-group.ts +797 -0
- package/src/execution/tasks.ts +44 -0
- package/src/generation/autoregressive.ts +840 -0
- package/src/generation/bindings/autoregressive.ts +104 -0
- package/src/generation/bindings/denoising.ts +60 -0
- package/src/generation/bindings/prefill-policy.ts +36 -0
- package/src/generation/checkpoint-identity.ts +60 -0
- package/src/generation/denoising.ts +85 -0
- package/src/generation/diffusion.ts +583 -0
- package/src/generation/fill/echo-index.ts +188 -0
- package/src/generation/fill/index.ts +3 -0
- package/src/generation/fill/proposal.ts +69 -0
- package/src/generation/fill/schema-rows.ts +506 -0
- package/src/generation/fill/session.ts +464 -0
- package/src/generation/fill/tool-boundary.ts +103 -0
- package/src/generation/fill-append.ts +58 -0
- package/src/generation/generate.ts +44 -0
- package/src/generation/grammar-step.ts +39 -0
- package/src/generation/index.ts +14 -0
- package/src/generation/phase-dispatch.ts +115 -0
- package/src/generation/prefill.ts +33 -0
- package/src/generation/result.ts +49 -0
- package/src/generation/scopes.ts +157 -0
- package/src/generation/speculative/acceptance.ts +41 -0
- package/src/generation/speculative/adaptive-draft-gate.ts +166 -0
- package/src/generation/speculative/bindings/assistant-rows.ts +102 -0
- package/src/generation/speculative/bindings/autoregressive-rows.ts +124 -0
- package/src/generation/speculative/bindings/binding.ts +106 -0
- package/src/generation/speculative/bindings/deepspec-rows.ts +33 -0
- package/src/generation/speculative/bindings/draft-target.ts +10 -0
- package/src/generation/speculative/bindings/glm52-mtp-rows.ts +128 -0
- package/src/generation/speculative/bindings/projected-context-rows.ts +78 -0
- package/src/generation/speculative/bindings/projected-draft-rows.ts +95 -0
- package/src/generation/speculative/bindings/qwen-mtp-rows.ts +336 -0
- package/src/generation/speculative/bindings/two-model-rows.ts +63 -0
- package/src/generation/speculative/cache-identity.ts +16 -0
- package/src/generation/speculative/draft-kind.ts +149 -0
- package/src/generation/speculative/draft-policy.ts +41 -0
- package/src/generation/speculative/draft-registry.ts +118 -0
- package/src/generation/speculative/draft-vocab.ts +110 -0
- package/src/generation/speculative/index.ts +17 -0
- package/src/generation/speculative/output.ts +49 -0
- package/src/generation/speculative/round.ts +307 -0
- package/src/generation/speculative/source.ts +144 -0
- package/src/generation/speculative/sources/assistant-source.ts +64 -0
- package/src/generation/speculative/sources/deepspec-source.ts +70 -0
- package/src/generation/speculative/sources/dflash-source.ts +84 -0
- package/src/generation/speculative/sources/dflash2-source.ts +86 -0
- package/src/generation/speculative/sources/glm52-mtp-source.ts +66 -0
- package/src/generation/speculative/sources/ngram-source.ts +165 -0
- package/src/generation/speculative/sources/qwen-mtp-source.ts +154 -0
- package/src/generation/speculative/sources/two-model.ts +75 -0
- package/src/generation/types.ts +194 -0
- package/src/index.ts +20 -0
- package/src/input/audio/audiotoolbox.ts +112 -0
- package/src/input/audio/decode.ts +133 -0
- package/src/input/audio/features.ts +202 -0
- package/src/input/audio/index.ts +6 -0
- package/src/input/audio/transcode.ts +67 -0
- package/src/input/audio/whisper-mel.ts +185 -0
- package/src/input/audio/whisper-tokenizer.ts +238 -0
- package/src/input/chat-template.ts +389 -0
- package/src/input/index.ts +6 -0
- package/src/input/media-fetch.ts +439 -0
- package/src/input/packed-mixed.ts +43 -0
- package/src/input/special-tokens.ts +75 -0
- package/src/input/token-groups.ts +49 -0
- package/src/input/tokenizer.ts +336 -0
- package/src/input/tool-call.ts +689 -0
- package/src/input/vision/index.ts +3 -0
- package/src/input/vision/preprocess.ts +247 -0
- package/src/input/vision/prompt.ts +398 -0
- package/src/input/vision/qwen3vl-preprocess.ts +409 -0
- package/src/input/vision/qwen3vl-prompt.ts +237 -0
- package/src/input/vision/video-frames.ts +100 -0
- package/src/kernels/ane/fill.ts +101 -0
- package/src/kernels/ane/linear.ts +416 -0
- package/src/kernels/attention/flash.ts +694 -0
- package/src/kernels/attention/kvq4-decode.ts +155 -0
- package/src/kernels/attention/masks.ts +40 -0
- package/src/kernels/attention/multi-query.ts +193 -0
- package/src/kernels/attention/paged.ts +130 -0
- package/src/kernels/delta/gated.ts +306 -0
- package/src/kernels/delta/index.ts +3 -0
- package/src/kernels/delta/silu-rms-heads.ts +69 -0
- package/src/kernels/delta/state.ts +74 -0
- package/src/kernels/gated-rms-norm.ts +64 -0
- package/src/kernels/glm52/layout.ts +37 -0
- package/src/kernels/glm52/streamed-experts.ts +360 -0
- package/src/kernels/logits.ts +38 -0
- package/src/kernels/quantization/affine-row.ts +154 -0
- package/src/kernels/quantization/affine-rows.ts +36 -0
- package/src/kernels/quantization/affine-split-mma.ts +144 -0
- package/src/kernels/quantization/affine3-mma.ts +117 -0
- package/src/kernels/quantization/affine3-rows.ts +103 -0
- package/src/kernels/quantization/affine4-mma.ts +113 -0
- package/src/kernels/quantization/affine4-rows.ts +102 -0
- package/src/kernels/residual-rms-norm.ts +65 -0
- package/src/kernels/sampling/index.ts +2 -0
- package/src/kernels/sampling/normalized-argmax.ts +116 -0
- package/src/kernels/sampling/token-bitmask.ts +52 -0
- package/src/kernels/softcap.ts +35 -0
- package/src/kernels/trellis/codebook.ts +123 -0
- package/src/kernels/trellis/down-codebook.ts +184 -0
- package/src/kernels/trellis/down-factored.ts +180 -0
- package/src/kernels/trellis/down-k3-interleaved-factored.ts +146 -0
- package/src/kernels/trellis/down-mma-wide.ts +195 -0
- package/src/kernels/trellis/down-mma.ts +145 -0
- package/src/kernels/trellis/expand.ts +42 -0
- package/src/kernels/trellis/gate-up-codebook-mma.ts +141 -0
- package/src/kernels/trellis/gate-up-codebook.ts +137 -0
- package/src/kernels/trellis/gate-up-factored.ts +197 -0
- package/src/kernels/trellis/gate-up-mma-wide.ts +147 -0
- package/src/kernels/trellis/gate-up-mma.ts +148 -0
- package/src/kernels/trellis/gate-up.ts +248 -0
- package/src/kernels/trellis/geometry.ts +22 -0
- package/src/kernels/trellis/index.ts +103 -0
- package/src/kernels/trellis/launch.ts +12 -0
- package/src/kernels/trellis/mixed-gate-up-factored.ts +119 -0
- package/src/kernels/trellis/mixed-gate-up.ts +146 -0
- package/src/kernels/trellis/qualified.ts +34 -0
- package/src/kernels/trellis/reduce.ts +150 -0
- package/src/kernels/trellis/scatter.ts +407 -0
- package/src/kernels/trellis/splitk-prefill.ts +152 -0
- package/src/kernels/trellis/tiled-prefill.ts +131 -0
- package/src/kernels/trellis/vector-expand.ts +58 -0
- package/src/kernels/trellis/wide-prefill.ts +89 -0
- package/src/kernels/turboquant/decode.ts +82 -0
- package/src/kernels/turboquant/index.ts +5 -0
- package/src/kernels/turboquant/inverse.ts +122 -0
- package/src/kernels/turboquant/ops.ts +860 -0
- package/src/kernels/turboquant/signs.ts +130 -0
- package/src/kernels/turboquant/tables.ts +124 -0
- package/src/layers/affine-verify-linear.ts +75 -0
- package/src/layers/ane-prefill-split.ts +283 -0
- package/src/layers/compiled-normalization.ts +41 -0
- package/src/layers/delta-heads.ts +23 -0
- package/src/layers/dense-embedding.ts +29 -0
- package/src/layers/dense-linear.ts +32 -0
- package/src/layers/dequantized-linear.ts +72 -0
- package/src/layers/folded-attention.ts +42 -0
- package/src/layers/geglu.ts +130 -0
- package/src/layers/helpers.ts +7 -0
- package/src/layers/index.ts +36 -0
- package/src/layers/kv4-decode-attention.ts +15 -0
- package/src/layers/layer-norm.ts +24 -0
- package/src/layers/loading.ts +92 -0
- package/src/layers/lora.ts +150 -0
- package/src/layers/normalization.ts +9 -0
- package/src/layers/prefix-layout.ts +33 -0
- package/src/layers/quantized-append-attention.ts +32 -0
- package/src/layers/quantized-attention.ts +353 -0
- package/src/layers/quantized-embedding.ts +39 -0
- package/src/layers/quantized-linear.ts +137 -0
- package/src/layers/quantized-switch-linear.ts +37 -0
- package/src/layers/qwen-append.ts +12 -0
- package/src/layers/qwen-mrope.ts +238 -0
- package/src/layers/rope-2d.ts +110 -0
- package/src/layers/rope.ts +389 -0
- package/src/layers/swiglu.ts +23 -0
- package/src/layers/trellis-codebook-down.ts +52 -0
- package/src/layers/trellis-codebook-gate-up.ts +42 -0
- package/src/layers/trellis-down.ts +117 -0
- package/src/layers/trellis-gate-up.ts +71 -0
- package/src/layers/trellis-linear.ts +211 -0
- package/src/layers/trellis-prompt.ts +102 -0
- package/src/layers/trellis-reduce-gate-up.ts +73 -0
- package/src/layers/trellis-scatter-down.ts +98 -0
- package/src/models/ane-install.ts +74 -0
- package/src/models/audio/conformer.ts +656 -0
- package/src/models/cache-composition.ts +44 -0
- package/src/models/capabilities.ts +89 -0
- package/src/models/chat-template.ts +10 -0
- package/src/models/composition.ts +107 -0
- package/src/models/diffusion-gemma/experts.ts +59 -0
- package/src/models/diffusion-gemma/family.ts +21 -0
- package/src/models/diffusion-gemma/model.ts +900 -0
- package/src/models/diffusion-gemma/vision.ts +549 -0
- package/src/models/drafter-loaders.ts +49 -0
- package/src/models/drafters.ts +39 -0
- package/src/models/factory.ts +351 -0
- package/src/models/families.ts +70 -0
- package/src/models/family.ts +125 -0
- package/src/models/gemma4/assistant-target.ts +46 -0
- package/src/models/gemma4/assistant.ts +327 -0
- package/src/models/gemma4/blocks.ts +755 -0
- package/src/models/gemma4/compiled-decode.ts +452 -0
- package/src/models/gemma4/family.ts +39 -0
- package/src/models/gemma4/gemma4-12b.ts +677 -0
- package/src/models/gemma4/gemma4-26b.ts +544 -0
- package/src/models/gemma4/gemma4-e4b.ts +599 -0
- package/src/models/gemma4/graphs.ts +147 -0
- package/src/models/gemma4/media.ts +88 -0
- package/src/models/gemma4/model.ts +860 -0
- package/src/models/gemma4/serving-blocks.ts +72 -0
- package/src/models/gemma4/trainable.ts +186 -0
- package/src/models/gemma4/written-blocks.ts +232 -0
- package/src/models/gemma4/written-forward.ts +159 -0
- package/src/models/gemma4/written-input.ts +29 -0
- package/src/models/glm52/atlas.ts +507 -0
- package/src/models/glm52/coupling.ts +388 -0
- package/src/models/glm52/dsa.ts +601 -0
- package/src/models/glm52/family.ts +20 -0
- package/src/models/glm52/mla.ts +812 -0
- package/src/models/glm52/model.ts +1127 -0
- package/src/models/glm52/moe.ts +223 -0
- package/src/models/glm52/mtp.ts +60 -0
- package/src/models/glm52/pilot.ts +537 -0
- package/src/models/glm52/reference.ts +445 -0
- package/src/models/glm52/residency.ts +557 -0
- package/src/models/glm52/streamed-experts.ts +447 -0
- package/src/models/graph.ts +59 -0
- package/src/models/implementation.ts +230 -0
- package/src/models/index.ts +15 -0
- package/src/models/media-input.ts +15 -0
- package/src/models/memory-plan.ts +39 -0
- package/src/models/minicpm5/family.ts +29 -0
- package/src/models/minicpm5/model.ts +394 -0
- package/src/models/minicpm5/trainable.ts +90 -0
- package/src/models/profile.ts +337 -0
- package/src/models/qwen/blocks.ts +658 -0
- package/src/models/qwen/checkpoint.ts +190 -0
- package/src/models/qwen/families.ts +57 -0
- package/src/models/qwen/media-input.ts +161 -0
- package/src/models/qwen/mtp.ts +101 -0
- package/src/models/qwen/qwen3-moe.ts +355 -0
- package/src/models/qwen/qwen3.ts +323 -0
- package/src/models/qwen/qwen38-27b-trellis-m1max.ts +1532 -0
- package/src/models/qwen/qwen38-27b-trellis-m4pro.ts +1092 -0
- package/src/models/qwen/qwen3_5.ts +433 -0
- package/src/models/qwen/written-layers.ts +285 -0
- package/src/models/row-table.ts +1 -0
- package/src/models/runtime.ts +73 -0
- package/src/models/speculative/deepspec-artifact.ts +10 -0
- package/src/models/speculative/deepspec.ts +744 -0
- package/src/models/speculative/dflash.ts +553 -0
- package/src/models/speculative/dflash2-artifact.ts +9 -0
- package/src/models/speculative/dflash2-operations.ts +1 -0
- package/src/models/speculative/dflash2.ts +576 -0
- package/src/models/speculative/loader.ts +29 -0
- package/src/models/support.ts +79 -0
- package/src/models/universal/archs.ts +365 -0
- package/src/models/universal/blocks.ts +479 -0
- package/src/models/universal/dense.ts +255 -0
- package/src/models/universal/family.ts +17 -0
- package/src/models/vision/qwen3vl.ts +566 -0
- package/src/models/vision/siglip.ts +520 -0
- package/src/models/vision/unified.ts +176 -0
- package/src/models/whisper/family.ts +19 -0
- package/src/models/whisper/fast.ts +734 -0
- package/src/models/whisper/model.ts +430 -0
- package/src/runtime/compiled-trace.ts +16 -0
- package/src/runtime/config.ts +77 -0
- package/src/runtime/expert-trace.ts +71 -0
- package/src/runtime/graph-forward.ts +65 -0
- package/src/runtime/integers.ts +6 -0
- package/src/runtime/native.ts +16 -0
- package/src/runtime/resources.ts +53 -0
- package/src/runtime/row-operations.ts +42 -0
- package/src/runtime/trace.ts +161 -0
- package/src/sampling/curve.ts +122 -0
- package/src/sampling/draft.ts +55 -0
- package/src/sampling/extras.ts +45 -0
- package/src/sampling/filters.ts +134 -0
- package/src/sampling/grammar.ts +630 -0
- package/src/sampling/hlg.ts +290 -0
- package/src/sampling/index.ts +9 -0
- package/src/sampling/processors.ts +142 -0
- package/src/sampling/sampler.ts +120 -0
- package/src/sampling/step.ts +343 -0
- package/src/sampling/types.ts +161 -0
- package/src/sampling/window-filters.ts +46 -0
- package/src/scoring/decisions.ts +96 -0
- package/src/scoring/full-sequence.ts +103 -0
- package/src/scoring/index.ts +9 -0
- package/src/scoring/kl.ts +29 -0
- package/src/scoring/perplexity.ts +165 -0
- package/src/scoring/response-logps.ts +65 -0
- package/src/state/affine-attention.ts +180 -0
- package/src/state/attachment.ts +68 -0
- package/src/state/attention-read.ts +215 -0
- package/src/state/batched-kv.ts +294 -0
- package/src/state/batched-mask.ts +445 -0
- package/src/state/batched-quant.ts +389 -0
- package/src/state/batched-quantized-kv.ts +209 -0
- package/src/state/batched-rotating-quant.ts +457 -0
- package/src/state/batched-rotating-state.ts +149 -0
- package/src/state/batched-rotating.ts +430 -0
- package/src/state/batched-row-storage.ts +179 -0
- package/src/state/batched-ssm.ts +54 -0
- package/src/state/batched-turboquant-kv.ts +144 -0
- package/src/state/bf16-first-kv.ts +663 -0
- package/src/state/cache-service.ts +592 -0
- package/src/state/capabilities.ts +65 -0
- package/src/state/checkpoint.ts +46 -0
- package/src/state/continuation-persistence.ts +126 -0
- package/src/state/decode-step-inputs.ts +31 -0
- package/src/state/decoded-kv-donor.ts +12 -0
- package/src/state/delayed-quantized-kv.ts +141 -0
- package/src/state/delayed-rotating-quantized-kv.ts +178 -0
- package/src/state/delayed-turboquant-kv.ts +123 -0
- package/src/state/durability.ts +214 -0
- package/src/state/encoder-cache.ts +26 -0
- package/src/state/full-kv-row-append.ts +33 -0
- package/src/state/full-kv-row-donor.ts +54 -0
- package/src/state/full-prefill-padding.ts +56 -0
- package/src/state/full-prefill-row.ts +112 -0
- package/src/state/full-transitioning-kv-rows.ts +70 -0
- package/src/state/glm52-cache.ts +783 -0
- package/src/state/grouped-heads-kv4-cache.ts +26 -0
- package/src/state/index.ts +38 -0
- package/src/state/kv-attention-view.ts +77 -0
- package/src/state/kv-budget.ts +14 -0
- package/src/state/kv-scheme.ts +315 -0
- package/src/state/kv-storage.ts +57 -0
- package/src/state/kv-tensor-rows.ts +212 -0
- package/src/state/kv.ts +324 -0
- package/src/state/kv4-head256-cache.ts +46 -0
- package/src/state/latent-legos.ts +895 -0
- package/src/state/layout.ts +277 -0
- package/src/state/leases.ts +26 -0
- package/src/state/paged/cache.ts +689 -0
- package/src/state/paged/codec.ts +36 -0
- package/src/state/paged/rows.ts +223 -0
- package/src/state/persistence-types.ts +173 -0
- package/src/state/persistence-worker.ts +83 -0
- package/src/state/persistence.ts +1036 -0
- package/src/state/persistence.worker.d.ts +3 -0
- package/src/state/persistence.worker.js +264 -0
- package/src/state/prefix-cache.ts +685 -0
- package/src/state/quantized-kv.ts +369 -0
- package/src/state/quantized-tensor.ts +26 -0
- package/src/state/request-policy.ts +48 -0
- package/src/state/retention-policy.ts +37 -0
- package/src/state/rollback.ts +131 -0
- package/src/state/rotating-kv-donor.ts +35 -0
- package/src/state/rotating-kv-layout.ts +341 -0
- package/src/state/rotating-kv.ts +529 -0
- package/src/state/rotating-quantized-kv.ts +616 -0
- package/src/state/rotating-row-transaction.ts +35 -0
- package/src/state/rows.ts +104 -0
- package/src/state/softcap-attention.ts +118 -0
- package/src/state/speculative/glm52-mtp-state.ts +38 -0
- package/src/state/speculative/qwen-mtp-state.ts +34 -0
- package/src/state/speculative-rotating-kv.ts +113 -0
- package/src/state/ssd-cache.ts +434 -0
- package/src/state/ssm-prefill-padding.ts +39 -0
- package/src/state/ssm.ts +422 -0
- package/src/state/target-layout.ts +7 -0
- package/src/state/tiered-prefix-cache.ts +45 -0
- package/src/state/training-cache.ts +300 -0
- package/src/state/transitioning-kv-rows.ts +267 -0
- package/src/state/turboquant-attention.ts +97 -0
- package/src/state/turboquant-codec.ts +90 -0
- package/src/state/turboquant-kv.ts +442 -0
- package/src/state/views.ts +26 -0
- package/src/transcription/index.ts +3 -0
- package/src/transcription/silero-vad.ts +379 -0
- package/src/transcription/whisper/decode.ts +773 -0
- package/src/transcription/whisper/format.ts +74 -0
- package/src/transcription/whisper/index.ts +4 -0
- package/src/transcription/whisper/timing.ts +274 -0
- package/src/transcription/whisper/transcribe.ts +394 -0
- package/src/transcription/whisper/types.ts +22 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
// Qwen3-VL-family image preprocessing (Qwen3.8 vision) — port of
|
|
2
|
+
// mlx-vlm's Qwen3VLImageProcessor image path (processing_qwen3_vl.py):
|
|
3
|
+
//
|
|
4
|
+
// decode → smart_resize to multiples of factor=patch*merge=32 (PIL-style
|
|
5
|
+
// antialiased bicubic via the shared resizeBicubic) → rescale 1/255 →
|
|
6
|
+
// normalize mean/std 0.5 → duplicate the frame temporal_patch_size(=2)
|
|
7
|
+
// times → patchify into [grid_t*grid_h*grid_w, C*tps*ps*ps] rows.
|
|
8
|
+
//
|
|
9
|
+
// Row order is MERGE-BLOCK-MAJOR: rows enumerate (t, hBlock, wBlock, mh, mw)
|
|
10
|
+
// so each 2×2 spatial-merge block is contiguous; row elements enumerate
|
|
11
|
+
// (c, tFrame, py, px) — exactly the reference's transpose
|
|
12
|
+
// (0,1,4,7,5,8,3,2,6,9) before its final reshape. The tower's PatchEmbed and
|
|
13
|
+
// PatchMerger both assume this order.
|
|
14
|
+
//
|
|
15
|
+
// Images sized to multiples of 32 skip the resize and are bit-identical to
|
|
16
|
+
// the python pipeline through preprocessing (the gemma/SigLIP precedent);
|
|
17
|
+
// resized images carry the documented sub-ulp bicubic residual.
|
|
18
|
+
|
|
19
|
+
import { decodeImage, type RGBImage } from "./preprocess";
|
|
20
|
+
|
|
21
|
+
export const QWEN3VL_PATCH_SIZE = 16;
|
|
22
|
+
export const QWEN3VL_TEMPORAL_PATCH_SIZE = 2;
|
|
23
|
+
export const QWEN3VL_MERGE_SIZE = 2;
|
|
24
|
+
/** Qwen3VLImageProcessor defaults (no preprocessor_config.json in the
|
|
25
|
+
* artifact — mlx-vlm falls back to these class defaults too). */
|
|
26
|
+
export const QWEN3VL_MIN_PIXELS = 56 * 56;
|
|
27
|
+
export const QWEN3VL_MAX_PIXELS = 14 * 14 * 4 * 1280;
|
|
28
|
+
|
|
29
|
+
export interface Qwen3VLPreprocessed {
|
|
30
|
+
/** [gridT*gridH*gridW, C*tps*ps*ps] f32 patch rows (merge-block-major). */
|
|
31
|
+
pixelValues: Float32Array;
|
|
32
|
+
rows: number;
|
|
33
|
+
cols: number;
|
|
34
|
+
/** [t, h, w] in PATCH units (h = resizedH/16 etc.). */
|
|
35
|
+
gridThw: [number, number, number];
|
|
36
|
+
/** Language-side image token count = t * (h/merge) * (w/merge). */
|
|
37
|
+
imageTokens: number;
|
|
38
|
+
/** Videos only: per-temporal-group timestamps in seconds (frame-pair
|
|
39
|
+
* averaged, transformers `_calculate_timestamps`) — the `<X.X seconds>`
|
|
40
|
+
* headers the prompt builder renders before each frame group. */
|
|
41
|
+
groupTimestamps?: number[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Python `f"{x:.1f}"` — correct rounding of the double with HALF-TO-EVEN
|
|
45
|
+
* at the decimal digit. JS toFixed rounds exact .x5 ties AWAY from zero
|
|
46
|
+
* (0.25 → "0.3"), the reference renders "0.2"; a different timestamp
|
|
47
|
+
* string is a different token sequence. */
|
|
48
|
+
export function pyFixed1(x: number): string {
|
|
49
|
+
const scaled = x * 10;
|
|
50
|
+
const floor = Math.floor(scaled);
|
|
51
|
+
const diff = scaled - floor;
|
|
52
|
+
let n: number;
|
|
53
|
+
if (diff > 0.5) n = floor + 1;
|
|
54
|
+
else if (diff < 0.5) n = floor;
|
|
55
|
+
else n = floor % 2 === 0 ? floor : floor + 1;
|
|
56
|
+
return (n / 10).toFixed(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Python's builtin round — HALF-TO-EVEN, unlike JS Math.round (half-up).
|
|
60
|
+
* smart_resize divides integer dims by factor 32, which lands on exact .5
|
|
61
|
+
* for heights like 80 (2.5): the reference rounds DOWN to the even 2 where
|
|
62
|
+
* Math.round gives 3 — a different grid and silently different tokens. */
|
|
63
|
+
export function roundHalfEven(x: number): number {
|
|
64
|
+
const floor = Math.floor(x);
|
|
65
|
+
const diff = x - floor;
|
|
66
|
+
if (diff > 0.5) return floor + 1;
|
|
67
|
+
if (diff < 0.5) return floor;
|
|
68
|
+
return floor % 2 === 0 ? floor : floor + 1;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** HF qwen2_vl smart_resize (image variant): round to multiples of `factor`,
|
|
72
|
+
* then scale into [minPixels, maxPixels] preserving aspect. */
|
|
73
|
+
export function smartResize(
|
|
74
|
+
height: number,
|
|
75
|
+
width: number,
|
|
76
|
+
factor = QWEN3VL_PATCH_SIZE * QWEN3VL_MERGE_SIZE,
|
|
77
|
+
minPixels = QWEN3VL_MIN_PIXELS,
|
|
78
|
+
maxPixels = QWEN3VL_MAX_PIXELS,
|
|
79
|
+
): [number, number] {
|
|
80
|
+
if (Math.max(height, width) / Math.min(height, width) > 200)
|
|
81
|
+
throw new Error(
|
|
82
|
+
`absolute aspect ratio must be smaller than 200, got ` +
|
|
83
|
+
`${Math.max(height, width) / Math.min(height, width)}`,
|
|
84
|
+
);
|
|
85
|
+
let hBar = roundHalfEven(height / factor) * factor;
|
|
86
|
+
let wBar = roundHalfEven(width / factor) * factor;
|
|
87
|
+
if (hBar * wBar > maxPixels) {
|
|
88
|
+
const beta = Math.sqrt((height * width) / maxPixels);
|
|
89
|
+
hBar = Math.max(factor, Math.floor(height / beta / factor) * factor);
|
|
90
|
+
wBar = Math.max(factor, Math.floor(width / beta / factor) * factor);
|
|
91
|
+
} else if (hBar * wBar < minPixels) {
|
|
92
|
+
const beta = Math.sqrt(minPixels / (height * width));
|
|
93
|
+
hBar = Math.ceil((height * beta) / factor) * factor;
|
|
94
|
+
wBar = Math.ceil((width * beta) / factor) * factor;
|
|
95
|
+
}
|
|
96
|
+
return [hBar, wBar];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// --- PIL-exact uint8 bicubic (Pillow Resample.c, 8bpc path) ---------------
|
|
100
|
+
// The reference pipeline roundtrips resize through PIL's 8-bit resampler:
|
|
101
|
+
// int32 fixed-point coefficients at PRECISION_BITS=22, a QUANTIZED uint8
|
|
102
|
+
// intermediate between the horizontal and vertical passes, and PIL's exact
|
|
103
|
+
// window bounds ((int)(center ± support + 0.5)). The float resizeBicubic in
|
|
104
|
+
// preprocess.ts (gemma's float-reference port) differs by ±1 uint8 count —
|
|
105
|
+
// this emulation is bit-exact instead (gated vs the oracle pixel grid).
|
|
106
|
+
|
|
107
|
+
const PIL_PRECISION_BITS = 32 - 8 - 2; // 22
|
|
108
|
+
|
|
109
|
+
function pilBicubicFilter(x: number): number {
|
|
110
|
+
const a = -0.5;
|
|
111
|
+
x = Math.abs(x);
|
|
112
|
+
if (x < 1) return ((a + 2) * x - (a + 3)) * x * x + 1;
|
|
113
|
+
if (x < 2) return (((x - 5) * x + 8) * x - 4) * a;
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface PilCoeffs {
|
|
118
|
+
bounds: Int32Array; // [outSize × 2]: (xmin, count)
|
|
119
|
+
kk: Int32Array; // [outSize × ksize] fixed-point (1<<22-scaled) weights
|
|
120
|
+
ksize: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function pilPrecomputeCoeffs(inSize: number, outSize: number): PilCoeffs {
|
|
124
|
+
const SUPPORT = 2.0;
|
|
125
|
+
const scale = inSize / outSize;
|
|
126
|
+
const filterscale = Math.max(scale, 1.0);
|
|
127
|
+
const support = SUPPORT * filterscale;
|
|
128
|
+
const ksize = Math.ceil(support) * 2 + 1;
|
|
129
|
+
const bounds = new Int32Array(outSize * 2);
|
|
130
|
+
const kk = new Int32Array(outSize * ksize);
|
|
131
|
+
const ss = 1.0 / filterscale;
|
|
132
|
+
for (let xx = 0; xx < outSize; xx++) {
|
|
133
|
+
const center = (xx + 0.5) * scale;
|
|
134
|
+
let xmin = Math.trunc(center - support + 0.5);
|
|
135
|
+
if (xmin < 0) xmin = 0;
|
|
136
|
+
let xmax = Math.trunc(center + support + 0.5);
|
|
137
|
+
if (xmax > inSize) xmax = inSize;
|
|
138
|
+
const count = xmax - xmin;
|
|
139
|
+
const w = new Float64Array(count);
|
|
140
|
+
let sum = 0;
|
|
141
|
+
for (let x = 0; x < count; x++) {
|
|
142
|
+
w[x] = pilBicubicFilter((x + xmin - center + 0.5) * ss);
|
|
143
|
+
sum += w[x]!;
|
|
144
|
+
}
|
|
145
|
+
for (let x = 0; x < count; x++) {
|
|
146
|
+
const v = sum !== 0 ? w[x]! / sum : w[x]!;
|
|
147
|
+
// normalize_coeffs_8bpc: round-half-away via ±0.5 then C truncation.
|
|
148
|
+
const scaled = v * (1 << PIL_PRECISION_BITS);
|
|
149
|
+
kk[xx * ksize + x] = Math.trunc(scaled < 0 ? scaled - 0.5 : scaled + 0.5);
|
|
150
|
+
}
|
|
151
|
+
bounds[xx * 2] = xmin;
|
|
152
|
+
bounds[xx * 2 + 1] = count;
|
|
153
|
+
}
|
|
154
|
+
return { bounds, kk, ksize };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function pilClip8(v: number): number {
|
|
158
|
+
const shifted = Math.floor(v / (1 << PIL_PRECISION_BITS));
|
|
159
|
+
return shifted < 0 ? 0 : shifted > 255 ? 255 : shifted;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** PIL Image.resize(..., BICUBIC) on uint8 RGB — bit-exact 8bpc emulation. */
|
|
163
|
+
export function pilResizeBicubic(img: RGBImage, outW: number, outH: number): RGBImage {
|
|
164
|
+
const { width: inW, height: inH } = img;
|
|
165
|
+
let data = img.data;
|
|
166
|
+
let curW = inW;
|
|
167
|
+
const ROUND = 1 << (PIL_PRECISION_BITS - 1);
|
|
168
|
+
if (outW !== inW) {
|
|
169
|
+
const { bounds, kk, ksize } = pilPrecomputeCoeffs(inW, outW);
|
|
170
|
+
const tmp = new Uint8Array(inH * outW * 3);
|
|
171
|
+
for (let y = 0; y < inH; y++) {
|
|
172
|
+
for (let x = 0; x < outW; x++) {
|
|
173
|
+
const xmin = bounds[x * 2]!;
|
|
174
|
+
const count = bounds[x * 2 + 1]!;
|
|
175
|
+
let r = ROUND, g = ROUND, b = ROUND;
|
|
176
|
+
for (let k = 0; k < count; k++) {
|
|
177
|
+
const w = kk[x * ksize + k]!;
|
|
178
|
+
const src = (y * inW + xmin + k) * 3;
|
|
179
|
+
r += data[src]! * w;
|
|
180
|
+
g += data[src + 1]! * w;
|
|
181
|
+
b += data[src + 2]! * w;
|
|
182
|
+
}
|
|
183
|
+
const dst = (y * outW + x) * 3;
|
|
184
|
+
tmp[dst] = pilClip8(r);
|
|
185
|
+
tmp[dst + 1] = pilClip8(g);
|
|
186
|
+
tmp[dst + 2] = pilClip8(b);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
data = tmp;
|
|
190
|
+
curW = outW;
|
|
191
|
+
}
|
|
192
|
+
if (outH !== inH) {
|
|
193
|
+
const { bounds, kk, ksize } = pilPrecomputeCoeffs(inH, outH);
|
|
194
|
+
const out = new Uint8Array(outH * curW * 3);
|
|
195
|
+
for (let y = 0; y < outH; y++) {
|
|
196
|
+
const ymin = bounds[y * 2]!;
|
|
197
|
+
const count = bounds[y * 2 + 1]!;
|
|
198
|
+
for (let x = 0; x < curW; x++) {
|
|
199
|
+
let r = ROUND, g = ROUND, b = ROUND;
|
|
200
|
+
for (let k = 0; k < count; k++) {
|
|
201
|
+
const w = kk[y * ksize + k]!;
|
|
202
|
+
const src = ((ymin + k) * curW + x) * 3;
|
|
203
|
+
r += data[src]! * w;
|
|
204
|
+
g += data[src + 1]! * w;
|
|
205
|
+
b += data[src + 2]! * w;
|
|
206
|
+
}
|
|
207
|
+
const dst = (y * curW + x) * 3;
|
|
208
|
+
out[dst] = pilClip8(r);
|
|
209
|
+
out[dst + 1] = pilClip8(g);
|
|
210
|
+
out[dst + 2] = pilClip8(b);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
data = out;
|
|
214
|
+
}
|
|
215
|
+
return { width: outW, height: outH, data };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Patchify one normalized frame (f32 CHW logical, provided as HWC bytes →
|
|
219
|
+
* normalized on the fly) into merge-block-major rows. */
|
|
220
|
+
export function patchifyImage(img: RGBImage): Qwen3VLPreprocessed {
|
|
221
|
+
const ps = QWEN3VL_PATCH_SIZE;
|
|
222
|
+
const tps = QWEN3VL_TEMPORAL_PATCH_SIZE;
|
|
223
|
+
const ms = QWEN3VL_MERGE_SIZE;
|
|
224
|
+
const C = 3;
|
|
225
|
+
const { width: W, height: H, data } = img;
|
|
226
|
+
if (H % (ps * ms) !== 0 || W % (ps * ms) !== 0)
|
|
227
|
+
throw new Error(`patchify expects dims % ${ps * ms} == 0, got ${W}x${H}`);
|
|
228
|
+
const gridH = H / ps;
|
|
229
|
+
const gridW = W / ps;
|
|
230
|
+
const rows = gridH * gridW;
|
|
231
|
+
const cols = C * tps * ps * ps;
|
|
232
|
+
const out = new Float32Array(rows * cols);
|
|
233
|
+
// Normalize with the reference's exact f32 op sequence — x*(1/255), then
|
|
234
|
+
// (x-0.5)/0.5 — NOT the algebraic x/127.5-1, which rounds differently in
|
|
235
|
+
// f32 (a flat 1.19e-7 max delta on the unresized gate before this).
|
|
236
|
+
const RESCALE = Math.fround(1 / 255);
|
|
237
|
+
const norm = new Float32Array(256);
|
|
238
|
+
for (let i = 0; i < 256; i++)
|
|
239
|
+
norm[i] = Math.fround((Math.fround(i * RESCALE) - 0.5) / 0.5);
|
|
240
|
+
const hBlocks = gridH / ms;
|
|
241
|
+
const wBlocks = gridW / ms;
|
|
242
|
+
let r = 0;
|
|
243
|
+
for (let h1 = 0; h1 < hBlocks; h1++) {
|
|
244
|
+
for (let w1 = 0; w1 < wBlocks; w1++) {
|
|
245
|
+
for (let mh = 0; mh < ms; mh++) {
|
|
246
|
+
for (let mw = 0; mw < ms; mw++) {
|
|
247
|
+
const hPatch = h1 * ms + mh;
|
|
248
|
+
const wPatch = w1 * ms + mw;
|
|
249
|
+
const base = r * cols;
|
|
250
|
+
for (let c = 0; c < C; c++) {
|
|
251
|
+
for (let tp = 0; tp < tps; tp++) {
|
|
252
|
+
// Images: the single frame is duplicated across tps.
|
|
253
|
+
for (let py = 0; py < ps; py++) {
|
|
254
|
+
const y = hPatch * ps + py;
|
|
255
|
+
const rowOff = (y * W + wPatch * ps) * 3 + c;
|
|
256
|
+
const dst = base + ((c * tps + tp) * ps + py) * ps;
|
|
257
|
+
for (let px = 0; px < ps; px++) {
|
|
258
|
+
out[dst + px] = norm[data[rowOff + px * 3]!]!;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
r++;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
pixelValues: out,
|
|
270
|
+
rows,
|
|
271
|
+
cols,
|
|
272
|
+
gridThw: [1, gridH, gridW],
|
|
273
|
+
imageTokens: (gridH / ms) * (gridW / ms),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Full image pipeline: decode → smart_resize (skipped when already sized) →
|
|
278
|
+
* patchify. */
|
|
279
|
+
export async function preprocessQwen3VLImage(
|
|
280
|
+
bytes: Uint8Array,
|
|
281
|
+
): Promise<Qwen3VLPreprocessed> {
|
|
282
|
+
const img = await decodeImage(bytes);
|
|
283
|
+
const [h, w] = smartResize(img.height, img.width);
|
|
284
|
+
const sized = h === img.height && w === img.width
|
|
285
|
+
? img
|
|
286
|
+
: pilResizeBicubic(img, w, h);
|
|
287
|
+
return patchifyImage(sized);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// --- video ------------------------------------------------------------------
|
|
291
|
+
|
|
292
|
+
/** Qwen3VLVideoProcessor class defaults (frame-count-aware budget). */
|
|
293
|
+
export const QWEN3VL_VIDEO_MIN_PIXELS = 128 * 32 * 32;
|
|
294
|
+
export const QWEN3VL_VIDEO_MAX_PIXELS = 32 * 32 * 768;
|
|
295
|
+
|
|
296
|
+
/** HF smart_resize, VIDEO variant: the token budget counts the (padded)
|
|
297
|
+
* temporal extent — t_bar·h_bar·w_bar against min/max pixels. */
|
|
298
|
+
export function smartResizeVideo(
|
|
299
|
+
numFrames: number, height: number, width: number,
|
|
300
|
+
temporalFactor = QWEN3VL_TEMPORAL_PATCH_SIZE,
|
|
301
|
+
factor = QWEN3VL_PATCH_SIZE * QWEN3VL_MERGE_SIZE,
|
|
302
|
+
minPixels = QWEN3VL_VIDEO_MIN_PIXELS,
|
|
303
|
+
maxPixels = QWEN3VL_VIDEO_MAX_PIXELS,
|
|
304
|
+
): [number, number] {
|
|
305
|
+
if (height < factor || width < factor)
|
|
306
|
+
throw new Error(`height:${height} or width:${width} must be larger than factor:${factor}`);
|
|
307
|
+
if (Math.max(height, width) / Math.min(height, width) > 200)
|
|
308
|
+
throw new Error(
|
|
309
|
+
`absolute aspect ratio must be smaller than 200, got ` +
|
|
310
|
+
`${Math.max(height, width) / Math.min(height, width)}`,
|
|
311
|
+
);
|
|
312
|
+
let hBar = roundHalfEven(height / factor) * factor;
|
|
313
|
+
let wBar = roundHalfEven(width / factor) * factor;
|
|
314
|
+
const tBar = Math.ceil(numFrames / temporalFactor) * temporalFactor;
|
|
315
|
+
if (tBar * hBar * wBar > maxPixels) {
|
|
316
|
+
const beta = Math.sqrt((numFrames * height * width) / maxPixels);
|
|
317
|
+
hBar = Math.max(factor, Math.floor(height / beta / factor) * factor);
|
|
318
|
+
wBar = Math.max(factor, Math.floor(width / beta / factor) * factor);
|
|
319
|
+
} else if (tBar * hBar * wBar < minPixels) {
|
|
320
|
+
const beta = Math.sqrt(minPixels / (numFrames * height * width));
|
|
321
|
+
hBar = Math.ceil((height * beta) / factor) * factor;
|
|
322
|
+
wBar = Math.ceil((width * beta) / factor) * factor;
|
|
323
|
+
}
|
|
324
|
+
return [hBar, wBar];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Video pipeline on ALREADY-DECODED frames (uniform size): T-aware
|
|
328
|
+
* smart_resize per frame → normalize → pad to even T by repeating the last
|
|
329
|
+
* frame → patchify with REAL temporal pairs (element order (c, tp, py, px)
|
|
330
|
+
* reads frame t·2+tp). File decoding is the AVFoundation sidecar's job. */
|
|
331
|
+
export function preprocessQwen3VLVideoFrames(
|
|
332
|
+
frames: RGBImage[],
|
|
333
|
+
opts: { sampleFps?: number } = {},
|
|
334
|
+
): Qwen3VLPreprocessed {
|
|
335
|
+
if (frames.length === 0) throw new Error("video needs at least one frame");
|
|
336
|
+
// Frame timestamps: the sidecar samples at exact times k/fps, so frame k
|
|
337
|
+
// sits at k/fps seconds; padding repeats the last frame's time (the
|
|
338
|
+
// reference extends frames_indices with the last index). Group timestamp
|
|
339
|
+
// = pair average (transformers _calculate_timestamps).
|
|
340
|
+
const fps = opts.sampleFps ?? 2;
|
|
341
|
+
const { height: H0, width: W0 } = frames[0]!;
|
|
342
|
+
for (const f of frames)
|
|
343
|
+
if (f.height !== H0 || f.width !== W0)
|
|
344
|
+
throw new Error("video frames must share one size");
|
|
345
|
+
const [h, w] = smartResizeVideo(frames.length, H0, W0);
|
|
346
|
+
const sized = frames.map((f) =>
|
|
347
|
+
h === f.height && w === f.width ? f : pilResizeBicubic(f, w, h));
|
|
348
|
+
// Pad to a multiple of the temporal patch size (repeat the last frame).
|
|
349
|
+
const tps = QWEN3VL_TEMPORAL_PATCH_SIZE;
|
|
350
|
+
const frameTimes = frames.map((_, k) => k / fps);
|
|
351
|
+
while (sized.length % tps !== 0) {
|
|
352
|
+
sized.push(sized[sized.length - 1]!);
|
|
353
|
+
frameTimes.push(frameTimes[frameTimes.length - 1]!);
|
|
354
|
+
}
|
|
355
|
+
const groupTimestamps: number[] = [];
|
|
356
|
+
for (let i = 0; i < frameTimes.length; i += tps)
|
|
357
|
+
groupTimestamps.push((frameTimes[i]! + frameTimes[i + tps - 1]!) / 2);
|
|
358
|
+
|
|
359
|
+
const ps = QWEN3VL_PATCH_SIZE;
|
|
360
|
+
const ms = QWEN3VL_MERGE_SIZE;
|
|
361
|
+
const C = 3;
|
|
362
|
+
const gridT = sized.length / tps;
|
|
363
|
+
const gridH = h / ps;
|
|
364
|
+
const gridW = w / ps;
|
|
365
|
+
const rows = gridT * gridH * gridW;
|
|
366
|
+
const cols = C * tps * ps * ps;
|
|
367
|
+
const out = new Float32Array(rows * cols);
|
|
368
|
+
const RESCALE = Math.fround(1 / 255);
|
|
369
|
+
const norm = new Float32Array(256);
|
|
370
|
+
for (let i = 0; i < 256; i++)
|
|
371
|
+
norm[i] = Math.fround((Math.fround(i * RESCALE) - 0.5) / 0.5);
|
|
372
|
+
const hBlocks = gridH / ms;
|
|
373
|
+
const wBlocks = gridW / ms;
|
|
374
|
+
let r = 0;
|
|
375
|
+
for (let t = 0; t < gridT; t++) {
|
|
376
|
+
for (let h1 = 0; h1 < hBlocks; h1++) {
|
|
377
|
+
for (let w1 = 0; w1 < wBlocks; w1++) {
|
|
378
|
+
for (let mh = 0; mh < ms; mh++) {
|
|
379
|
+
for (let mw = 0; mw < ms; mw++) {
|
|
380
|
+
const hPatch = h1 * ms + mh;
|
|
381
|
+
const wPatch = w1 * ms + mw;
|
|
382
|
+
const base = r * cols;
|
|
383
|
+
for (let c = 0; c < C; c++) {
|
|
384
|
+
for (let tp = 0; tp < tps; tp++) {
|
|
385
|
+
const frame = sized[t * tps + tp]!.data;
|
|
386
|
+
for (let py = 0; py < ps; py++) {
|
|
387
|
+
const y = hPatch * ps + py;
|
|
388
|
+
const rowOff = (y * w + wPatch * ps) * 3 + c;
|
|
389
|
+
const dst = base + ((c * tps + tp) * ps + py) * ps;
|
|
390
|
+
for (let px = 0; px < ps; px++)
|
|
391
|
+
out[dst + px] = norm[frame[rowOff + px * 3]!]!;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
r++;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return {
|
|
402
|
+
pixelValues: out,
|
|
403
|
+
rows,
|
|
404
|
+
cols,
|
|
405
|
+
gridThw: [gridT, gridH, gridW],
|
|
406
|
+
imageTokens: gridT * (gridH / ms) * (gridW / ms),
|
|
407
|
+
groupTimestamps,
|
|
408
|
+
};
|
|
409
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
// Qwen3.8 vision prompt assembly — mirrors mlx-vlm's processor +
|
|
2
|
+
// get_input_embeddings flow:
|
|
3
|
+
//
|
|
4
|
+
// template renders each {type:"image"} part as
|
|
5
|
+
// <|vision_start|><|image_pad|><|vision_end|> → every <|image_pad|>
|
|
6
|
+
// is EXPANDED to gridT*(gridH/2)*(gridW/2) copies (the processor's
|
|
7
|
+
// merge_length expansion) → embed_tokens(ids) with the tower's merged
|
|
8
|
+
// features overwriting the image-token rows (masked_scatter ≡ segment
|
|
9
|
+
// concat for contiguous spans) → get_rope_index positions + delta.
|
|
10
|
+
//
|
|
11
|
+
// One tower call per image — attention never crosses cu_seqlens boundaries
|
|
12
|
+
// and pos/rope embeds are per-grid, so per-image encoding is value-identical
|
|
13
|
+
// to the reference's single batched call.
|
|
14
|
+
|
|
15
|
+
import { MlxArray } from "@mlx-bun/mlx/array";
|
|
16
|
+
import * as ops from "@mlx-bun/mlx/ops";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import type { TextEmbeddingModel } from "../../contracts/mlx/media";
|
|
19
|
+
import { type MropeRequestState } from "../../contracts/mlx/positions";
|
|
20
|
+
import { qwenRopeIndex } from "../../layers/qwen-mrope";
|
|
21
|
+
import type { EncoderCache } from "../../state/encoder-cache";
|
|
22
|
+
import type { ChatMessage,ChatTemplate } from "../chat-template";
|
|
23
|
+
import type { LoadedTokenizer } from "../tokenizer";
|
|
24
|
+
import { preprocessQwen3VLImage,preprocessQwen3VLVideoFrames,pyFixed1,QWEN3VL_MERGE_SIZE,type Qwen3VLPreprocessed } from "./qwen3vl-preprocess";
|
|
25
|
+
import { extractVideoFrames } from "./video-frames";
|
|
26
|
+
/** A Qwen-compatible image encoder; the caller chooses its implementation. */
|
|
27
|
+
export interface QwenVisionEncoder {
|
|
28
|
+
readonly cacheIdentity?: string;
|
|
29
|
+
encode(input: Qwen3VLPreprocessed): MlxArray;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Qwen3VLTokenIds {
|
|
33
|
+
imageTokenId: number; // <|image_pad|>
|
|
34
|
+
videoTokenId: number; // <|video_pad|>
|
|
35
|
+
/** <|vision_start|> / <|vision_end|> — the per-frame-group wrappers the
|
|
36
|
+
* video expansion emits (defaults are the Qwen3.5 family ids). */
|
|
37
|
+
visionStartId?: number;
|
|
38
|
+
visionEndId?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface Qwen3VLVisionPrompt {
|
|
42
|
+
ids: number[];
|
|
43
|
+
prefixIdentity?: string;
|
|
44
|
+
/** [1, L, H] bf16 spliced input embeddings (caller owns → generate()). */
|
|
45
|
+
embeddings: MlxArray;
|
|
46
|
+
/** The request's mRoPE positions state (the media input binds it to its forwards). */
|
|
47
|
+
mrope: MropeRequestState;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function buildQwen3VLVisionPrompt(
|
|
51
|
+
model: TextEmbeddingModel,
|
|
52
|
+
tower: QwenVisionEncoder,
|
|
53
|
+
tokenizer: LoadedTokenizer,
|
|
54
|
+
template: ChatTemplate,
|
|
55
|
+
messages: ChatMessage[],
|
|
56
|
+
images: Uint8Array[],
|
|
57
|
+
tokenIds: Qwen3VLTokenIds,
|
|
58
|
+
renderOptions: Parameters<ChatTemplate["render"]>[1] = {},
|
|
59
|
+
videos: Uint8Array[] = [],
|
|
60
|
+
nativeWork: <T>(work: () => Promise<T>) => Promise<T> = work => work(),
|
|
61
|
+
encoderCache?: EncoderCache,
|
|
62
|
+
): Promise<Qwen3VLVisionPrompt> {
|
|
63
|
+
// The request's full template options (tools, enableThinking,
|
|
64
|
+
// reasoningEffort, preserveThinking) flow through — a media prompt must
|
|
65
|
+
// honor the same thinking controls as a text one.
|
|
66
|
+
const rendered = template.render(messages, {
|
|
67
|
+
...renderOptions, addGenerationPrompt: true,
|
|
68
|
+
});
|
|
69
|
+
const rawIds = tokenizer.encode(rendered, /* addSpecialTokens */ false);
|
|
70
|
+
const imagePads = rawIds.filter((t) => t === tokenIds.imageTokenId).length;
|
|
71
|
+
const videoPads = rawIds.filter((t) => t === tokenIds.videoTokenId).length;
|
|
72
|
+
if (imagePads !== images.length)
|
|
73
|
+
throw new Error(
|
|
74
|
+
`prompt renders ${imagePads} image slots but ${images.length} images were supplied`,
|
|
75
|
+
);
|
|
76
|
+
if (videoPads !== videos.length)
|
|
77
|
+
throw new Error(
|
|
78
|
+
`prompt renders ${videoPads} video slots but ${videos.length} videos were supplied`,
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
// Preprocess each medium in its own appearance order; videos decode to
|
|
82
|
+
// sampled frames through the AVFoundation sidecar first.
|
|
83
|
+
const imagePps: Qwen3VLPreprocessed[] = [];
|
|
84
|
+
for (const img of images) imagePps.push(await preprocessQwen3VLImage(img));
|
|
85
|
+
const videoPps: Qwen3VLPreprocessed[] = [];
|
|
86
|
+
for (const vid of videos)
|
|
87
|
+
videoPps.push(preprocessQwen3VLVideoFrames(await extractVideoFrames(vid)));
|
|
88
|
+
|
|
89
|
+
// Expand each pad token; collect grids in PROMPT order (get_rope_index
|
|
90
|
+
// consumes image/video grids interleaved). Images expand to one contiguous
|
|
91
|
+
// run. Videos follow the TRAINING-TIME processor (transformers
|
|
92
|
+
// replace_video_token — mlx-vlm 0.6.14 lacks this and is NOT the oracle
|
|
93
|
+
// here): each temporal frame group renders as
|
|
94
|
+
// <{t:.1f} seconds><|vision_start|>{pads}<|vision_end|>
|
|
95
|
+
// inside the template's outer vision wrappers, with a PER-GROUP t=1 grid
|
|
96
|
+
// (the reference splits video_grid_thw per frame — "timestamps are used
|
|
97
|
+
// to separate videos"). Timestamp text always sits between special
|
|
98
|
+
// tokens, so per-segment encoding equals whole-string tokenization.
|
|
99
|
+
const visionStartId = tokenIds.visionStartId ?? 248053;
|
|
100
|
+
const visionEndId = tokenIds.visionEndId ?? 248054;
|
|
101
|
+
const ids: number[] = [];
|
|
102
|
+
const grids: [number, number, number][] = [];
|
|
103
|
+
let imgIdx = 0;
|
|
104
|
+
let vidIdx = 0;
|
|
105
|
+
let lastMediaEnd = 0;
|
|
106
|
+
for (const t of rawIds) {
|
|
107
|
+
if (t === tokenIds.imageTokenId) {
|
|
108
|
+
const pp = imagePps[imgIdx++]!;
|
|
109
|
+
grids.push(pp.gridThw);
|
|
110
|
+
for (let i = 0; i < pp.imageTokens; i++) ids.push(tokenIds.imageTokenId);
|
|
111
|
+
lastMediaEnd = ids.length;
|
|
112
|
+
} else if (t === tokenIds.videoTokenId) {
|
|
113
|
+
const pp = videoPps[vidIdx++]!;
|
|
114
|
+
const [gridT, gridH, gridW] = pp.gridThw;
|
|
115
|
+
const frameTokens = pp.imageTokens / gridT;
|
|
116
|
+
const ts = pp.groupTimestamps ?? [];
|
|
117
|
+
for (let g = 0; g < gridT; g++) {
|
|
118
|
+
const header = `<${pyFixed1(ts[g] ?? g)} seconds>`;
|
|
119
|
+
for (const tok of tokenizer.encode(header, false)) ids.push(tok);
|
|
120
|
+
ids.push(visionStartId);
|
|
121
|
+
grids.push([1, gridH, gridW]);
|
|
122
|
+
for (let i = 0; i < frameTokens; i++) ids.push(tokenIds.videoTokenId);
|
|
123
|
+
ids.push(visionEndId);
|
|
124
|
+
}
|
|
125
|
+
lastMediaEnd = ids.length;
|
|
126
|
+
} else ids.push(t);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const mrope = qwenRopeIndex(
|
|
130
|
+
ids, grids, QWEN3VL_MERGE_SIZE, tokenIds.imageTokenId, tokenIds.videoTokenId,
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
// Text embeddings, then splice the tower features over the media spans by
|
|
134
|
+
// segment concatenation (spans are contiguous runs of their pad token).
|
|
135
|
+
// Everything mlx-allocated here is owned by THIS function until the
|
|
136
|
+
// final embeddings hand-off, so a throw mid-splice (tower.encode on media
|
|
137
|
+
// 2 of 3, an mlx graph error) must dispose the lot — the caller's 400
|
|
138
|
+
// path can't reach any of it (2026-08-18 review: repeated failing media
|
|
139
|
+
// requests would otherwise strand un-admitted GPU memory on the GC
|
|
140
|
+
// backstop).
|
|
141
|
+
// Look up exact preprocessed content before entering the execution queue.
|
|
142
|
+
// URLs are not identities: their contents can change. Position/timestamp
|
|
143
|
+
// assembly above remains request-owned even when encoder features are reused.
|
|
144
|
+
const inputs = [...imagePps, ...videoPps];
|
|
145
|
+
const keys = encoderCache ? inputs.map(pp => createHash("sha256")
|
|
146
|
+
.update(`qwen3vl-v1:${JSON.stringify(pp.gridThw)}:${pp.rows}:${pp.cols}:`)
|
|
147
|
+
.update(new Uint8Array(pp.pixelValues.buffer, pp.pixelValues.byteOffset, pp.pixelValues.byteLength))
|
|
148
|
+
.digest("hex")) : [];
|
|
149
|
+
const prefixIdentity = encoderCache && lastMediaEnd > 0
|
|
150
|
+
? createHash("sha256").update("qwen-prepared-prefix-v1").update(encoderCache.identity)
|
|
151
|
+
.update(JSON.stringify({ keys, tokens: ids.slice(0, lastMediaEnd), delta: mrope.delta,
|
|
152
|
+
positions: mrope.positions.map(axis => Array.from(axis.slice(0, lastMediaEnd))),
|
|
153
|
+
})).digest("hex") : undefined;
|
|
154
|
+
const reused: Array<MlxArray | null> = [];
|
|
155
|
+
try {
|
|
156
|
+
for (const key of keys) reused.push(await encoderCache!.take(key));
|
|
157
|
+
return await nativeWork(async () => {
|
|
158
|
+
const encode = (index: number): MlxArray => {
|
|
159
|
+
const cached = reused[index];
|
|
160
|
+
if (cached) return cached.slice([0, 0], [...cached.shape]);
|
|
161
|
+
const features = tower.encode(inputs[index]!);
|
|
162
|
+
try { if (encoderCache) encoderCache.put(keys[index]!, features); }
|
|
163
|
+
catch (error) { features.dispose(); throw error; }
|
|
164
|
+
return features;
|
|
165
|
+
};
|
|
166
|
+
const idsArr = ops.fromInt32(ids, [1, ids.length]);
|
|
167
|
+
const textEmb = model.embed.encode(idsArr); // [1, L, H]
|
|
168
|
+
idsArr.dispose();
|
|
169
|
+
const owned: MlxArray[] = [];
|
|
170
|
+
try {
|
|
171
|
+
const H = textEmb.shape[2]!;
|
|
172
|
+
const segments: MlxArray[] = [];
|
|
173
|
+
let cursor = 0;
|
|
174
|
+
imgIdx = 0;
|
|
175
|
+
vidIdx = 0;
|
|
176
|
+
// A video's tower features cover ALL its frame groups; consecutive pad
|
|
177
|
+
// RUNS consume consecutive feature-row windows.
|
|
178
|
+
let vidFeat: MlxArray | null = null;
|
|
179
|
+
let vidRow = 0;
|
|
180
|
+
for (let i = 0; i < ids.length; ) {
|
|
181
|
+
const isImage = ids[i] === tokenIds.imageTokenId;
|
|
182
|
+
const isVideo = ids[i] === tokenIds.videoTokenId;
|
|
183
|
+
if (isImage || isVideo) {
|
|
184
|
+
// Measure this contiguous pad run.
|
|
185
|
+
let runEnd = i;
|
|
186
|
+
while (runEnd < ids.length && ids[runEnd] === ids[i]) runEnd++;
|
|
187
|
+
const runLen = runEnd - i;
|
|
188
|
+
if (cursor < i) {
|
|
189
|
+
const seg = textEmb.slice([0, cursor, 0], [1, i, H]);
|
|
190
|
+
segments.push(seg);
|
|
191
|
+
owned.push(seg);
|
|
192
|
+
}
|
|
193
|
+
let rows: MlxArray;
|
|
194
|
+
if (isImage) {
|
|
195
|
+
const feat = encode(imgIdx++); // [runLen, H]
|
|
196
|
+
owned.push(feat);
|
|
197
|
+
rows = feat;
|
|
198
|
+
} else {
|
|
199
|
+
if (!vidFeat) {
|
|
200
|
+
vidFeat = encode(imagePps.length + vidIdx); // [imageTokens, H]
|
|
201
|
+
owned.push(vidFeat);
|
|
202
|
+
vidRow = 0;
|
|
203
|
+
}
|
|
204
|
+
const sl = vidFeat.slice([vidRow, 0], [vidRow + runLen, H]);
|
|
205
|
+
owned.push(sl);
|
|
206
|
+
rows = sl;
|
|
207
|
+
vidRow += runLen;
|
|
208
|
+
if (vidRow >= videoPps[vidIdx]!.imageTokens) {
|
|
209
|
+
vidFeat = null;
|
|
210
|
+
vidIdx++;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const feat3 = ops.reshape(rows, [1, runLen, H]);
|
|
214
|
+
segments.push(feat3);
|
|
215
|
+
owned.push(feat3);
|
|
216
|
+
cursor = runEnd;
|
|
217
|
+
i = cursor;
|
|
218
|
+
} else i++;
|
|
219
|
+
}
|
|
220
|
+
if (cursor < ids.length) {
|
|
221
|
+
const seg = textEmb.slice([0, cursor, 0], [1, ids.length, H]);
|
|
222
|
+
segments.push(seg);
|
|
223
|
+
owned.push(seg);
|
|
224
|
+
}
|
|
225
|
+
const embeddings = segments.length === 1
|
|
226
|
+
? ops.contiguous(segments[0]!)
|
|
227
|
+
: ops.concatAxis(segments, 1);
|
|
228
|
+
return { ids, embeddings, mrope, prefixIdentity };
|
|
229
|
+
} finally {
|
|
230
|
+
for (const s of owned) s.dispose();
|
|
231
|
+
textEmb.dispose();
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
} finally {
|
|
235
|
+
for (const features of reused) features?.dispose();
|
|
236
|
+
}
|
|
237
|
+
}
|