@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,553 @@
|
|
|
1
|
+
import { rowOperationFor } from "../graph";
|
|
2
|
+
// Faithful DFlash drafter (DSpark paper §3.1, Eq 2–3) — the KV-injection
|
|
3
|
+
// architecture. Selected by variant="dspark" (or legacy "dflash") in the
|
|
4
|
+
// checkpoint metadata. The superseded v1 single-vector module (target context
|
|
5
|
+
// collapsed to ONE vector fused as a sequence token before layer 0) is deleted;
|
|
6
|
+
// this builds the paper's mechanism:
|
|
7
|
+
// Eq 2: H_ctx = RMSNorm(W_c · [H^{l1};…;H^{lm}]) — m tapped target layers,
|
|
8
|
+
// over the FULL context, projected into the draft width.
|
|
9
|
+
// Eq 3: every draft layer i forms K_i=[W_i^K H_ctx; W_i^K H_d],
|
|
10
|
+
// V_i=[W_i^V H_ctx; W_i^V H_d], Q_i=W_i^Q H_d — the block attends
|
|
11
|
+
// bidirectionally over [context ++ block]; context is read-only memory
|
|
12
|
+
// re-projected fresh at every layer, never a token that gets rewritten.
|
|
13
|
+
// The draft projects the target's HIDDEN STATES with its OWN Wk/Wv (not the
|
|
14
|
+
// target's K/V — that's the separate GemmaAssistantDrafter baseline).
|
|
15
|
+
|
|
16
|
+
import { MlxArray } from "@mlx-bun/mlx/array";
|
|
17
|
+
import { Dtype } from "@mlx-bun/mlx/ffi";
|
|
18
|
+
import * as ops from "@mlx-bun/mlx/ops";
|
|
19
|
+
import type { Gemma4Model } from "../gemma4/model";
|
|
20
|
+
import type { DraftProjection } from "../../contracts/mlx/draft-projection";
|
|
21
|
+
|
|
22
|
+
import type { DsparkContextAttention, DsparkDrafterModel } from "../../contracts/mlx/drafter";
|
|
23
|
+
import { loadAdapterTensors } from "../../adapters/manager";
|
|
24
|
+
import { writeShardedSafetensors, type NamedTensor } from "../../artifacts/safetensors-writer";
|
|
25
|
+
import { processLogits, sampleToken, KeyStream, type DSparkSampleConfig } from "../../sampling/draft";
|
|
26
|
+
import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
|
|
29
|
+
/** STS calibration (§3.2.1) — per-position confidence thresholds fit on real
|
|
30
|
+
* (confidence, accepted) verify outcomes (`fitStsThresholds` in
|
|
31
|
+
* `@mlx-bun/training/dspark`; `mlx-bun draft calibrate` writes them into
|
|
32
|
+
* dspark.json). Consumed by the confidence-scheduled
|
|
33
|
+
* draft-length pruning (Alg 1) in forwardRows. Stored
|
|
34
|
+
* inside DflashConfig so it round-trips through dspark.json for free.
|
|
35
|
+
* ABSENT ⟹ no pruning — an uncalibrated checkpoint drafts exactly as before. */
|
|
36
|
+
export interface StsCalibration {
|
|
37
|
+
/** thresholds[k] = min confidence to KEEP draft position k. length γ. */
|
|
38
|
+
thresholds: number[];
|
|
39
|
+
/** Target acceptance precision the thresholds were fit for (e.g. 0.5). */
|
|
40
|
+
target: number;
|
|
41
|
+
/** Verify outcomes the fit saw (provenance). */
|
|
42
|
+
samples?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface DflashConfig {
|
|
46
|
+
gamma: number;
|
|
47
|
+
dDraft: number;
|
|
48
|
+
/** Backbone depth (paper default 5). */
|
|
49
|
+
nLayers: number;
|
|
50
|
+
nHeads: number;
|
|
51
|
+
markovRank: number;
|
|
52
|
+
ffMult: number;
|
|
53
|
+
/** Target layer indices tapped for H_ctx (Eq 2). nLayers-of-target..sentinel.
|
|
54
|
+
* For e4b (42 layers): index 0..41 = post-layer residual, 42 = post-finalNorm. */
|
|
55
|
+
tapLayers: number[];
|
|
56
|
+
/** Sequential head: "markov" (Eq 5, default) or "rnn" (Eq 6). */
|
|
57
|
+
seqHead?: "markov" | "rnn";
|
|
58
|
+
/** STS calibration (§3.2.1); absent = no confidence pruning. */
|
|
59
|
+
sts?: StsCalibration;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const DEFAULT_DFLASH_CONFIG: DflashConfig = {
|
|
63
|
+
gamma: 5,
|
|
64
|
+
dDraft: 1024,
|
|
65
|
+
nLayers: 5,
|
|
66
|
+
nHeads: 8,
|
|
67
|
+
markovRank: 256,
|
|
68
|
+
ffMult: 2,
|
|
69
|
+
tapLayers: [20, 31, 41, 42],
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export interface TargetDims { hiddenSize: number; vocabSize: number; eps: number }
|
|
73
|
+
|
|
74
|
+
export interface DflashTrainOut { draftLogits: MlxArray; conf: MlxArray }
|
|
75
|
+
/** Per row, tokens/conf may be SHORTER than the requested γ when confidence
|
|
76
|
+
* pruning fires (Alg 1); always ≥1. draftLogits covers the drafted
|
|
77
|
+
* positions — ABSENT when the caller passed collectLogits:false (the loop
|
|
78
|
+
* never materialized/concatenated the per-position logits). */
|
|
79
|
+
export interface DflashDraftRows { tokens: number[][]; conf: number[][]; draftLogits?: MlxArray; }
|
|
80
|
+
export type DflashContextAttention = DsparkContextAttention;
|
|
81
|
+
export interface DflashDraftOpts {
|
|
82
|
+
sample?: DSparkSampleConfig;
|
|
83
|
+
keys?: KeyStream;
|
|
84
|
+
/** Confidence-scheduled draft-length pruning (Alg 1, single-user form):
|
|
85
|
+
* position k is DROPPED (and the block truncated there) when its predicted
|
|
86
|
+
* acceptance c_k < thresholds[k] (per-position, STS-calibrated) or < minConf
|
|
87
|
+
* (uniform manual override). Position 0 is always kept (a source must
|
|
88
|
+
* return ≥1 token). Both absent ⟹ fixed-γ drafting (pre-scheduler
|
|
89
|
+
* behavior). Losslessness is invariant — pruning only changes how many
|
|
90
|
+
* positions the target VERIFIES, never what is emitted. */
|
|
91
|
+
thresholds?: number[];
|
|
92
|
+
minConf?: number;
|
|
93
|
+
/** Materialize+concat the per-position draft logits into the returned
|
|
94
|
+
* DflashDraftRows.draftLogits. Default true. The grouped draft rows
|
|
95
|
+
* run their own verify lm-head and never read it — pass false
|
|
96
|
+
* there to skip the dead concat + a host-unrelated GPU alloc every round. */
|
|
97
|
+
collectLogits?: boolean;
|
|
98
|
+
/** Return confidence telemetry; pruning still computes it when needed. */
|
|
99
|
+
collectConfidence?: boolean;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const CDT = Dtype.float32;
|
|
103
|
+
const NEG = -1e9;
|
|
104
|
+
|
|
105
|
+
function disposing(old: MlxArray, next: MlxArray): MlxArray { old.dispose(); return next; }
|
|
106
|
+
|
|
107
|
+
function makeRng(seed: number): () => number {
|
|
108
|
+
let s = seed >>> 0 || 0x9e3779b9;
|
|
109
|
+
return () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 0x100000000; };
|
|
110
|
+
}
|
|
111
|
+
function normalArray(rng: () => number, shape: number[], std: number): MlxArray {
|
|
112
|
+
const n = shape.reduce((a, b) => a * b, 1);
|
|
113
|
+
const out = new Float32Array(n);
|
|
114
|
+
for (let i = 0; i < n; i += 2) {
|
|
115
|
+
const u1 = Math.max(rng(), 1e-12), u2 = rng();
|
|
116
|
+
const r = Math.sqrt(-2 * Math.log(u1));
|
|
117
|
+
out[i] = r * Math.cos(2 * Math.PI * u2) * std;
|
|
118
|
+
if (i + 1 < n) out[i + 1] = r * Math.sin(2 * Math.PI * u2) * std;
|
|
119
|
+
}
|
|
120
|
+
return MlxArray.fromFloat32(out, shape);
|
|
121
|
+
}
|
|
122
|
+
const zerosArray = (shape: number[]) => MlxArray.fromFloat32(new Float32Array(shape.reduce((a, b) => a * b, 1)), shape);
|
|
123
|
+
const constArray = (shape: number[], v: number) => MlxArray.fromFloat32(new Float32Array(shape.reduce((a, b) => a * b, 1)).fill(v), shape);
|
|
124
|
+
|
|
125
|
+
export class DflashDrafter implements DsparkDrafterModel {
|
|
126
|
+
readonly cfg: DflashConfig;
|
|
127
|
+
readonly dims: TargetDims;
|
|
128
|
+
readonly targetId: string;
|
|
129
|
+
readonly m: number; // number of tapped layers
|
|
130
|
+
#p = new Map<string, MlxArray>();
|
|
131
|
+
readonly names: string[];
|
|
132
|
+
|
|
133
|
+
private constructor(cfg: DflashConfig, dims: TargetDims, targetId: string) {
|
|
134
|
+
this.cfg = cfg;
|
|
135
|
+
this.dims = dims;
|
|
136
|
+
this.targetId = targetId;
|
|
137
|
+
this.m = cfg.tapLayers.length;
|
|
138
|
+
if (cfg.dDraft % cfg.nHeads !== 0) throw new Error(`dDraft ${cfg.dDraft} not divisible by nHeads ${cfg.nHeads}`);
|
|
139
|
+
this.names = buildNames(cfg);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
static dimsOf(model: Gemma4Model): TargetDims {
|
|
143
|
+
const t = model.config.text;
|
|
144
|
+
return { hiddenSize: t.hiddenSize, vocabSize: t.vocabSize, eps: t.rmsNormEps };
|
|
145
|
+
}
|
|
146
|
+
static init(model: Gemma4Model, cfg: DflashConfig, targetId: string, seed = 0): DflashDrafter {
|
|
147
|
+
return DflashDrafter.initFromDims(DflashDrafter.dimsOf(model), cfg, targetId, seed);
|
|
148
|
+
}
|
|
149
|
+
static initFromDims(dims: TargetDims, cfg: DflashConfig, targetId: string, seed = 0): DflashDrafter {
|
|
150
|
+
const d = new DflashDrafter(cfg, dims, targetId);
|
|
151
|
+
const rng = makeRng(seed);
|
|
152
|
+
const { dDraft, nLayers, markovRank: r, ffMult } = cfg;
|
|
153
|
+
const dInter = ffMult * dDraft;
|
|
154
|
+
const { hiddenSize: H, vocabSize: V } = dims;
|
|
155
|
+
const mH = d.m * H;
|
|
156
|
+
const set = (n: string, a: MlxArray) => d.#p.set(n, a.eval());
|
|
157
|
+
for (let i = 0; i < nLayers; i++) {
|
|
158
|
+
set(`bb.${i}.attn_norm`, constArray([dDraft], 1.0));
|
|
159
|
+
for (const w of ["q", "k", "v", "o"]) set(`bb.${i}.${w}`, normalArray(rng, [dDraft, dDraft], 0.02));
|
|
160
|
+
set(`bb.${i}.ff_norm`, constArray([dDraft], 1.0));
|
|
161
|
+
set(`bb.${i}.gate`, normalArray(rng, [dDraft, dInter], 0.02));
|
|
162
|
+
set(`bb.${i}.up`, normalArray(rng, [dDraft, dInter], 0.02));
|
|
163
|
+
set(`bb.${i}.down`, normalArray(rng, [dInter, dDraft], 0.02));
|
|
164
|
+
}
|
|
165
|
+
set("W_c", normalArray(rng, [mH, dDraft], 0.02)); // Eq 2 projection
|
|
166
|
+
set("ctx_norm", constArray([dDraft], 1.0));
|
|
167
|
+
set("tok_proj", normalArray(rng, [H, dDraft], 0.02));
|
|
168
|
+
set("mask_emb", normalArray(rng, [cfg.gamma - 1, dDraft], 0.02));
|
|
169
|
+
set("block_pos", normalArray(rng, [cfg.gamma, dDraft], 0.02));
|
|
170
|
+
set("out_norm", constArray([dDraft], 1.0));
|
|
171
|
+
set("out_proj", normalArray(rng, [dDraft, H], 0.02));
|
|
172
|
+
set("markov.w1", normalArray(rng, [V, r], 0.02));
|
|
173
|
+
set("markov.w2", zerosArray([r, V])); // W2=0 → starts as pure parallel DFlash
|
|
174
|
+
set("conf.w", zerosArray([dDraft + r, 1]));
|
|
175
|
+
set("conf.b", zerosArray([1]));
|
|
176
|
+
// rnn.* MUST be initialized last (after every markov/shared param) so the
|
|
177
|
+
// seeded rng stream hands out IDENTICAL draws to a markov-only init up to
|
|
178
|
+
// this point — this is what makes the init-equivalence gate hold (an rnn
|
|
179
|
+
// drafter and a markov drafter, same seed, are bit-identical at t=0).
|
|
180
|
+
if (cfg.seqHead === "rnn") {
|
|
181
|
+
set("rnn.wH", normalArray(rng, [r, r], 0.02));
|
|
182
|
+
set("rnn.bH", zerosArray([r]));
|
|
183
|
+
set("rnn.wO", zerosArray([r, V])); // zero-init → starts as pure DFlash, mirrors markov.w2
|
|
184
|
+
}
|
|
185
|
+
return d;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
get(name: string): MlxArray { const a = this.#p.get(name); if (!a) throw new Error(`param ${name}`); return a; }
|
|
189
|
+
flatParams(): MlxArray[] { return this.names.map((n) => this.get(n)); }
|
|
190
|
+
useParams<T>(primals: MlxArray[], fn: () => T): T {
|
|
191
|
+
const saved = this.names.map((n) => this.get(n));
|
|
192
|
+
this.names.forEach((n, i) => this.#p.set(n, primals[i]!));
|
|
193
|
+
try { return fn(); } finally { this.names.forEach((n, i) => this.#p.set(n, saved[i]!)); }
|
|
194
|
+
}
|
|
195
|
+
installParam(i: number, p: MlxArray): void { this.#p.set(this.names[i]!, p); }
|
|
196
|
+
|
|
197
|
+
// --- Eq 2: context construction ---
|
|
198
|
+
/** hCtx [A, Lctx, m*H] (m tapped layers concatenated on the feature axis) →
|
|
199
|
+
* H_ctx [A, Lctx, d]. */
|
|
200
|
+
#buildContext(hCtx: MlxArray): MlxArray {
|
|
201
|
+
const f = hCtx.dtype === CDT ? hCtx : hCtx.astype(CDT);
|
|
202
|
+
const proj = ops.matmul(f, this.get("W_c")); // [A,Lctx,d]
|
|
203
|
+
if (f !== hCtx) f.dispose();
|
|
204
|
+
const out = ops.rmsNorm(proj, this.get("ctx_norm"), this.dims.eps);
|
|
205
|
+
proj.dispose();
|
|
206
|
+
return out;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Block hidden H_d [A, γ, d]: anchor at pos 0, mask tokens after. */
|
|
210
|
+
#buildBlock(anchorEmb: MlxArray, A: number): MlxArray {
|
|
211
|
+
const { gamma, dDraft } = this.cfg;
|
|
212
|
+
const bp = this.get("block_pos"); // [γ,d]
|
|
213
|
+
const af = anchorEmb.dtype === CDT ? anchorEmb : anchorEmb.astype(CDT);
|
|
214
|
+
let anchor = ops.matmul(af, this.get("tok_proj")); // [A,d]
|
|
215
|
+
if (af !== anchorEmb) af.dispose();
|
|
216
|
+
const p0 = bp.slice([0, 0], [1, dDraft]);
|
|
217
|
+
anchor = disposing(anchor, ops.add(anchor, p0)); p0.dispose();
|
|
218
|
+
anchor = disposing(anchor, ops.reshape(anchor, [A, 1, dDraft]));
|
|
219
|
+
const parts = [anchor];
|
|
220
|
+
if (gamma > 1) {
|
|
221
|
+
const me = this.get("mask_emb"); // [γ-1,d]
|
|
222
|
+
const pm = bp.slice([1, 0], [gamma, dDraft]); // [γ-1,d]
|
|
223
|
+
let masks = ops.add(me, pm); pm.dispose(); // [γ-1,d]
|
|
224
|
+
masks = disposing(masks, ops.reshape(masks, [1, gamma - 1, dDraft]));
|
|
225
|
+
const zerosA = MlxArray.fromFloat32(new Float32Array(A * dDraft), [A, 1, dDraft]);
|
|
226
|
+
const masksA = ops.add(masks, zerosA); // broadcast → [A,γ-1,d]
|
|
227
|
+
masks.dispose(); zerosA.dispose();
|
|
228
|
+
parts.push(masksA);
|
|
229
|
+
}
|
|
230
|
+
const H_d = ops.concatAxis(parts, 1); // [A,γ,d]
|
|
231
|
+
for (const p of parts) p.dispose();
|
|
232
|
+
return H_d;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Additive attention bias [A,1,1,Lctx+γ] from a context key-padding mask
|
|
236
|
+
* ([A,Lctx], 1=real/0=pad). Context pad cols → -1e9; real ctx + all block
|
|
237
|
+
* cols → 0. null when no padding (inference, batch 1). */
|
|
238
|
+
#maskBias(ctxMask: MlxArray | null, A: number, Lctx: number): MlxArray | null {
|
|
239
|
+
if (!ctxMask) return null;
|
|
240
|
+
const mf = ctxMask.dtype === CDT ? ctxMask : ctxMask.astype(CDT);
|
|
241
|
+
const one = MlxArray.fromFloat32(new Float32Array([1]), [1]);
|
|
242
|
+
const sub = ops.sub(mf, one); one.dispose(); // real→0, pad→-1
|
|
243
|
+
if (mf !== ctxMask) mf.dispose();
|
|
244
|
+
const bias = ops.mulScalar(sub, -NEG); sub.dispose(); // real→0, pad→-1e9 (-NEG = 1e9; (-1)*1e9=-1e9)
|
|
245
|
+
let ctxBias = ops.reshape(bias, [A, 1, 1, Lctx]); bias.dispose();
|
|
246
|
+
const blockZeros = MlxArray.fromFloat32(new Float32Array(A * this.cfg.gamma), [A, 1, 1, this.cfg.gamma]);
|
|
247
|
+
const full = ops.concatAxis([ctxBias, blockZeros], 3); // [A,1,1,Lctx+γ]
|
|
248
|
+
ctxBias.dispose(); blockZeros.dispose();
|
|
249
|
+
return full;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// --- Eq 3: one KV-injection layer. H_ctx read-only; H_d is queries+updated ---
|
|
253
|
+
#layer(i: number, H_d: MlxArray, H_ctx: MlxArray, maskBias: MlxArray | null, A: number, Lctx: number, context?: DflashContextAttention): MlxArray {
|
|
254
|
+
const { dDraft, nHeads, gamma } = this.cfg;
|
|
255
|
+
const hd = dDraft / nHeads;
|
|
256
|
+
const eps = this.dims.eps;
|
|
257
|
+
const wk = this.get(`bb.${i}.k`), wv = this.get(`bb.${i}.v`);
|
|
258
|
+
|
|
259
|
+
const residual = H_d;
|
|
260
|
+
const nd = ops.rmsNorm(H_d, this.get(`bb.${i}.attn_norm`), eps);
|
|
261
|
+
const nc = context ? null : ops.rmsNorm(H_ctx, this.get(`bb.${i}.attn_norm`), eps); // SAME norm as block
|
|
262
|
+
|
|
263
|
+
// Q from block only
|
|
264
|
+
let q = ops.matmul(nd, this.get(`bb.${i}.q`)); // [A,γ,d]
|
|
265
|
+
q = disposing(q, ops.reshape(q, [A, gamma, nHeads, hd]));
|
|
266
|
+
q = disposing(q, ops.transposeAxes(q, [0, 2, 1, 3])); // [A,nHeads,γ,hd]
|
|
267
|
+
|
|
268
|
+
const kd = ops.matmul(nd, wk), vd = ops.matmul(nd, wv); nd.dispose();
|
|
269
|
+
let attn: MlxArray;
|
|
270
|
+
if (context) {
|
|
271
|
+
const shape = (array: MlxArray) => {
|
|
272
|
+
using rows = ops.reshape(array, [A, gamma, nHeads, hd]);
|
|
273
|
+
return ops.transposeAxes(rows, [0, 2, 1, 3]);
|
|
274
|
+
};
|
|
275
|
+
using keys = shape(kd), values = shape(vd); kd.dispose(); vd.dispose();
|
|
276
|
+
attn = context.attend(i, q, keys, values, Math.pow(hd, -0.5));
|
|
277
|
+
} else {
|
|
278
|
+
const kc = ops.matmul(nc!, wk), vc = ops.matmul(nc!, wv); nc!.dispose();
|
|
279
|
+
const shape = (array: MlxArray) => {
|
|
280
|
+
using rows = ops.reshape(array, [A, Lctx + gamma, nHeads, hd]);
|
|
281
|
+
return ops.transposeAxes(rows, [0, 2, 1, 3]);
|
|
282
|
+
};
|
|
283
|
+
using k = ops.concatAxis([kc, kd], 1), v = ops.concatAxis([vc, vd], 1);
|
|
284
|
+
kc.dispose(); kd.dispose(); vc.dispose(); vd.dispose();
|
|
285
|
+
using keys = shape(k), values = shape(v);
|
|
286
|
+
attn = ops.sdpa(q, keys, values, Math.pow(hd, -0.5), maskBias ? "array" : "", maskBias);
|
|
287
|
+
}
|
|
288
|
+
q.dispose();
|
|
289
|
+
attn = disposing(attn, ops.transposeAxes(attn, [0, 2, 1, 3])); // [A,γ,nHeads,hd]
|
|
290
|
+
attn = disposing(attn, ops.reshape(attn, [A, gamma, dDraft]));
|
|
291
|
+
attn = disposing(attn, ops.matmul(attn, this.get(`bb.${i}.o`)));
|
|
292
|
+
let H = ops.add(residual, attn); residual.dispose(); attn.dispose();
|
|
293
|
+
|
|
294
|
+
// gated-GELU FFN on the block only
|
|
295
|
+
const res2 = H;
|
|
296
|
+
const n2 = ops.rmsNorm(H, this.get(`bb.${i}.ff_norm`), eps);
|
|
297
|
+
const g = ops.matmul(n2, this.get(`bb.${i}.gate`));
|
|
298
|
+
const u = ops.matmul(n2, this.get(`bb.${i}.up`));
|
|
299
|
+
n2.dispose();
|
|
300
|
+
const act = ops.geluApprox(g); g.dispose();
|
|
301
|
+
let mlp = ops.mul(act, u); act.dispose(); u.dispose();
|
|
302
|
+
mlp = disposing(mlp, ops.matmul(mlp, this.get(`bb.${i}.down`)));
|
|
303
|
+
const out = ops.add(res2, mlp); res2.dispose(); mlp.dispose();
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** hCtx [A,Lctx,m*H], anchorEmb [A,H], ctxMask [A,Lctx]|null → block [A,γ,d]. */
|
|
308
|
+
#backbone(hCtx: MlxArray | null, anchorEmb: MlxArray, ctxMask: MlxArray | null, A: number, context?: DflashContextAttention): MlxArray {
|
|
309
|
+
const Lctx = hCtx?.shape[1] ?? 0;
|
|
310
|
+
const H_ctx = context ? null : this.#buildContext(hCtx!);
|
|
311
|
+
let H_d = this.#buildBlock(anchorEmb, A);
|
|
312
|
+
const maskBias = this.#maskBias(ctxMask, A, Lctx);
|
|
313
|
+
for (let i = 0; i < this.cfg.nLayers; i++) H_d = disposing(H_d, this.#layer(i, H_d, H_ctx!, maskBias, A, Lctx, context));
|
|
314
|
+
H_ctx?.dispose(); maskBias?.dispose();
|
|
315
|
+
H_d = disposing(H_d, ops.rmsNorm(H_d, this.get("out_norm"), this.dims.eps));
|
|
316
|
+
return H_d;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Context projection is independent of the block and can be retained. */
|
|
320
|
+
projectContextRows(hidden: MlxArray): { k: MlxArray; v: MlxArray }[] {
|
|
321
|
+
const { nHeads, dDraft } = this.cfg, B = hidden.shape[0]!, N = hidden.shape[1]!;
|
|
322
|
+
using projected = this.#buildContext(hidden);
|
|
323
|
+
using pending = new DisposableStack();
|
|
324
|
+
const pairs = Array.from({ length: this.cfg.nLayers }, (_, layer) => {
|
|
325
|
+
using normalized = ops.rmsNorm(projected, this.get(`bb.${layer}.attn_norm`), this.dims.eps);
|
|
326
|
+
const plane = (name: string) => {
|
|
327
|
+
using flat = ops.matmul(normalized, this.get(name));
|
|
328
|
+
using rows = ops.reshape(flat, [B, N, nHeads, dDraft / nHeads]);
|
|
329
|
+
return pending.use(ops.transposeAxes(rows, [0, 2, 1, 3]));
|
|
330
|
+
};
|
|
331
|
+
return { k: plane(`bb.${layer}.k`), v: plane(`bb.${layer}.v`) };
|
|
332
|
+
});
|
|
333
|
+
pending.move();
|
|
334
|
+
return pairs;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
#baseLogits(model: DraftProjection, block: MlxArray, anchors: number): MlxArray {
|
|
338
|
+
const hOut = ops.matmul(block, this.get("out_proj")); // [A,γ,H]
|
|
339
|
+
const hBf = hOut.astype(model.embed.scales.dtype); hOut.dispose();
|
|
340
|
+
const logits = rowOperationFor(model.logits,anchors * this.cfg.gamma)(hBf); hBf.dispose();
|
|
341
|
+
return logits;
|
|
342
|
+
}
|
|
343
|
+
#markov(prevToks: MlxArray): { B: MlxArray; emb1: MlxArray } {
|
|
344
|
+
const emb1 = ops.takeAxis(this.get("markov.w1"), prevToks, 0); // [A,γ,r]
|
|
345
|
+
const B = ops.matmul(emb1, this.get("markov.w2")); // [A,γ,V]
|
|
346
|
+
return { B, emb1 };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** RNN sequential head — the ELMAN variant. VERIFIED-DIVERGENT from paper
|
|
350
|
+
* Eq 6 (2026-07-06 audit vs arXiv:2607.05147): the paper's cell is GATED
|
|
351
|
+
* over z_k=[s_{k−1}; W₁[x_{k−1}]; h_k] (backbone hidden included!) with a
|
|
352
|
+
* fused (2r+d)→3r projection, s_k=σ(W_g z)⊙s_{k−1}+(1−σ)⊙tanh(W_c z),
|
|
353
|
+
* B_k=W₂ᵀtanh(W_o z) — DeepSpec's RNNHead is that form. This ungated
|
|
354
|
+
* tanh recurrence over the shared token embedding (no h_k) is kept as a
|
|
355
|
+
* documented VARIANT ([[dont-delete-optionality-on-one-measurement]]):
|
|
356
|
+
* the paper reports the RNN head's gains over Markov as "marginal" and
|
|
357
|
+
* production uses Markov (our default). Add the gated cell as
|
|
358
|
+
* seqHead:"gru" if it ever earns a run; details in the design doc's
|
|
359
|
+
* "DeepSpec ground truth" section. */
|
|
360
|
+
#rnn(prevToks: MlxArray): { B: MlxArray; emb1: MlxArray } {
|
|
361
|
+
const { gamma: G, markovRank: r } = this.cfg;
|
|
362
|
+
const A = prevToks.shape[0]!;
|
|
363
|
+
const emb1 = ops.takeAxis(this.get("markov.w1"), prevToks, 0); // [A,γ,r] (shared embedding, no 2nd table)
|
|
364
|
+
const wH = this.get("rnn.wH"), bH = this.get("rnn.bH"), wO = this.get("rnn.wO");
|
|
365
|
+
let s: MlxArray | null = zerosArray([A, r]); // s_{-1} = 0
|
|
366
|
+
const bSlices: MlxArray[] = [];
|
|
367
|
+
const pending: MlxArray[] = []; // iteration temps, released by the catch
|
|
368
|
+
try {
|
|
369
|
+
for (let k = 0; k < G; k++) {
|
|
370
|
+
const e1S = emb1.slice([0, k, 0], [A, k + 1, r]); pending.push(e1S);
|
|
371
|
+
const e1k = ops.reshape(e1S, [A, r]); pending.push(e1k);
|
|
372
|
+
e1S.dispose();
|
|
373
|
+
const sh = ops.matmul(s!, wH); pending.push(sh);
|
|
374
|
+
s!.dispose(); s = null;
|
|
375
|
+
let sNext = ops.add(sh, e1k); pending.push(sNext);
|
|
376
|
+
sh.dispose(); e1k.dispose();
|
|
377
|
+
sNext = disposing(sNext, ops.add(sNext, bH)); pending.push(sNext);
|
|
378
|
+
sNext = disposing(sNext, ops.tanh(sNext)); pending.push(sNext);
|
|
379
|
+
s = sNext; // s_k
|
|
380
|
+
const bk = ops.matmul(s, wO); pending.push(bk); // [A,V]
|
|
381
|
+
bSlices.push(ops.reshape(bk, [A, 1, this.dims.vocabSize])); bk.dispose();
|
|
382
|
+
pending.length = 0;
|
|
383
|
+
}
|
|
384
|
+
s!.dispose(); s = null;
|
|
385
|
+
const B = ops.concatAxis(bSlices, 1); // [A,γ,V]
|
|
386
|
+
for (const b of bSlices) b.dispose();
|
|
387
|
+
return { B, emb1 };
|
|
388
|
+
} catch (err) {
|
|
389
|
+
// Mid-recurrence throw: free the carried state, the collected slices,
|
|
390
|
+
// the current iteration's temps, and the emb1 the caller never received
|
|
391
|
+
// (dispose() idempotence makes over-disposal inert).
|
|
392
|
+
for (const a of pending) a.dispose();
|
|
393
|
+
for (const b of bSlices) b.dispose();
|
|
394
|
+
s?.dispose();
|
|
395
|
+
emb1.dispose();
|
|
396
|
+
throw err;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
#seqHead(prevToks: MlxArray): { B: MlxArray; emb1: MlxArray } {
|
|
401
|
+
return this.cfg.seqHead === "rnn" ? this.#rnn(prevToks) : this.#markov(prevToks);
|
|
402
|
+
}
|
|
403
|
+
#confidence(block: MlxArray, emb1: MlxArray): MlxArray {
|
|
404
|
+
const inp = ops.concatAxis([block, emb1], 2);
|
|
405
|
+
let z = ops.matmul(inp, this.get("conf.w")); inp.dispose();
|
|
406
|
+
z = disposing(z, ops.add(z, this.get("conf.b")));
|
|
407
|
+
z = disposing(z, ops.sigmoid(z));
|
|
408
|
+
const A = z.shape[0]!, G = z.shape[1]!;
|
|
409
|
+
const c = ops.reshape(z, [A, G]); z.dispose();
|
|
410
|
+
return c;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Parallel training forward (teacher-forced Markov).
|
|
414
|
+
* hCtx [A,Lctx,m*H], ctxMask [A,Lctx]|null, anchorEmb [A,H], prevToks [A,γ]. */
|
|
415
|
+
forwardTrain(model: DraftProjection, hCtx: MlxArray, ctxMask: MlxArray | null, anchorEmb: MlxArray, prevToks: MlxArray): DflashTrainOut {
|
|
416
|
+
const A = hCtx.shape[0]!;
|
|
417
|
+
let block: MlxArray | null = null, Uf: MlxArray | null = null;
|
|
418
|
+
let B: MlxArray | null = null, emb1: MlxArray | null = null;
|
|
419
|
+
try {
|
|
420
|
+
block = this.#backbone(hCtx, anchorEmb, ctxMask, A);
|
|
421
|
+
const U = this.#baseLogits(model, block, A);
|
|
422
|
+
Uf = U.astype(CDT); U.dispose();
|
|
423
|
+
({ B, emb1 } = this.#seqHead(prevToks));
|
|
424
|
+
const draftLogits = ops.add(Uf, B);
|
|
425
|
+
Uf.dispose(); Uf = null; B.dispose(); B = null;
|
|
426
|
+
const conf = this.#confidence(block, emb1);
|
|
427
|
+
block.dispose(); block = null; emb1.dispose(); emb1 = null;
|
|
428
|
+
return { draftLogits, conf };
|
|
429
|
+
} catch (err) {
|
|
430
|
+
// Free whatever a mid-forward throw left live (each slot is nulled the
|
|
431
|
+
// moment its normal disposal ran — no double-free).
|
|
432
|
+
block?.dispose(); Uf?.dispose(); B?.dispose(); emb1?.dispose();
|
|
433
|
+
throw err;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
forwardRows(model: DraftProjection, hCtx: MlxArray | null, anchors: readonly number[], gamma: number,
|
|
438
|
+
opts: DflashDraftOpts = {}, context?: DflashContextAttention): DflashDraftRows {
|
|
439
|
+
const B = anchors.length, { dDraft, markovRank: r } = this.cfg, V = this.dims.vocabSize;
|
|
440
|
+
const sample = opts.sample && opts.sample.temperature > 0 ? opts.sample : null;
|
|
441
|
+
const keys = sample ? anchors.map((_, row) => row === 0 && opts.keys ? opts.keys : new KeyStream(opts.sample?.seed ?? 0)) : [];
|
|
442
|
+
const collect = opts.collectLogits ?? true, pruning = opts.thresholds !== undefined || opts.minConf !== undefined;
|
|
443
|
+
using ids = ops.fromInt32([...anchors], [B, 1]);
|
|
444
|
+
using embeddings = model.embed.encode(ids);
|
|
445
|
+
using anchorEmb = ops.reshape(embeddings, [B, this.dims.hiddenSize]);
|
|
446
|
+
using block = this.#backbone(hCtx, anchorEmb, null, B, context);
|
|
447
|
+
using raw = this.#baseLogits(model, block, B);
|
|
448
|
+
using base = raw.astype(CDT);
|
|
449
|
+
const isRnn = this.cfg.seqHead === "rnn";
|
|
450
|
+
let state: MlxArray | null = isRnn ? zerosArray([B, r]) : null;
|
|
451
|
+
const tokens: MlxArray[] = [], confidence: MlxArray[] = [], logits: MlxArray[] = [];
|
|
452
|
+
const lengths: Array<number | undefined> = anchors.map(() => undefined);
|
|
453
|
+
const hostConfidence: number[][] = [];
|
|
454
|
+
const needConfidence = pruning || opts.collectConfidence !== false;
|
|
455
|
+
using first = ops.fromInt32([...anchors], [B]); let previous = first;
|
|
456
|
+
try {
|
|
457
|
+
for (let step = 0; step < gamma; step++) {
|
|
458
|
+
using row = base.slice([0, step, 0], [B, step + 1, V]);
|
|
459
|
+
using flat = ops.reshape(row, [B, V]);
|
|
460
|
+
using e1 = ops.takeAxis(this.get("markov.w1"), previous, 0);
|
|
461
|
+
let bias: MlxArray;
|
|
462
|
+
if (isRnn) {
|
|
463
|
+
using recurrent = ops.matmul(state!, this.get("rnn.wH"));
|
|
464
|
+
using sum = ops.add(recurrent, e1);
|
|
465
|
+
using shifted = ops.add(sum, this.get("rnn.bH"));
|
|
466
|
+
const next = ops.tanh(shifted); state!.dispose(); state = next;
|
|
467
|
+
bias = ops.matmul(state, this.get("rnn.wO"));
|
|
468
|
+
} else bias = ops.matmul(e1, this.get("markov.w2"));
|
|
469
|
+
using correction = bias;
|
|
470
|
+
using scores = ops.add(flat, correction);
|
|
471
|
+
let token: MlxArray;
|
|
472
|
+
if (sample) {
|
|
473
|
+
const sampled = anchors.map((_, index) => {
|
|
474
|
+
if (lengths[index] !== undefined) return 0;
|
|
475
|
+
using one = scores.slice([index, 0], [index + 1, V]);
|
|
476
|
+
using processed = processLogits(one, sample);
|
|
477
|
+
return sampleToken(processed, keys[index]!.next());
|
|
478
|
+
});
|
|
479
|
+
token = ops.fromInt32(sampled, [B]);
|
|
480
|
+
} else token = ops.argmaxAxis(scores, -1);
|
|
481
|
+
tokens.push(token); previous = token;
|
|
482
|
+
if (collect) logits.push(ops.reshape(scores, [B, 1, V]));
|
|
483
|
+
if (needConfidence) {
|
|
484
|
+
using h = block.slice([0, step, 0], [B, step + 1, dDraft]);
|
|
485
|
+
using hFlat = ops.reshape(h, [B, dDraft]);
|
|
486
|
+
using joined = ops.concatAxis([hFlat, e1], 1);
|
|
487
|
+
using product = ops.matmul(joined, this.get("conf.w"));
|
|
488
|
+
using shifted = ops.add(product, this.get("conf.b"));
|
|
489
|
+
const conf = ops.sigmoid(shifted); confidence.push(conf);
|
|
490
|
+
if (pruning) {
|
|
491
|
+
const values = conf.toFloat32(), threshold = opts.thresholds?.[step] ?? opts.minConf;
|
|
492
|
+
hostConfidence.push(Array.from(values));
|
|
493
|
+
if (step > 0 && threshold !== undefined) values.forEach((value, row) => {
|
|
494
|
+
if (lengths[row] === undefined && value < threshold) lengths[row] = step;
|
|
495
|
+
});
|
|
496
|
+
if (lengths.every(length => length !== undefined)) break;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
using packed = ops.concatAxis(tokens, 0); const values = packed.toIntTokens();
|
|
501
|
+
using packedConfidence = !pruning && confidence.length ? ops.concatAxis(confidence, 0) : null;
|
|
502
|
+
const conf = packedConfidence?.toFloat32();
|
|
503
|
+
const sizes = lengths.map(length => length ?? tokens.length);
|
|
504
|
+
let draftLogits: MlxArray | undefined;
|
|
505
|
+
if (collect) {
|
|
506
|
+
using full = ops.concatAxis(logits, 1);
|
|
507
|
+
draftLogits = full.slice([0, 0, 0], [B, Math.max(...sizes), V]);
|
|
508
|
+
}
|
|
509
|
+
return {
|
|
510
|
+
tokens: sizes.map((length, row) => Array.from({ length }, (_, step) => values[step * B + row]!)),
|
|
511
|
+
conf: sizes.map((length, row) => opts.collectConfidence === false ? [] : Array.from({ length }, (_, step) => pruning ? hostConfidence[step]![row]! : conf![step * B + row]!)), draftLogits
|
|
512
|
+
};
|
|
513
|
+
} finally { state?.dispose(); for (const array of [...tokens, ...confidence, ...logits]) array.dispose(); }
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
save(dir: string): void {
|
|
517
|
+
mkdirSync(dir, { recursive: true });
|
|
518
|
+
const tensors: NamedTensor[] = this.names.map((name) => ({ name, array: this.get(name) }));
|
|
519
|
+
writeShardedSafetensors(dir, tensors);
|
|
520
|
+
writeFileSync(join(dir, "dspark.json"), JSON.stringify({
|
|
521
|
+
// "dspark" is the canonical variant (this faithful module IS DSpark);
|
|
522
|
+
// load() accepts the legacy "dflash" stamp from older checkpoints.
|
|
523
|
+
kind: "dspark-drafter", variant: "dspark", version: 1,
|
|
524
|
+
target_id: this.targetId, config: this.cfg, dims: this.dims, param_names: this.names,
|
|
525
|
+
}, null, 2));
|
|
526
|
+
}
|
|
527
|
+
static load(dir: string): DflashDrafter {
|
|
528
|
+
const meta = JSON.parse(readFileSync(join(dir, "dspark.json"), "utf8")) as {
|
|
529
|
+
variant?: string; config: DflashConfig; dims: TargetDims; target_id: string;
|
|
530
|
+
};
|
|
531
|
+
if (meta.variant !== "dspark" && meta.variant !== "dflash")
|
|
532
|
+
throw new Error(`${dir} is not a dspark drafter (variant=${meta.variant ?? "none — a superseded v1 single-vector checkpoint?"})`);
|
|
533
|
+
const d = new DflashDrafter(meta.config, meta.dims, meta.target_id);
|
|
534
|
+
const tensors = loadAdapterTensors(join(dir, "model.safetensors"));
|
|
535
|
+
try {
|
|
536
|
+
for (const name of d.names) { const a = tensors.get(name); if (!a) throw new Error(`missing ${name}`); d.#p.set(name, a); }
|
|
537
|
+
} finally { for (const [name, arr] of tensors) if (!d.names.includes(name)) arr.dispose(); }
|
|
538
|
+
return d;
|
|
539
|
+
}
|
|
540
|
+
dispose(): void { for (const a of this.#p.values()) a.dispose(); this.#p.clear(); }
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function buildNames(cfg: DflashConfig): string[] {
|
|
544
|
+
const names: string[] = [];
|
|
545
|
+
for (let i = 0; i < cfg.nLayers; i++)
|
|
546
|
+
names.push(`bb.${i}.attn_norm`, `bb.${i}.q`, `bb.${i}.k`, `bb.${i}.v`, `bb.${i}.o`, `bb.${i}.ff_norm`, `bb.${i}.gate`, `bb.${i}.up`, `bb.${i}.down`);
|
|
547
|
+
names.push("W_c", "ctx_norm", "tok_proj", "mask_emb", "block_pos", "out_norm", "out_proj", "markov.w1", "markov.w2", "conf.w", "conf.b");
|
|
548
|
+
// rnn.* MUST be appended LAST — see the matching comment in initFromDims:
|
|
549
|
+
// this ordering keeps the shared/markov params drawing identical seeded rng
|
|
550
|
+
// values whether or not the rnn head is present (init-equivalence gate).
|
|
551
|
+
if (cfg.seqHead === "rnn") names.push("rnn.wH", "rnn.bH", "rnn.wO");
|
|
552
|
+
return names;
|
|
553
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// How a DFlash 2 drafter (incoai/Qwen3.8-27B-DFlash2) declares itself in its
|
|
2
|
+
// config.json. No MLX: the draft registry reads it before loading anything.
|
|
3
|
+
|
|
4
|
+
/** `architectures[0]` of a DFlash 2 checkpoint. */
|
|
5
|
+
const DFLASH2_ARCHITECTURE = "DFlash2DraftModel";
|
|
6
|
+
|
|
7
|
+
export function isDflash2Architecture(architectures: unknown): boolean {
|
|
8
|
+
return Array.isArray(architectures) && architectures[0] === DFLASH2_ARCHITECTURE;
|
|
9
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { mapOperations } from "../../runtime/row-operations";
|