@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,549 @@
|
|
|
1
|
+
// DiffusionGemma vision tower — DEDICATED, parity-exact port of optiq's
|
|
2
|
+
// gemma4 `VisionModel` (optiq/vlm/_mlxvlm/models/gemma4/vision.py) at the
|
|
3
|
+
// DiffusionGemma geometry (hidden 1152, head_dim 72, 16 heads, 27 layers,
|
|
4
|
+
// position_embedding_size 10240, standardize ON). This is its OWN module, not a
|
|
5
|
+
// reuse of the e4b SigLIP path — the two are separate models with separate
|
|
6
|
+
// towers (e4b ships a bf16 optiq_vision.safetensors sidecar; DiffusionGemma's
|
|
7
|
+
// vision is inline-quantized in the main shards). Ported op-for-op so it is
|
|
8
|
+
// bit-exact to the optiq reference.
|
|
9
|
+
//
|
|
10
|
+
// Forward (reference VisionModel.__call__):
|
|
11
|
+
// pixels [1,3,H,W] → patchify (reshape/transpose, 2*(x-0.5)) → input_proj
|
|
12
|
+
// + 2D position embedding (gather table[0,x]+table[1,y]) → PAD to
|
|
13
|
+
// max_patches=2520 (zeros) → 27× transformer blocks (manual-f32 q/k/v RMS,
|
|
14
|
+
// 2D multidimensional RoPE, bidirectional -1e4 mask, scale=1.0, GeGLU) →
|
|
15
|
+
// position-grouped 3×3 avg-pool to 280 (×√hidden) → trim to the real soft
|
|
16
|
+
// tokens → standardize (h - std_bias)*std_scale → MultimodalEmbedder
|
|
17
|
+
// (RMSNormNoScale → projection 1152→2816).
|
|
18
|
+
// Output = `getImageFeatures`: [1, softTokens, textHidden], scattered AS-IS into
|
|
19
|
+
// the prompt embeddings (NO /embed_scale — the diffusion merge adds it once via
|
|
20
|
+
// embed_tokens*embed_scale).
|
|
21
|
+
//
|
|
22
|
+
// The vision linears are 4-bit quantized inline; we run them as QuantizedLinear
|
|
23
|
+
// (== the reference's nn.quantize'd modules), not dequant+matmul.
|
|
24
|
+
|
|
25
|
+
import type { ModelConfig } from "../../artifacts/config";
|
|
26
|
+
import type { Weights } from "../../artifacts/weights";
|
|
27
|
+
import { MlxArray } from "@mlx-bun/mlx/array";
|
|
28
|
+
import { Dtype } from "@mlx-bun/mlx/ffi";
|
|
29
|
+
import * as ops from "@mlx-bun/mlx/ops";
|
|
30
|
+
import { disposing } from "../../layers/helpers";
|
|
31
|
+
import { QuantizedLinear } from "../../layers/quantized-linear";
|
|
32
|
+
import { RMSNorm } from "../../layers/normalization";
|
|
33
|
+
import { applyRope2d, rope2dTables, type Rope2dTables } from "../../layers/rope-2d";
|
|
34
|
+
import { parseSiglipConfig, type SiglipVisionConfig } from "../vision/siglip";
|
|
35
|
+
import { decodeImage, resizeBicubic } from "../../input/vision/preprocess";
|
|
36
|
+
|
|
37
|
+
const VP = "model.encoder.vision_tower.";
|
|
38
|
+
|
|
39
|
+
/** Expand each `<|image|>` placeholder id into `boi + image*softCount + eoi`,
|
|
40
|
+
* matching optiq's `_build_image_inputs`. Returns the spliced ids (the
|
|
41
|
+
* diffusion engine's encoder prefills the merged vision features at the
|
|
42
|
+
* contiguous image run). */
|
|
43
|
+
export function spliceImageTokens(
|
|
44
|
+
ids: number[],
|
|
45
|
+
softCounts: number[],
|
|
46
|
+
tokenIds: { image: number; boi: number; eoi: number },
|
|
47
|
+
): number[] {
|
|
48
|
+
const out: number[] = [];
|
|
49
|
+
let k = 0;
|
|
50
|
+
for (const id of ids) {
|
|
51
|
+
if (id === tokenIds.image) {
|
|
52
|
+
out.push(tokenIds.boi);
|
|
53
|
+
const n = softCounts[k] ?? softCounts[softCounts.length - 1] ?? 0;
|
|
54
|
+
for (let i = 0; i < n; i++) out.push(tokenIds.image);
|
|
55
|
+
out.push(tokenIds.eoi);
|
|
56
|
+
k++;
|
|
57
|
+
} else {
|
|
58
|
+
out.push(id);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A vision linear that is EITHER 4-bit quantized (q/k/v/o, gate/up, input_proj,
|
|
65
|
+
* embedding_projection) OR plain bf16 (down_proj is full-precision). Matches the
|
|
66
|
+
* reference, where nn.quantize skips the unquantized `down_proj`. */
|
|
67
|
+
class VisionLinear {
|
|
68
|
+
private constructor(
|
|
69
|
+
readonly q: QuantizedLinear | null,
|
|
70
|
+
readonly w: MlxArray | null,
|
|
71
|
+
) {}
|
|
72
|
+
static load(weights: Weights, config: ModelConfig, path: string): VisionLinear {
|
|
73
|
+
if (weights.has(`${path}.scales`))
|
|
74
|
+
return new VisionLinear(QuantizedLinear.load(weights, path, config), null);
|
|
75
|
+
return new VisionLinear(null, weights.tensor(`${path}.weight`));
|
|
76
|
+
}
|
|
77
|
+
/** The dtype of the underlying weight tensor — uint32 for a quantized linear
|
|
78
|
+
* (the packed weight), the float dtype for a plain one. The reference
|
|
79
|
+
* patch-embedder casts its input to THIS dtype (a uint32 truncation for the
|
|
80
|
+
* quantized diffusion input_proj — see #patchify). */
|
|
81
|
+
get weightDtype(): Dtype {
|
|
82
|
+
return (this.q ? this.q.w : this.w!).dtype;
|
|
83
|
+
}
|
|
84
|
+
forward(x: MlxArray): MlxArray {
|
|
85
|
+
if (this.q) return this.q.forward(x);
|
|
86
|
+
const xc = x.astype(this.w!.dtype);
|
|
87
|
+
const wT = ops.transposeAxes(this.w!, [1, 0]);
|
|
88
|
+
const out = ops.matmul(xc, wT);
|
|
89
|
+
xc.dispose();
|
|
90
|
+
wT.dispose();
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Manual fp32 RMS norm matching the reference VisionRMSNorm / NoScale:
|
|
96
|
+
* x_f32 * rsqrt(mean(x²)+eps) [* weight_f32], cast back. (NOT the fused kernel
|
|
97
|
+
* — the reference q/k/v norms are decomposed f32.) */
|
|
98
|
+
function manualRms(x: MlxArray, weight: MlxArray | null, eps: number): MlxArray {
|
|
99
|
+
const xf = x.astype(Dtype.float32);
|
|
100
|
+
const sq = ops.mul(xf, xf);
|
|
101
|
+
const varr = ops.meanAxis(sq, -1, true);
|
|
102
|
+
sq.dispose();
|
|
103
|
+
const epsArr = ops.scalarLike(eps, varr);
|
|
104
|
+
const denom = ops.add(varr, epsArr);
|
|
105
|
+
varr.dispose();
|
|
106
|
+
epsArr.dispose();
|
|
107
|
+
const rs = ops.rsqrt(denom);
|
|
108
|
+
denom.dispose();
|
|
109
|
+
let normed = ops.mul(xf, rs);
|
|
110
|
+
xf.dispose();
|
|
111
|
+
rs.dispose();
|
|
112
|
+
if (weight) {
|
|
113
|
+
const wf = weight.astype(Dtype.float32);
|
|
114
|
+
normed = disposing(normed, ops.mul(normed, wf));
|
|
115
|
+
wf.dispose();
|
|
116
|
+
}
|
|
117
|
+
const out = normed.astype(x.dtype);
|
|
118
|
+
normed.dispose();
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Pad the last dim of x up to `target` with zeros (for the fused-SDPA head_dim
|
|
123
|
+
* padding, reference ensure_fused_sdpa). */
|
|
124
|
+
function padLastDim(x: MlxArray, target: number): MlxArray {
|
|
125
|
+
const sh = x.shape;
|
|
126
|
+
const D = sh[sh.length - 1]!;
|
|
127
|
+
if (D >= target) return x;
|
|
128
|
+
const padShape = [...sh];
|
|
129
|
+
padShape[padShape.length - 1] = target - D;
|
|
130
|
+
const zeros = ops.zeros(padShape, x.dtype);
|
|
131
|
+
const out = ops.concatAxis([x, zeros], -1);
|
|
132
|
+
zeros.dispose();
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
class DiffVisionAttention {
|
|
137
|
+
readonly qProj: VisionLinear;
|
|
138
|
+
readonly kProj: VisionLinear;
|
|
139
|
+
readonly vProj: VisionLinear;
|
|
140
|
+
readonly oProj: VisionLinear;
|
|
141
|
+
readonly qNorm: MlxArray;
|
|
142
|
+
readonly kNorm: MlxArray;
|
|
143
|
+
readonly nHeads: number;
|
|
144
|
+
readonly nKvHeads: number;
|
|
145
|
+
readonly headDim: number;
|
|
146
|
+
readonly eps: number;
|
|
147
|
+
constructor(w: Weights, config: ModelConfig, cfg: SiglipVisionConfig, prefix: string) {
|
|
148
|
+
this.qProj = VisionLinear.load(w, config, `${prefix}.q_proj.linear`);
|
|
149
|
+
this.kProj = VisionLinear.load(w, config, `${prefix}.k_proj.linear`);
|
|
150
|
+
this.vProj = VisionLinear.load(w, config, `${prefix}.v_proj.linear`);
|
|
151
|
+
this.oProj = VisionLinear.load(w, config, `${prefix}.o_proj.linear`);
|
|
152
|
+
this.qNorm = w.tensor(`${prefix}.q_norm.weight`);
|
|
153
|
+
this.kNorm = w.tensor(`${prefix}.k_norm.weight`);
|
|
154
|
+
this.nHeads = cfg.numHeads;
|
|
155
|
+
this.nKvHeads = cfg.numKvHeads;
|
|
156
|
+
this.headDim = cfg.headDim;
|
|
157
|
+
this.eps = cfg.rmsNormEps;
|
|
158
|
+
}
|
|
159
|
+
forward(x: MlxArray, rope: Rope2dTables, mask: MlxArray): MlxArray {
|
|
160
|
+
const [B, L] = x.shape as [number, number, number];
|
|
161
|
+
const qf = this.qProj.forward(x);
|
|
162
|
+
let q = ops.reshape(qf, [B, L, this.nHeads, this.headDim]);
|
|
163
|
+
qf.dispose();
|
|
164
|
+
const kf = this.kProj.forward(x);
|
|
165
|
+
let k = ops.reshape(kf, [B, L, this.nKvHeads, this.headDim]);
|
|
166
|
+
kf.dispose();
|
|
167
|
+
const vf = this.vProj.forward(x);
|
|
168
|
+
let v = ops.reshape(vf, [B, L, this.nKvHeads, this.headDim]);
|
|
169
|
+
vf.dispose();
|
|
170
|
+
|
|
171
|
+
q = disposing(q, manualRms(q, this.qNorm, this.eps));
|
|
172
|
+
k = disposing(k, manualRms(k, this.kNorm, this.eps));
|
|
173
|
+
v = disposing(v, manualRms(v, null, this.eps));
|
|
174
|
+
|
|
175
|
+
q = disposing(q, applyRope2d(q, rope));
|
|
176
|
+
k = disposing(k, applyRope2d(k, rope));
|
|
177
|
+
|
|
178
|
+
q = disposing(q, ops.transposeAxes(q, [0, 2, 1, 3]));
|
|
179
|
+
k = disposing(k, ops.transposeAxes(k, [0, 2, 1, 3]));
|
|
180
|
+
v = disposing(v, ops.transposeAxes(v, [0, 2, 1, 3]));
|
|
181
|
+
|
|
182
|
+
// Reference ensure_fused_sdpa: head_dim 72 isn't a fused-SDPA size, so it
|
|
183
|
+
// PADS q/k/v to 80 (zeros, no effect on scores — the extra dims are 0),
|
|
184
|
+
// runs the fused kernel, and slices back to 72. Replicate exactly: mlx's
|
|
185
|
+
// SDPA path/numerics differ for an unpadded 72 vs the padded-80 fused path.
|
|
186
|
+
const D = this.headDim;
|
|
187
|
+
const target = D <= 64 ? 64 : D <= 80 ? 80 : D <= 128 ? 128 : D;
|
|
188
|
+
if (target !== D) {
|
|
189
|
+
q = disposing(q, padLastDim(q, target));
|
|
190
|
+
k = disposing(k, padLastDim(k, target));
|
|
191
|
+
v = disposing(v, padLastDim(v, target));
|
|
192
|
+
}
|
|
193
|
+
let attn = ops.sdpa(q, k, v, 1.0, "array", mask);
|
|
194
|
+
q.dispose();
|
|
195
|
+
k.dispose();
|
|
196
|
+
v.dispose();
|
|
197
|
+
if (target !== D) {
|
|
198
|
+
const sh = attn.shape;
|
|
199
|
+
attn = disposing(attn, attn.slice(sh.map(() => 0), sh.map((s, i) => (i === sh.length - 1 ? D : s))));
|
|
200
|
+
}
|
|
201
|
+
let o = ops.transposeAxes(attn, [0, 2, 1, 3]);
|
|
202
|
+
attn.dispose();
|
|
203
|
+
o = disposing(o, ops.reshape(o, [B, L, this.nHeads * this.headDim]));
|
|
204
|
+
const out = this.oProj.forward(o);
|
|
205
|
+
o.dispose();
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** GeGLU stays uncompiled here: the reference vision MLP is plain
|
|
211
|
+
* `nn.gelu_approx(gate) * up`, not the language model's @mx.compile'd geglu. */
|
|
212
|
+
class DiffVisionMLP {
|
|
213
|
+
readonly gate: VisionLinear;
|
|
214
|
+
readonly up: VisionLinear;
|
|
215
|
+
readonly down: VisionLinear;
|
|
216
|
+
constructor(w: Weights, config: ModelConfig, prefix: string) {
|
|
217
|
+
this.gate = VisionLinear.load(w, config, `${prefix}.gate_proj.linear`);
|
|
218
|
+
this.up = VisionLinear.load(w, config, `${prefix}.up_proj.linear`);
|
|
219
|
+
this.down = VisionLinear.load(w, config, `${prefix}.down_proj.linear`);
|
|
220
|
+
}
|
|
221
|
+
forward(x: MlxArray): MlxArray {
|
|
222
|
+
const g = this.gate.forward(x);
|
|
223
|
+
const act = ops.geluApprox(g);
|
|
224
|
+
g.dispose();
|
|
225
|
+
const u = this.up.forward(x);
|
|
226
|
+
const m = ops.mul(act, u);
|
|
227
|
+
act.dispose();
|
|
228
|
+
u.dispose();
|
|
229
|
+
const out = this.down.forward(m);
|
|
230
|
+
m.dispose();
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
class DiffVisionBlock {
|
|
236
|
+
readonly attn: DiffVisionAttention;
|
|
237
|
+
readonly mlp: DiffVisionMLP;
|
|
238
|
+
readonly inputNorm: RMSNorm;
|
|
239
|
+
readonly postAttnNorm: RMSNorm;
|
|
240
|
+
readonly preFfNorm: RMSNorm;
|
|
241
|
+
readonly postFfNorm: RMSNorm;
|
|
242
|
+
constructor(w: Weights, config: ModelConfig, cfg: SiglipVisionConfig, prefix: string) {
|
|
243
|
+
this.attn = new DiffVisionAttention(w, config, cfg, `${prefix}.self_attn`);
|
|
244
|
+
this.mlp = new DiffVisionMLP(w, config, `${prefix}.mlp`);
|
|
245
|
+
const norm = (n: string) => new RMSNorm(w.tensor(`${prefix}.${n}.weight`), cfg.rmsNormEps);
|
|
246
|
+
this.inputNorm = norm("input_layernorm");
|
|
247
|
+
this.postAttnNorm = norm("post_attention_layernorm");
|
|
248
|
+
this.preFfNorm = norm("pre_feedforward_layernorm");
|
|
249
|
+
this.postFfNorm = norm("post_feedforward_layernorm");
|
|
250
|
+
}
|
|
251
|
+
forward(x: MlxArray, rope: Rope2dTables, mask: MlxArray): MlxArray {
|
|
252
|
+
const normed = this.inputNorm.forward(x);
|
|
253
|
+
let attnOut = this.attn.forward(normed, rope, mask);
|
|
254
|
+
normed.dispose();
|
|
255
|
+
attnOut = disposing(attnOut, this.postAttnNorm.forward(attnOut));
|
|
256
|
+
const h = ops.add(x, attnOut);
|
|
257
|
+
attnOut.dispose();
|
|
258
|
+
const normedH = this.preFfNorm.forward(h);
|
|
259
|
+
let ffw = this.mlp.forward(normedH);
|
|
260
|
+
normedH.dispose();
|
|
261
|
+
ffw = disposing(ffw, this.postFfNorm.forward(ffw));
|
|
262
|
+
const out = ops.add(h, ffw);
|
|
263
|
+
h.dispose();
|
|
264
|
+
ffw.dispose();
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export class DiffusionVisionTower {
|
|
270
|
+
readonly cfg: SiglipVisionConfig;
|
|
271
|
+
readonly inputProj: VisionLinear;
|
|
272
|
+
readonly posTable: MlxArray; // [2, posSize, hidden]
|
|
273
|
+
readonly layers: DiffVisionBlock[];
|
|
274
|
+
readonly stdBias: MlxArray | null;
|
|
275
|
+
readonly stdScale: MlxArray | null;
|
|
276
|
+
readonly embedProj: VisionLinear; // MultimodalEmbedder projection
|
|
277
|
+
readonly embedEps: number;
|
|
278
|
+
readonly maxPatches: number;
|
|
279
|
+
readonly patchSize: number;
|
|
280
|
+
readonly defaultOutputLength: number;
|
|
281
|
+
readonly rootHidden: number;
|
|
282
|
+
|
|
283
|
+
constructor(weights: Weights, config: ModelConfig) {
|
|
284
|
+
const raw = (config as unknown as { raw: Record<string, any> }).raw.vision_config;
|
|
285
|
+
const cfg = parseSiglipConfig(raw);
|
|
286
|
+
this.cfg = cfg;
|
|
287
|
+
this.patchSize = cfg.patchSize;
|
|
288
|
+
this.defaultOutputLength = cfg.defaultOutputLength;
|
|
289
|
+
this.maxPatches = cfg.defaultOutputLength * cfg.poolingKernelSize * cfg.poolingKernelSize;
|
|
290
|
+
this.rootHidden = Math.sqrt(cfg.hiddenSize);
|
|
291
|
+
this.embedEps = (raw.rms_norm_eps as number) ?? 1e-6;
|
|
292
|
+
|
|
293
|
+
this.inputProj = VisionLinear.load(weights, config, `${VP}patch_embedder.input_proj`);
|
|
294
|
+
this.posTable = weights.tensor(`${VP}patch_embedder.position_embedding_table`);
|
|
295
|
+
this.layers = Array.from(
|
|
296
|
+
{ length: cfg.numLayers },
|
|
297
|
+
(_, i) => new DiffVisionBlock(weights, config, cfg, `${VP}encoder.layers.${i}`),
|
|
298
|
+
);
|
|
299
|
+
this.stdBias = cfg.standardize ? weights.tensor(`${VP}std_bias`) : null;
|
|
300
|
+
this.stdScale = cfg.standardize ? weights.tensor(`${VP}std_scale`) : null;
|
|
301
|
+
this.embedProj = VisionLinear.load(weights, config, "model.encoder.embed_vision.embedding_projection");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Decode + aspect-preserving resize (multiples of pooling·patch=48, within the
|
|
305
|
+
* max_patches budget) + rescale 1/255 + channel-first. Mirrors optiq's
|
|
306
|
+
* gemma4 `preprocess_images` (BICUBIC, do_rescale, do_normalize=False).
|
|
307
|
+
* Returns pixel_values [1,3,H,W] f32 and the per-image soft-token count. */
|
|
308
|
+
async preprocess(bytes: Uint8Array): Promise<{ pixels: MlxArray; softTokens: number }> {
|
|
309
|
+
let img = await decodeImage(bytes);
|
|
310
|
+
const p = this.patchSize;
|
|
311
|
+
const k = this.cfg.poolingKernelSize;
|
|
312
|
+
const sideMult = p * k;
|
|
313
|
+
const targetPx = this.maxPatches * p * p;
|
|
314
|
+
const factor = Math.sqrt(targetPx / (img.height * img.width));
|
|
315
|
+
let th = Math.floor((factor * img.height) / sideMult) * sideMult;
|
|
316
|
+
let tw = Math.floor((factor * img.width) / sideMult) * sideMult;
|
|
317
|
+
const maxSide = Math.floor(this.maxPatches / (k * k)) * sideMult;
|
|
318
|
+
if (th === 0 && tw === 0) {
|
|
319
|
+
th = sideMult;
|
|
320
|
+
tw = sideMult;
|
|
321
|
+
} else if (th === 0) {
|
|
322
|
+
th = sideMult;
|
|
323
|
+
tw = Math.min(Math.floor(img.width / img.height) * sideMult, maxSide);
|
|
324
|
+
} else if (tw === 0) {
|
|
325
|
+
tw = sideMult;
|
|
326
|
+
th = Math.min(Math.floor(img.height / img.width) * sideMult, maxSide);
|
|
327
|
+
}
|
|
328
|
+
if (th !== img.height || tw !== img.width) img = resizeBicubic(img, tw, th);
|
|
329
|
+
|
|
330
|
+
const { width: W, height: H, data } = img;
|
|
331
|
+
// HWC uint8 -> CHW f32 / 255
|
|
332
|
+
const chw = new Float32Array(3 * H * W);
|
|
333
|
+
for (let y = 0; y < H; y++)
|
|
334
|
+
for (let x = 0; x < W; x++)
|
|
335
|
+
for (let c = 0; c < 3; c++)
|
|
336
|
+
chw[c * H * W + y * W + x] = data[(y * W + x) * 3 + c]! / 255;
|
|
337
|
+
const pixels = MlxArray.fromFloat32(chw, [1, 3, H, W]);
|
|
338
|
+
const softTokens = Math.floor((Math.floor(H / p) * Math.floor(W / p)) / (k * k));
|
|
339
|
+
return { pixels, softTokens };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Host-side patch positions (x,y) for the real patches + the padding mask,
|
|
343
|
+
* matching VisionModel._patch_positions_single (meshgrid xy, row-major). */
|
|
344
|
+
#positions(H: number, W: number): { real: Int32Array; numReal: number } {
|
|
345
|
+
const p = this.patchSize;
|
|
346
|
+
const pH = Math.floor(H / p);
|
|
347
|
+
const pW = Math.floor(W / p);
|
|
348
|
+
const numReal = pH * pW;
|
|
349
|
+
const real = new Int32Array(numReal * 2);
|
|
350
|
+
for (let y = 0; y < pH; y++)
|
|
351
|
+
for (let x = 0; x < pW; x++) {
|
|
352
|
+
const L = y * pW + x;
|
|
353
|
+
real[L * 2] = x;
|
|
354
|
+
real[L * 2 + 1] = y;
|
|
355
|
+
}
|
|
356
|
+
return { real, numReal };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** patchify: [1,3,H,W] -> [1, numReal, 3*p*p] (order p_row,p_col,C), 2*(x-0.5). */
|
|
360
|
+
#patchify(pixels: MlxArray): MlxArray {
|
|
361
|
+
const [B, C, H, W] = pixels.shape as [number, number, number, number];
|
|
362
|
+
const p = this.patchSize;
|
|
363
|
+
const pH = Math.floor(H / p);
|
|
364
|
+
const pW = Math.floor(W / p);
|
|
365
|
+
let t = ops.reshape(pixels, [B, C, pH, p, pW, p]);
|
|
366
|
+
t = disposing(t, ops.transposeAxes(t, [0, 2, 4, 3, 5, 1])); // [B,pH,pW,p,p,C]
|
|
367
|
+
t = disposing(t, ops.reshape(t, [B, pH * pW, C * p * p]));
|
|
368
|
+
// 2*(x - 0.5)
|
|
369
|
+
const half = ops.scalarLike(0.5, t);
|
|
370
|
+
t = disposing(t, ops.sub(t, half));
|
|
371
|
+
half.dispose();
|
|
372
|
+
t = disposing(t, ops.mulScalar(t, 2));
|
|
373
|
+
// Reference quirk: `patches.astype(self.input_proj.weight.dtype)`. The
|
|
374
|
+
// DiffusionGemma input_proj is QUANTIZED, so weight.dtype is uint32 and this
|
|
375
|
+
// TRUNCATES the patches to integers (mostly 0) before the matmul. The model
|
|
376
|
+
// was trained with this, so replicate it exactly (e4b's bf16 input_proj made
|
|
377
|
+
// it a no-op there). Back to a float the quantized matmul consumes.
|
|
378
|
+
t = disposing(t, t.astype(this.inputProj.weightDtype));
|
|
379
|
+
t = disposing(t, t.astype(Dtype.bfloat16));
|
|
380
|
+
return t;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Full tower forward over channel-first pixel_values [1,3,H,W] -> standardized
|
|
384
|
+
* pooled hidden [1, numRealSoft, hidden] (BEFORE the MultimodalEmbedder). */
|
|
385
|
+
visionTower(pixels: MlxArray, dbg?: (n: string, a: MlxArray) => void): MlxArray {
|
|
386
|
+
const [, , H, W] = pixels.shape as [number, number, number, number];
|
|
387
|
+
const { real, numReal } = this.#positions(H, W);
|
|
388
|
+
const k = this.cfg.poolingKernelSize;
|
|
389
|
+
const p = this.patchSize;
|
|
390
|
+
const pW = Math.floor(W / p);
|
|
391
|
+
const pH = Math.floor(H / p);
|
|
392
|
+
|
|
393
|
+
// --- patch embed (real patches only) ---
|
|
394
|
+
const patches = this.#patchify(pixels);
|
|
395
|
+
let embeds = this.inputProj.forward(patches); // [1, numReal, hidden]
|
|
396
|
+
patches.dispose();
|
|
397
|
+
|
|
398
|
+
// + 2D position embedding: table[0, x] + table[1, y]
|
|
399
|
+
const hidden = this.cfg.hiddenSize;
|
|
400
|
+
const posSize = this.cfg.positionEmbeddingSize;
|
|
401
|
+
const pxIdx = new Int32Array(numReal);
|
|
402
|
+
const pyIdx = new Int32Array(numReal);
|
|
403
|
+
for (let i = 0; i < numReal; i++) {
|
|
404
|
+
pxIdx[i] = real[i * 2]!;
|
|
405
|
+
pyIdx[i] = real[i * 2 + 1]!;
|
|
406
|
+
}
|
|
407
|
+
const plane0 = this.posTable.slice([0, 0, 0], [1, posSize, hidden]);
|
|
408
|
+
const t0r = ops.reshape(plane0, [posSize, hidden]);
|
|
409
|
+
plane0.dispose();
|
|
410
|
+
const plane1 = this.posTable.slice([1, 0, 0], [2, posSize, hidden]);
|
|
411
|
+
const t1r = ops.reshape(plane1, [posSize, hidden]);
|
|
412
|
+
plane1.dispose();
|
|
413
|
+
const pxArr = MlxArray.fromInt32(pxIdx, [numReal]);
|
|
414
|
+
const pyArr = MlxArray.fromInt32(pyIdx, [numReal]);
|
|
415
|
+
const e0 = ops.takeAxis(t0r, pxArr, 0);
|
|
416
|
+
const e1 = ops.takeAxis(t1r, pyArr, 0);
|
|
417
|
+
t0r.dispose();
|
|
418
|
+
t1r.dispose();
|
|
419
|
+
pxArr.dispose();
|
|
420
|
+
pyArr.dispose();
|
|
421
|
+
let pos = ops.add(e0, e1);
|
|
422
|
+
e0.dispose();
|
|
423
|
+
e1.dispose();
|
|
424
|
+
pos = disposing(pos, ops.reshape(pos, [1, numReal, hidden]));
|
|
425
|
+
pos = disposing(pos, pos.astype(embeds.dtype));
|
|
426
|
+
embeds = disposing(embeds, ops.add(embeds, pos)); // [1, numReal, hidden]
|
|
427
|
+
pos.dispose();
|
|
428
|
+
dbg?.("patchembed", embeds);
|
|
429
|
+
|
|
430
|
+
// --- pad to maxPatches (zeros) ---
|
|
431
|
+
const numPad = this.maxPatches - numReal;
|
|
432
|
+
if (numPad > 0) {
|
|
433
|
+
const padE = ops.zeros([1, numPad, hidden], embeds.dtype);
|
|
434
|
+
embeds = disposing(embeds, ops.concatAxis([embeds, padE], 1));
|
|
435
|
+
padE.dispose();
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// --- positions array [1, maxPatches, 2] (real then -1 pad) for RoPE ---
|
|
439
|
+
const posInts = new Int32Array(this.maxPatches * 2).fill(-1);
|
|
440
|
+
posInts.set(real, 0);
|
|
441
|
+
const positions = MlxArray.fromInt32(posInts, [1, this.maxPatches, 2]);
|
|
442
|
+
const rope = rope2dTables(positions, this.cfg.headDim, this.cfg.ropeTheta, embeds.dtype);
|
|
443
|
+
positions.dispose();
|
|
444
|
+
|
|
445
|
+
// --- bidirectional -1e4 mask [1,1,maxPatches,maxPatches] ---
|
|
446
|
+
// valid_i AND valid_j → 0 else -1e4. valid = patch index < numReal.
|
|
447
|
+
const validInts = new Float32Array(this.maxPatches);
|
|
448
|
+
for (let i = 0; i < this.maxPatches; i++) validInts[i] = i < numReal ? 1 : 0;
|
|
449
|
+
const validRow = MlxArray.fromFloat32(validInts, [1, 1, 1, this.maxPatches]); // keys
|
|
450
|
+
const validCol = MlxArray.fromFloat32(validInts, [1, 1, this.maxPatches, 1]); // queries
|
|
451
|
+
const both = ops.mul(validRow, validCol); // [1,1,mp,mp] 1 if both valid
|
|
452
|
+
validRow.dispose();
|
|
453
|
+
validCol.dispose();
|
|
454
|
+
// mask_fill: where(both, 0, -1e4) = (both-1)*1e4
|
|
455
|
+
const oneArr = ops.scalarLike(1, both);
|
|
456
|
+
const bm1 = ops.sub(both, oneArr); // both-1: 0 or -1
|
|
457
|
+
both.dispose();
|
|
458
|
+
oneArr.dispose();
|
|
459
|
+
let mask = ops.mulScalar(bm1, 1e4); // 0 or -1e4
|
|
460
|
+
bm1.dispose();
|
|
461
|
+
mask = disposing(mask, mask.astype(embeds.dtype));
|
|
462
|
+
|
|
463
|
+
// --- transformer ---
|
|
464
|
+
let h = embeds;
|
|
465
|
+
for (let li = 0; li < this.layers.length; li++) {
|
|
466
|
+
const next = this.layers[li]!.forward(h, rope, mask);
|
|
467
|
+
h.dispose();
|
|
468
|
+
h = next;
|
|
469
|
+
if (li < 3) dbg?.(`vlayer${li}`, h);
|
|
470
|
+
}
|
|
471
|
+
rope.dispose();
|
|
472
|
+
mask.dispose();
|
|
473
|
+
dbg?.("transformer", h);
|
|
474
|
+
|
|
475
|
+
// --- pooler: zero padding, position-grouped 3x3 avg-pool to 280, ×√hidden ---
|
|
476
|
+
// zero padding rows
|
|
477
|
+
if (numPad > 0) {
|
|
478
|
+
const keep = new Float32Array(this.maxPatches);
|
|
479
|
+
for (let i = 0; i < this.maxPatches; i++) keep[i] = i < numReal ? 1 : 0;
|
|
480
|
+
const keepArr = MlxArray.fromFloat32(keep, [1, this.maxPatches, 1]).astype(h.dtype);
|
|
481
|
+
h = disposing(h, ops.mul(h, keepArr));
|
|
482
|
+
keepArr.dispose();
|
|
483
|
+
}
|
|
484
|
+
// pooling matrix [maxPatches, length] : kernel_idx = (x//k) + (pW_blocks)*(y//k)
|
|
485
|
+
// pW_blocks = (max_x+1)//k where max_x = pW-1 → pW//k... reference: (max_x//k)
|
|
486
|
+
// where max_x = max(clamped x)+1 = pW. So blocksPerRow = pW // k.
|
|
487
|
+
const length = this.defaultOutputLength;
|
|
488
|
+
const blocksPerRow = Math.floor(pW / k);
|
|
489
|
+
const poolW = new Float32Array(this.maxPatches * length);
|
|
490
|
+
const invK2 = 1 / (k * k);
|
|
491
|
+
for (let i = 0; i < this.maxPatches; i++) {
|
|
492
|
+
// clamped positions: pad (-1) → 0
|
|
493
|
+
const x = i < numReal ? real[i * 2]! : 0;
|
|
494
|
+
const y = i < numReal ? real[i * 2 + 1]! : 0;
|
|
495
|
+
const idx = Math.floor(x / k) + blocksPerRow * Math.floor(y / k);
|
|
496
|
+
if (idx < length) poolW[i * length + idx] = invK2;
|
|
497
|
+
}
|
|
498
|
+
const hf = h.astype(Dtype.float32);
|
|
499
|
+
h.dispose();
|
|
500
|
+
const poolWArr = MlxArray.fromFloat32(poolW, [this.maxPatches, length]);
|
|
501
|
+
// output[l,d] = sum_L poolW[L,l] * hf[L,d] = poolW.T @ hf
|
|
502
|
+
const hf2 = ops.reshape(hf, [this.maxPatches, hidden]);
|
|
503
|
+
hf.dispose();
|
|
504
|
+
const poolWT = ops.transposeAxes(poolWArr, [1, 0]); // [length, maxPatches]
|
|
505
|
+
poolWArr.dispose();
|
|
506
|
+
let pooled = ops.matmul(poolWT, hf2); // [length, hidden] f32
|
|
507
|
+
poolWT.dispose();
|
|
508
|
+
hf2.dispose();
|
|
509
|
+
// ×√hidden, back to bf16, reshape [1, length, hidden]
|
|
510
|
+
const dtype = this.posTable.dtype;
|
|
511
|
+
pooled = disposing(pooled, pooled.astype(dtype));
|
|
512
|
+
pooled = disposing(pooled, ops.mulScalar(pooled, this.rootHidden));
|
|
513
|
+
pooled = disposing(pooled, ops.reshape(pooled, [1, length, hidden]));
|
|
514
|
+
|
|
515
|
+
// --- trim to the real soft tokens (kernel_idx < numRealSoft) ---
|
|
516
|
+
const softW = blocksPerRow;
|
|
517
|
+
const softH = Math.floor(pH / k);
|
|
518
|
+
const numSoft = softW * softH;
|
|
519
|
+
const trimmed = pooled.slice([0, 0, 0], [1, numSoft, hidden]);
|
|
520
|
+
pooled.dispose();
|
|
521
|
+
let out = trimmed;
|
|
522
|
+
dbg?.("pooled", out);
|
|
523
|
+
|
|
524
|
+
// --- standardize: (h - std_bias) * std_scale ---
|
|
525
|
+
if (this.stdBias && this.stdScale) {
|
|
526
|
+
const sb = this.stdBias.astype(out.dtype);
|
|
527
|
+
const ss = this.stdScale.astype(out.dtype);
|
|
528
|
+
const sub = ops.sub(out, sb);
|
|
529
|
+
out.dispose();
|
|
530
|
+
sb.dispose();
|
|
531
|
+
out = ops.mul(sub, ss);
|
|
532
|
+
sub.dispose();
|
|
533
|
+
ss.dispose();
|
|
534
|
+
}
|
|
535
|
+
dbg?.("toweroutput", out);
|
|
536
|
+
return out;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** get_image_features = embed_vision(vision_tower(pixels)):
|
|
540
|
+
* MultimodalEmbedder (RMSNormNoScale → projection 1152→2816). NO /embed_scale. */
|
|
541
|
+
getImageFeatures(pixels: MlxArray, dbg?: (n: string, a: MlxArray) => void): MlxArray {
|
|
542
|
+
const tower = this.visionTower(pixels, dbg);
|
|
543
|
+
const normed = manualRms(tower, null, this.embedEps); // RMSNormNoScale
|
|
544
|
+
tower.dispose();
|
|
545
|
+
const out = this.embedProj.forward(normed);
|
|
546
|
+
normed.dispose();
|
|
547
|
+
return out;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Drafter models as the layers above build them. Each loader imports its
|
|
2
|
+
// implementation on first use and hands the drafter over as the port the draft
|
|
3
|
+
// sources consume (`contracts/mlx/drafter`); no source names a class.
|
|
4
|
+
|
|
5
|
+
import type { ModelConfig } from "../artifacts/config";
|
|
6
|
+
import type { Weights } from "../artifacts/weights";
|
|
7
|
+
import type { AssistantDrafterModel, DeepspecDrafterModel, Dflash2DrafterModel, DsparkDrafterModel, NativeMtpHead, RecurrentMtpModule }
|
|
8
|
+
from "../contracts/mlx/drafter";
|
|
9
|
+
import type { MlxDeclaredGraph } from "../contracts/mlx/graph";
|
|
10
|
+
|
|
11
|
+
/** The KV-borrowing assistant drafter in `dir`. */
|
|
12
|
+
export async function loadAssistantDrafter(dir: string): Promise<AssistantDrafterModel> {
|
|
13
|
+
const { GemmaAssistantDrafter } = await import("./gemma4/assistant");
|
|
14
|
+
return GemmaAssistantDrafter.load(dir);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** A DeepSpec drafter in `dir`. */
|
|
18
|
+
export async function loadDeepspecDrafter(dir: string): Promise<DeepspecDrafterModel> {
|
|
19
|
+
const { DeepspecDrafter } = await import("./speculative/deepspec");
|
|
20
|
+
return DeepspecDrafter.load(dir);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A DFlash 2 drafter in `dir`, in its trained basis (projections quantized to `bits`, 0 = BF16). */
|
|
24
|
+
export async function loadDflash2Drafter(dir: string, opts: { bits: number }): Promise<Dflash2DrafterModel> {
|
|
25
|
+
const { Dflash2Drafter } = await import("./speculative/dflash2");
|
|
26
|
+
return Dflash2Drafter.load(dir, opts);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Our trained DSpark drafter in `dir` (`dspark.json` beside the weights), dispatching on its variant. */
|
|
30
|
+
export async function loadDsparkDrafter(dir: string): Promise<DsparkDrafterModel> {
|
|
31
|
+
const { loadDsparkDrafter: load } = await import("./speculative/loader");
|
|
32
|
+
return load(dir);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The recurrent MTP block of a Qwen companion checkpoint. Its tensors belong to `weights`; the
|
|
36
|
+
* module's own views belong to `resources`. */
|
|
37
|
+
export async function loadQwenMtpModule(weights: Weights, config: ModelConfig,
|
|
38
|
+
resources: DisposableStack): Promise<RecurrentMtpModule> {
|
|
39
|
+
const { MtpModule } = await import("./qwen/mtp");
|
|
40
|
+
return new MtpModule(weights, config, resources);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The native MTP head a graph declares (`nativeDraft`). Only a graph that provides its head binds. */
|
|
44
|
+
export function nativeMtpHeadOf(graph: object): NativeMtpHead {
|
|
45
|
+
const head = (graph as Partial<MlxDeclaredGraph>).nativeDraftHead;
|
|
46
|
+
if (typeof head !== "function")
|
|
47
|
+
throw new Error("native GLM-5.2 MTP binds only to the GLM-5.2 graph that declares it");
|
|
48
|
+
return head.call(graph);
|
|
49
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Conventions by which speculative-decoding artifacts and graphs declare
|
|
2
|
+
// themselves. Pure string facts, so the model index, the hub and the draft
|
|
3
|
+
// provider registry all read one definition without loading MLX (the drafters
|
|
4
|
+
// themselves load through `drafter-loaders`).
|
|
5
|
+
|
|
6
|
+
import { isDeepspecArchitecture } from "./speculative/deepspec-artifact";
|
|
7
|
+
import { isDflash2Architecture } from "./speculative/dflash2-artifact";
|
|
8
|
+
|
|
9
|
+
/** A DeepSpec drafter (DeepSeek's released DSpark checkpoints): a plain HF config stamped with its
|
|
10
|
+
* architecture. */
|
|
11
|
+
export function isDeepspecDrafterConfig(config: Record<string, unknown> | null): boolean {
|
|
12
|
+
return isDeepspecArchitecture(config?.architectures);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** A DFlash 2 block drafter (incoai/Qwen3.8-27B-DFlash2): a plain HF config stamped with its architecture. */
|
|
16
|
+
export function isDflash2DrafterConfig(config: Record<string, unknown> | null): boolean {
|
|
17
|
+
return isDflash2Architecture(config?.architectures);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A drafter whose weights are Q-only and have no standalone LM head
|
|
21
|
+
* (`gemma4_assistant`, `gemma4_unified_assistant`). */
|
|
22
|
+
export function isAssistantModelType(modelType: string): boolean {
|
|
23
|
+
return modelType.includes("assistant");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A multi-token-prediction head split from a qwen3_5-family release
|
|
27
|
+
* (`qwen3_5_mtp`). */
|
|
28
|
+
export function isMtpModelType(modelType: string): boolean {
|
|
29
|
+
return modelType.endsWith("_mtp");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Drafters with no standalone graph: never servable or selectable as a model. */
|
|
33
|
+
export function isUnservableDrafterModelType(modelType: string): boolean {
|
|
34
|
+
return isAssistantModelType(modelType);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The `GraphCapabilities.nativeDraft` kind of a graph whose checkpoint carries
|
|
38
|
+
* its own multi-token-prediction row. */
|
|
39
|
+
export const NATIVE_MTP_DRAFT = "checkpoint-mtp";
|