@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,744 @@
|
|
|
1
|
+
// DeepSpec's Gemma4DSparkModel — semi-autoregressive draft model, ported
|
|
2
|
+
// verbatim (copy-verbatim methodology: transcribe THEIR forward, then port
|
|
3
|
+
// op-for-op) from github.com/deepseek-ai/DeepSpec (MIT), files:
|
|
4
|
+
// deepspec/modeling/dspark/gemma4/modeling.py (Gemma4DSparkModel)
|
|
5
|
+
// deepspec/modeling/dspark/common.py (extract_context_feature)
|
|
6
|
+
// deepspec/modeling/dspark/markov_head.py (VanillaMarkov)
|
|
7
|
+
// deepspec/eval/dspark/draft_ops.py (inference-time draft loop)
|
|
8
|
+
// deepspec/utils/sampling.py (sample_tokens, temp=0 argmax)
|
|
9
|
+
// Cross-checked against the installed HF reference (transformers
|
|
10
|
+
// models/gemma4/modeling_gemma4.py) for Gemma4RMSNorm, apply_rotary_pos_emb,
|
|
11
|
+
// Gemma4TextRotaryEmbedding (rope_type "proportional" via
|
|
12
|
+
// modeling_rope_utils._compute_proportional_rope_parameters), and
|
|
13
|
+
// Gemma4TextScaledWordEmbedding — since Gemma4DSparkModel subclasses/reuses
|
|
14
|
+
// those directly rather than redefining them.
|
|
15
|
+
//
|
|
16
|
+
// This is a DRAFT model for target-Gemma4 speculative decoding: not
|
|
17
|
+
// causal, not autoregressive over the whole sequence — it predicts a
|
|
18
|
+
// γ-token block in one backbone pass (context-conditioned, bidirectional
|
|
19
|
+
// within the block), then a cheap sequential Markov correction walks the
|
|
20
|
+
// block left-to-right applying a low-rank transition bias per step.
|
|
21
|
+
//
|
|
22
|
+
// This module is STATELESS server-lifetime weights. Per-request context
|
|
23
|
+
// K/V (the incremental cache DeepSpec threads through consecutive draft
|
|
24
|
+
// rounds via a DynamicCache) is NOT stored here — see `projectContextKVRows` /
|
|
25
|
+
// `draftRows` below for the seam.
|
|
26
|
+
|
|
27
|
+
import { Weights } from "../../artifacts/weights";
|
|
28
|
+
import type {
|
|
29
|
+
ContextKV, DeepspecContextAttention, DeepspecDraftRows, DeepspecDrafterModel, DrafterContextKV, DrafterContextProjection,
|
|
30
|
+
} from "../../contracts/mlx/drafter";
|
|
31
|
+
import type { MlxRowTable } from "../../contracts/mlx/graph";
|
|
32
|
+
import { isDeepspecArchitecture } from "./deepspec-artifact";
|
|
33
|
+
import { MlxArray } from "@mlx-bun/mlx/array";
|
|
34
|
+
import { Dtype } from "@mlx-bun/mlx/ffi";
|
|
35
|
+
import * as ops from "@mlx-bun/mlx/ops";
|
|
36
|
+
import { parseQuantization, quantFor, type QuantizationConfig } from "../../artifacts/config";
|
|
37
|
+
|
|
38
|
+
function disposing(old: MlxArray, next: MlxArray): MlxArray {
|
|
39
|
+
old.dispose();
|
|
40
|
+
return next;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// Weight representation: every matmul weight and gather table loads as either
|
|
45
|
+
// bf16 (the released checkpoint) or affine-quantized (a
|
|
46
|
+
// `02d723a:scripts/dspark.ts` quantize sibling). Detection is the house
|
|
47
|
+
// pattern — a `.scales` sibling key marks a quantized module; bits/group_size
|
|
48
|
+
// come from the config's `quantization` block (per-module overrides + the
|
|
49
|
+
// mlx `false` = kept-full-precision convention). Both formats flow through
|
|
50
|
+
// the same forward: the quantized matmul path is mlx QuantizedLinear
|
|
51
|
+
// semantics (x @ W^T via quantized_matmul transpose=true) and the quantized
|
|
52
|
+
// gather path is mlx QuantizedEmbedding semantics (gather packed/scales/bias
|
|
53
|
+
// rows, dequantize the gathered rows) — matching mlx-lm's numerics.
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
/** A Linear weight `W [out, in]`, used as `x @ W^T`. bf16 keeps the lazy
|
|
57
|
+
* transpose VIEW (see the memory note below); quant keeps packed storage. */
|
|
58
|
+
type MatW =
|
|
59
|
+
| { kind: "bf16"; t: MlxArray }
|
|
60
|
+
| { kind: "quant"; w: MlxArray; scales: MlxArray; biases: MlxArray | null; spec: ops.QuantSpec };
|
|
61
|
+
|
|
62
|
+
/** An embedding table `[vocab, dim]`, used via row gather. */
|
|
63
|
+
type TableW =
|
|
64
|
+
| { kind: "bf16"; w: MlxArray }
|
|
65
|
+
| { kind: "quant"; w: MlxArray; scales: MlxArray; biases: MlxArray | null; spec: ops.QuantSpec };
|
|
66
|
+
|
|
67
|
+
/** x @ W^T for either format. Output dtype follows x (bf16 on the real
|
|
68
|
+
* checkpoint) in BOTH branches — the model-dtype fidelity notes on the
|
|
69
|
+
* markov/confidence paths hold unchanged for the quantized path. */
|
|
70
|
+
function matmulW(x: MlxArray, m: MatW): MlxArray {
|
|
71
|
+
if (m.kind === "bf16") return ops.matmul(x, m.t);
|
|
72
|
+
return ops.quantizedMatmul(x, m.w, m.scales, m.biases, m.spec, true);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Row gather for either format (quant: QuantizedEmbedding.encode —
|
|
76
|
+
* dequantize returns the scales' dtype, bf16, same as the bf16 branch). */
|
|
77
|
+
function gatherW(t: TableW, idsU32: MlxArray): MlxArray {
|
|
78
|
+
if (t.kind === "bf16") return ops.takeAxis(t.w, idsU32, 0);
|
|
79
|
+
const rows = ops.takeAxis(t.w, idsU32, 0);
|
|
80
|
+
const scaleRows = ops.takeAxis(t.scales, idsU32, 0);
|
|
81
|
+
const biasRows = t.biases ? ops.takeAxis(t.biases, idsU32, 0) : null;
|
|
82
|
+
const out = ops.dequantize(rows, scaleRows, biasRows, t.spec);
|
|
83
|
+
rows.dispose();
|
|
84
|
+
scaleRows.dispose();
|
|
85
|
+
biasRows?.dispose();
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function disposeW(m: MatW | TableW | null): void {
|
|
90
|
+
if (!m) return;
|
|
91
|
+
if (m.kind === "bf16") {
|
|
92
|
+
("t" in m ? m.t : m.w).dispose();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
m.w.dispose();
|
|
96
|
+
m.scales.dispose();
|
|
97
|
+
m.biases?.dispose();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// Config (their config.json field names, verbatim keys — no renaming so the
|
|
102
|
+
// mapping to the checkpoint stays obvious).
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
export interface DeepspecConfig {
|
|
106
|
+
architectures: string[];
|
|
107
|
+
hidden_size: number;
|
|
108
|
+
num_hidden_layers: number;
|
|
109
|
+
num_attention_heads: number;
|
|
110
|
+
global_head_dim: number;
|
|
111
|
+
num_global_key_value_heads: number;
|
|
112
|
+
attention_k_eq_v: boolean;
|
|
113
|
+
intermediate_size: number;
|
|
114
|
+
hidden_activation: string;
|
|
115
|
+
rms_norm_eps: number;
|
|
116
|
+
final_logit_softcapping: number | null;
|
|
117
|
+
vocab_size: number;
|
|
118
|
+
block_size: number;
|
|
119
|
+
mask_token_id: number;
|
|
120
|
+
target_layer_ids: number[];
|
|
121
|
+
num_target_layers: number;
|
|
122
|
+
markov_rank: number;
|
|
123
|
+
markov_head_type: string;
|
|
124
|
+
enable_confidence_head: boolean;
|
|
125
|
+
confidence_head_with_markov: boolean;
|
|
126
|
+
rope_theta: number;
|
|
127
|
+
partial_rotary_factor: number;
|
|
128
|
+
/** Not in the checkpoint's config.json (draft_ops.py takes it as a call
|
|
129
|
+
* arg to build_dspark_proposal); default 0 = confidence head disabled
|
|
130
|
+
* functionally even when weights exist (threshold<=0 ⇒ full γ block). */
|
|
131
|
+
confidence_threshold: number;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function readConfig(raw: Record<string, any>): DeepspecConfig {
|
|
135
|
+
if (!isDeepspecArchitecture(raw.architectures))
|
|
136
|
+
throw new Error(`DeepspecDrafter: expected architectures[0]==="Gemma4DSparkModel", got ${JSON.stringify(raw.architectures)}`);
|
|
137
|
+
|
|
138
|
+
// RoPE: their config nests rope params under rope_parameters.full_attention
|
|
139
|
+
// (matches Gemma4TextConfig / Gemma4TextRotaryEmbedding's per-layer-type
|
|
140
|
+
// dict); ground truth also allows a flat rope_theta/partial_rotary_factor
|
|
141
|
+
// for simplified checkpoints — accept either shape.
|
|
142
|
+
const ropeFull = raw.rope_parameters?.full_attention ?? raw.rope_parameters ?? {};
|
|
143
|
+
const ropeTheta = ropeFull.rope_theta ?? raw.rope_theta ?? 1e6;
|
|
144
|
+
const partialRotary = ropeFull.partial_rotary_factor ?? raw.partial_rotary_factor ?? 1.0;
|
|
145
|
+
|
|
146
|
+
const targetLayerIds: number[] = raw.target_layer_ids;
|
|
147
|
+
if (!Array.isArray(targetLayerIds) || targetLayerIds.length === 0)
|
|
148
|
+
throw new Error("DeepspecDrafter: config.target_layer_ids must be a non-empty array");
|
|
149
|
+
|
|
150
|
+
// Silent-wrongness guards (2026-07-06 port review): each of these variants
|
|
151
|
+
// would LOAD cleanly and compute wrong math — this module implements only
|
|
152
|
+
// the released-checkpoint shape. Refuse loudly instead.
|
|
153
|
+
if (!raw.attention_k_eq_v)
|
|
154
|
+
throw new Error(
|
|
155
|
+
"DeepspecDrafter: attention_k_eq_v=false checkpoints need a real v_proj path — not implemented (this module wires V ≡ K)",
|
|
156
|
+
);
|
|
157
|
+
if ((raw.markov_rank ?? 0) > 0 && (raw.markov_head_type ?? "vanilla") !== "vanilla")
|
|
158
|
+
throw new Error(
|
|
159
|
+
`DeepspecDrafter: markov_head_type "${raw.markov_head_type}" not implemented (gated/rnn heads ship markov_w1/w2 too and would silently get vanilla math) — only "vanilla"`,
|
|
160
|
+
);
|
|
161
|
+
if ((raw.hidden_activation ?? "gelu_pytorch_tanh") !== "gelu_pytorch_tanh")
|
|
162
|
+
throw new Error(
|
|
163
|
+
`DeepspecDrafter: hidden_activation "${raw.hidden_activation}" not implemented — the MLP hardcodes gelu_pytorch_tanh`,
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
architectures: raw.architectures,
|
|
168
|
+
hidden_size: raw.hidden_size,
|
|
169
|
+
num_hidden_layers: raw.num_hidden_layers,
|
|
170
|
+
num_attention_heads: raw.num_attention_heads,
|
|
171
|
+
global_head_dim: raw.global_head_dim,
|
|
172
|
+
num_global_key_value_heads: raw.num_global_key_value_heads,
|
|
173
|
+
attention_k_eq_v: !!raw.attention_k_eq_v,
|
|
174
|
+
intermediate_size: raw.intermediate_size,
|
|
175
|
+
hidden_activation: raw.hidden_activation ?? "gelu_pytorch_tanh",
|
|
176
|
+
rms_norm_eps: raw.rms_norm_eps ?? 1e-6,
|
|
177
|
+
final_logit_softcapping: raw.final_logit_softcapping ?? null,
|
|
178
|
+
vocab_size: raw.vocab_size,
|
|
179
|
+
block_size: raw.block_size,
|
|
180
|
+
mask_token_id: raw.mask_token_id,
|
|
181
|
+
target_layer_ids: targetLayerIds,
|
|
182
|
+
num_target_layers: raw.num_target_layers,
|
|
183
|
+
markov_rank: raw.markov_rank ?? 0,
|
|
184
|
+
markov_head_type: raw.markov_head_type ?? "vanilla",
|
|
185
|
+
enable_confidence_head: !!raw.enable_confidence_head,
|
|
186
|
+
confidence_head_with_markov: !!raw.confidence_head_with_markov,
|
|
187
|
+
rope_theta: ropeTheta,
|
|
188
|
+
partial_rotary_factor: partialRotary,
|
|
189
|
+
confidence_threshold: raw.confidence_threshold ?? 0,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
// Per-layer weights.
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
interface Layer {
|
|
198
|
+
qProj: MatW; // [nHeads*headDim, hidden] Linear storage, used as x@W^T
|
|
199
|
+
kProj: MatW; // [nKvHeads*headDim, hidden]
|
|
200
|
+
oProj: MatW; // [hidden, nHeads*headDim]
|
|
201
|
+
qNorm: MlxArray; // [headDim]
|
|
202
|
+
kNorm: MlxArray; // [headDim]
|
|
203
|
+
// v_norm has with_scale=False (Gemma4RMSNorm(..., with_scale=False)) — no
|
|
204
|
+
// weight tensor in the checkpoint; represented as `null` into ops.rmsNorm.
|
|
205
|
+
inputNorm: MlxArray;
|
|
206
|
+
postAttnNorm: MlxArray;
|
|
207
|
+
preFfNorm: MlxArray;
|
|
208
|
+
postFfNorm: MlxArray;
|
|
209
|
+
gateProj: MatW;
|
|
210
|
+
upProj: MatW;
|
|
211
|
+
downProj: MatW;
|
|
212
|
+
layerScalar: MlxArray; // [1]
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export class DeepspecDrafter implements DeepspecDrafterModel {
|
|
216
|
+
readonly cfg: DeepspecConfig;
|
|
217
|
+
/** === config.target_layer_ids, alias for the ground-truth term. */
|
|
218
|
+
readonly tapLayers: number[];
|
|
219
|
+
/** === config.block_size (γ), alias for the ground-truth term. */
|
|
220
|
+
readonly gamma: number;
|
|
221
|
+
readonly hidden: number;
|
|
222
|
+
readonly nHeads: number;
|
|
223
|
+
readonly nKvHeads: number;
|
|
224
|
+
readonly headDim: number;
|
|
225
|
+
readonly eps: number;
|
|
226
|
+
readonly embedScale: number;
|
|
227
|
+
readonly ropeFreqs: MlxArray; // proportional-RoPE freqs, [headDim/2]
|
|
228
|
+
|
|
229
|
+
#w: Weights;
|
|
230
|
+
#embed: TableW; // [vocab, hidden]
|
|
231
|
+
#fc: MatW; // fc.weight [hidden, taps*hidden] Linear storage
|
|
232
|
+
#hiddenNorm: MlxArray; // [hidden]
|
|
233
|
+
#norm: MlxArray; // [hidden]
|
|
234
|
+
#lmHead: MatW; // lm_head.weight [vocab, hidden]
|
|
235
|
+
#layers: Layer[] = [];
|
|
236
|
+
#markovW1: TableW | null; // [vocab, markovRank] embedding
|
|
237
|
+
#markovW2: MatW | null; // markov_w2.weight [vocab, rank] Linear storage
|
|
238
|
+
/** One block step's token per row, bound once: the argmax of the step's
|
|
239
|
+
* logits [B, V], plus the Markov head's bias from the previous tokens [B]
|
|
240
|
+
* when the checkpoint carries one. Borrows both; owns the ids. */
|
|
241
|
+
readonly #selectStep: (logits: MlxArray, previous: MlxArray) => MlxArray;
|
|
242
|
+
#confProj: MatW | null; // proj.weight [1, confDim] Linear storage (bf16
|
|
243
|
+
// keeps the once-built transpose view — per-call
|
|
244
|
+
// transpose+cast leaked, 2026-07-06 review fix)
|
|
245
|
+
#confB: MlxArray | null; // [1]
|
|
246
|
+
|
|
247
|
+
private constructor(w: Weights, cfg: DeepspecConfig, quant: QuantizationConfig | null) {
|
|
248
|
+
this.#w = w;
|
|
249
|
+
this.cfg = cfg;
|
|
250
|
+
this.tapLayers = cfg.target_layer_ids;
|
|
251
|
+
this.gamma = cfg.block_size;
|
|
252
|
+
this.hidden = cfg.hidden_size;
|
|
253
|
+
this.nHeads = cfg.num_attention_heads;
|
|
254
|
+
this.nKvHeads = cfg.num_global_key_value_heads; // k_eq_v enforced in readConfig (no v_proj path)
|
|
255
|
+
this.headDim = cfg.global_head_dim;
|
|
256
|
+
this.eps = cfg.rms_norm_eps;
|
|
257
|
+
this.embedScale = Math.sqrt(cfg.hidden_size);
|
|
258
|
+
|
|
259
|
+
const T = (name: string) => w.tensor(name);
|
|
260
|
+
// Lazy transpose VIEW — no contiguous copy. Materializing would store
|
|
261
|
+
// every matmul weight a
|
|
262
|
+
// second time: on the real 6.86 GB checkpoint that's ~+4.8 GB resident
|
|
263
|
+
// (lm_head alone ~2 GB), decisive on a 24 GB box. mlx's steel GEMM
|
|
264
|
+
// dispatches a transposed-B operand natively, so the view costs nothing
|
|
265
|
+
// per matmul. (2026-07-06 port review, MEDIUM-memory finding.)
|
|
266
|
+
const transposed = (name: string): MlxArray => ops.transposeAxes(T(name), [1, 0]);
|
|
267
|
+
// Quantized-module detection + spec (house pattern: `.scales` sibling
|
|
268
|
+
// key gates; bits/group_size from the config quantization block).
|
|
269
|
+
const qspec = (base: string): ops.QuantSpec => {
|
|
270
|
+
const spec = quantFor(quant, base);
|
|
271
|
+
if (!spec)
|
|
272
|
+
throw new Error(
|
|
273
|
+
`DeepspecDrafter: ${base} has quantized tensors (.scales sibling) but no quantization config entry`,
|
|
274
|
+
);
|
|
275
|
+
return { bits: spec.bits, groupSize: spec.groupSize, mode: spec.mode };
|
|
276
|
+
};
|
|
277
|
+
const quantParts = (base: string) => ({
|
|
278
|
+
w: T(`${base}.weight`),
|
|
279
|
+
scales: T(`${base}.scales`),
|
|
280
|
+
biases: w.has(`${base}.biases`) ? T(`${base}.biases`) : null,
|
|
281
|
+
spec: qspec(base),
|
|
282
|
+
});
|
|
283
|
+
const mat = (base: string): MatW =>
|
|
284
|
+
w.has(`${base}.scales`)
|
|
285
|
+
? { kind: "quant", ...quantParts(base) }
|
|
286
|
+
: { kind: "bf16", t: transposed(`${base}.weight`) };
|
|
287
|
+
const table = (base: string): TableW =>
|
|
288
|
+
w.has(`${base}.scales`)
|
|
289
|
+
? { kind: "quant", ...quantParts(base) }
|
|
290
|
+
: { kind: "bf16", w: T(`${base}.weight`) };
|
|
291
|
+
|
|
292
|
+
this.#embed = table("embed_tokens");
|
|
293
|
+
this.#fc = mat("fc");
|
|
294
|
+
this.#hiddenNorm = T("hidden_norm.weight");
|
|
295
|
+
this.#norm = T("norm.weight");
|
|
296
|
+
this.#lmHead = mat("lm_head");
|
|
297
|
+
|
|
298
|
+
// Proportional RoPE freqs (mlx_lm.models.rope_utils.ProportionalRoPE,
|
|
299
|
+
// transformers._compute_proportional_rope_parameters): rotated_dims =
|
|
300
|
+
// int(head_dim * partial_rotary_factor); exponents over [0, rotated_dims)
|
|
301
|
+
// step 2, divided by FULL head_dim (not rotated_dims); tail padded with
|
|
302
|
+
// +inf ⇒ angle pos/∞ = 0 ⇒ cos=1, sin=0 — the identity rotation, i.e.
|
|
303
|
+
// passthrough on those dims (freqs is the wavelength array fast::rope
|
|
304
|
+
// divides position by, same convention as packages/inference/src/models/gemma4/assistant.ts's
|
|
305
|
+
// ProportionalRoPE port; verified vs mlx_lm rope_utils.ProportionalRoPE).
|
|
306
|
+
const rotatedDims = Math.floor(this.headDim * cfg.partial_rotary_factor);
|
|
307
|
+
const n = this.headDim / 2;
|
|
308
|
+
const freqs = new Float32Array(n).fill(Infinity);
|
|
309
|
+
for (let k = 0; k < rotatedDims / 2; k++) {
|
|
310
|
+
freqs[k] = Math.pow(cfg.rope_theta, (2 * k) / this.headDim);
|
|
311
|
+
}
|
|
312
|
+
this.ropeFreqs = MlxArray.fromFloat32(freqs, [n]);
|
|
313
|
+
|
|
314
|
+
for (let i = 0; i < cfg.num_hidden_layers; i++) {
|
|
315
|
+
const p = `layers.${i}`;
|
|
316
|
+
this.#layers.push({
|
|
317
|
+
qProj: mat(`${p}.self_attn.q_proj`),
|
|
318
|
+
kProj: mat(`${p}.self_attn.k_proj`),
|
|
319
|
+
oProj: mat(`${p}.self_attn.o_proj`),
|
|
320
|
+
qNorm: T(`${p}.self_attn.q_norm.weight`),
|
|
321
|
+
kNorm: T(`${p}.self_attn.k_norm.weight`),
|
|
322
|
+
inputNorm: T(`${p}.input_layernorm.weight`),
|
|
323
|
+
postAttnNorm: T(`${p}.post_attention_layernorm.weight`),
|
|
324
|
+
preFfNorm: T(`${p}.pre_feedforward_layernorm.weight`),
|
|
325
|
+
postFfNorm: T(`${p}.post_feedforward_layernorm.weight`),
|
|
326
|
+
gateProj: mat(`${p}.mlp.gate_proj`),
|
|
327
|
+
upProj: mat(`${p}.mlp.up_proj`),
|
|
328
|
+
downProj: mat(`${p}.mlp.down_proj`),
|
|
329
|
+
layerScalar: T(`${p}.layer_scalar`),
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (cfg.markov_rank > 0) {
|
|
334
|
+
this.#markovW1 = table("markov_head.markov_w1"); // [vocab, rank] embedding
|
|
335
|
+
this.#markovW2 = mat("markov_head.markov_w2"); // stored [vocab, rank] Linear
|
|
336
|
+
this.#selectStep = (logits, previous) => {
|
|
337
|
+
using bias = this.#markovStepBias(previous);
|
|
338
|
+
using corrected = ops.add(logits, bias);
|
|
339
|
+
return ops.argmaxAxis(corrected, -1);
|
|
340
|
+
};
|
|
341
|
+
} else {
|
|
342
|
+
this.#markovW1 = null;
|
|
343
|
+
this.#markovW2 = null;
|
|
344
|
+
this.#selectStep = logits => ops.argmaxAxis(logits, -1);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
if (cfg.enable_confidence_head) {
|
|
348
|
+
this.#confProj = mat("confidence_head.proj"); // [1, confDim] Linear
|
|
349
|
+
this.#confB = T("confidence_head.proj.bias"); // [1]
|
|
350
|
+
} else {
|
|
351
|
+
this.#confProj = null;
|
|
352
|
+
this.#confB = null;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
static async load(dir: string): Promise<DeepspecDrafter> {
|
|
357
|
+
const raw = (await Bun.file(`${dir}/config.json`).json()) as Record<string, any>;
|
|
358
|
+
const cfg = readConfig(raw);
|
|
359
|
+
// Quantized siblings (`02d723a:scripts/dspark.ts` quantize) carry the house
|
|
360
|
+
// quantization block; the released bf16 checkpoint has none → null.
|
|
361
|
+
const quant = parseQuantization(raw.quantization ?? raw.quantization_config);
|
|
362
|
+
const w = await Weights.open(dir);
|
|
363
|
+
return new DeepspecDrafter(w, cfg, quant);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** f32-internal RMSNorm (Gemma4RMSNorm casts through float32 internally:
|
|
367
|
+
* `hidden_states.float()` → norm → `* weight.float()` → `.type_as`).
|
|
368
|
+
* weight=null reproduces `with_scale=False` (v_norm). */
|
|
369
|
+
#rms(x: MlxArray, weight: MlxArray | null): MlxArray {
|
|
370
|
+
const f = x.dtype === Dtype.float32 ? x : x.astype(Dtype.float32);
|
|
371
|
+
const n = ops.rmsNorm(f, weight, this.eps);
|
|
372
|
+
if (f !== x) f.dispose();
|
|
373
|
+
if (n.dtype === x.dtype) return n;
|
|
374
|
+
const back = n.astype(x.dtype);
|
|
375
|
+
n.dispose();
|
|
376
|
+
return back;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
#geluTanhMlp(x: MlxArray, layer: Layer): MlxArray {
|
|
380
|
+
const g = matmulW(x, layer.gateProj);
|
|
381
|
+
const u = matmulW(x, layer.upProj);
|
|
382
|
+
const act = ops.geluApprox(g); // gelu_pytorch_tanh == config.hidden_activation
|
|
383
|
+
g.dispose();
|
|
384
|
+
let mlp = ops.mul(act, u);
|
|
385
|
+
act.dispose();
|
|
386
|
+
u.dispose();
|
|
387
|
+
mlp = disposing(mlp, matmulW(mlp, layer.downProj));
|
|
388
|
+
return mlp;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* extract_context_feature (common.py):
|
|
393
|
+
* torch.cat([hidden_states[0 if lid==-1 else lid+1] for lid in layer_ids], -1)
|
|
394
|
+
* i.e. tap i (target_layer_ids[i], never -1 for this checkpoint) reads the
|
|
395
|
+
* TARGET's post-layer-i residual output (list-of-all-hidden-states
|
|
396
|
+
* convention: index 0 = embedding, index L+1 = output of layer L). The
|
|
397
|
+
* caller is expected to hand us exactly that: targetHiddens is the
|
|
398
|
+
* concatenation over taps, [1, L, taps*hidden], already ordered to match
|
|
399
|
+
* config.target_layer_ids (ascending, enforced upstream by
|
|
400
|
+
* validate_target_layer_ids).
|
|
401
|
+
*
|
|
402
|
+
* context = hidden_norm(fc(target_hiddens)) — modeling.py _forward_backbone:
|
|
403
|
+
* target_hidden_states = self.hidden_norm(self.fc(target_hidden_states))
|
|
404
|
+
*
|
|
405
|
+
* Returns the projected+normed context hidden [1, L, hidden] (still needs
|
|
406
|
+
* per-layer k_proj + k_norm + rope to become cacheable ContextKV — see
|
|
407
|
+
* projectContextKVRows).
|
|
408
|
+
*/
|
|
409
|
+
#projectContext(targetHiddens: MlxArray): MlxArray {
|
|
410
|
+
const proj = matmulW(targetHiddens, this.#fc); // [1,L,hidden]
|
|
411
|
+
return disposing(proj, this.#rms(proj, this.#hiddenNorm));
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** The context projection for every positive B·L row count (`matmulW`:
|
|
415
|
+
* MLX's quantized matmul, matmul for a BF16 checkpoint). */
|
|
416
|
+
readonly projectContext: MlxRowTable<DrafterContextProjection> =
|
|
417
|
+
Object.freeze({
|
|
418
|
+
default: (targetHiddens: MlxArray) => this.#projectContext(targetHiddens),
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
/** Each layer's context K/V: the same operation for every positive B·L row count. */
|
|
422
|
+
readonly projectContextKVRows: MlxRowTable<DrafterContextKV> =
|
|
423
|
+
Object.freeze({
|
|
424
|
+
default: (contextHidden: MlxArray, position: number | MlxArray) => this.#projectContextKVRows(contextHidden, position),
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Per-layer context K/V rows, projected + normed + ROPE'd, ready to cache
|
|
429
|
+
* across draft rounds.
|
|
430
|
+
*
|
|
431
|
+
* Justification for caching at this stage (from modeling.py's
|
|
432
|
+
* Gemma4DSparkAttention.forward, transcribed above the port below):
|
|
433
|
+
* k_ctx = self.k_proj(target_hidden_states) # per-layer proj
|
|
434
|
+
* k = torch.cat([k_ctx, k_noise], dim=1).view(...) # concat BEFORE norm
|
|
435
|
+
* k = self.k_norm(k).transpose(1, 2) # norm over the concat
|
|
436
|
+
* k = apply_gemma4_rotary_pos_emb(k, cos, sin, ...) # rope over the concat
|
|
437
|
+
* if past_key_values is not None:
|
|
438
|
+
* k, v = past_key_values.update(k, v, self.layer_idx, cache_kwargs) # CACHE AFTER ROPE
|
|
439
|
+
*
|
|
440
|
+
* Gemma4RMSNorm normalizes over the LAST axis (head_dim) independently per
|
|
441
|
+
* row; concatenation happens along the sequence axis. So k_norm(cat(ctx,
|
|
442
|
+
* noise))[i] == k_norm(ctx)[i] for every ctx row i — norming the context
|
|
443
|
+
* rows alone and norming them as part of a larger concat batch produce
|
|
444
|
+
* IDENTICAL values (RMSNorm has no cross-row term). RoPE likewise applies
|
|
445
|
+
* per-position (absolute position index, stable per context row across
|
|
446
|
+
* rounds) independent of what else shares the batch. Caching post-norm,
|
|
447
|
+
* post-rope context K rows is therefore bit-exact equivalent to
|
|
448
|
+
* recomputing them fresh inside every round's concat — which is exactly
|
|
449
|
+
* what DeepSpec's own DynamicCache.update-after-rope does (it caches the
|
|
450
|
+
* already roped/normed tensor, then crop() drops only the noise suffix).
|
|
451
|
+
*
|
|
452
|
+
* v ≡ k when attention_k_eq_v (v_proj is absent; v_norm is the SAME
|
|
453
|
+
* concat-then-scale-less-norm, over k_proj's output — v gets NO rope).
|
|
454
|
+
* `position` is the first context row's absolute position (per row as an
|
|
455
|
+
* array when the rows start at different positions).
|
|
456
|
+
*/
|
|
457
|
+
#projectContextKVRows(contextHidden: MlxArray, position: number | MlxArray): ContextKV[] {
|
|
458
|
+
const B = contextHidden.shape[0]!, L = contextHidden.shape[1]!;
|
|
459
|
+
const out: ContextKV[] = [];
|
|
460
|
+
for (const layer of this.#layers) {
|
|
461
|
+
const kFlat = matmulW(contextHidden, layer.kProj); // [1,L,nKvHeads*headDim]
|
|
462
|
+
const k4 = ops.reshape(kFlat, [B, L, this.nKvHeads, this.headDim]);
|
|
463
|
+
kFlat.dispose();
|
|
464
|
+
// v ≡ k pre-norm (attention_k_eq_v: v_ctx = k_ctx, same tensor before
|
|
465
|
+
// the two norms diverge — v_norm has no weight).
|
|
466
|
+
const vNormed = this.#rms(k4, null); // scale-less
|
|
467
|
+
const kNormed = this.#rms(k4, layer.kNorm);
|
|
468
|
+
k4.dispose();
|
|
469
|
+
|
|
470
|
+
const kT = ops.transposeAxes(kNormed, [0, 2, 1, 3]); // [1,nKvHeads,L,headDim]
|
|
471
|
+
kNormed.dispose();
|
|
472
|
+
const vT = ops.transposeAxes(vNormed, [0, 2, 1, 3]);
|
|
473
|
+
vNormed.dispose();
|
|
474
|
+
|
|
475
|
+
const kRoped = typeof position === "number"
|
|
476
|
+
? ops.rope(kT, this.headDim, null, position, this.ropeFreqs)
|
|
477
|
+
: ops.ropeDynamic(kT, this.headDim, null, position, this.ropeFreqs);
|
|
478
|
+
kT.dispose();
|
|
479
|
+
out.push({ k: kRoped, v: vT });
|
|
480
|
+
}
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* One backbone forward over the noise block, given cached context K/V —
|
|
486
|
+
* modeling.py Gemma4DSparkModel._forward_backbone + Gemma4DSparkAttention,
|
|
487
|
+
* transcribed inline per-layer below. Non-causal SDPA (scale=1.0) over
|
|
488
|
+
* [ctx rows ++ block rows]; q uses only the block's own positions.
|
|
489
|
+
*
|
|
490
|
+
* blockIds: token ids for each noise block, shape [B, gamma] — [anchor, MASK,
|
|
491
|
+
* MASK, ..., MASK] (create_noise_embed: only position 0 gets the real
|
|
492
|
+
* anchor token when block_keep_mask; MASK elsewhere — at inference every
|
|
493
|
+
* anchor is "kept" so this is always [anchor, mask_token_id × (γ-1)]).
|
|
494
|
+
* position: each row's initial absolute position. RoPE advances contiguous
|
|
495
|
+
* positions within the block.
|
|
496
|
+
*/
|
|
497
|
+
#forwardBackbone(context: DeepspecContextAttention, blockIds: MlxArray, position: number | MlxArray): MlxArray {
|
|
498
|
+
const B = blockIds.shape[0]!, G = blockIds.shape[1]!;
|
|
499
|
+
const idsU32 = blockIds.astype(Dtype.uint32);
|
|
500
|
+
const embRaw = gatherW(this.#embed, idsU32); // [1,G,hidden] (gather over vocab axis)
|
|
501
|
+
idsU32.dispose();
|
|
502
|
+
const embFlat = ops.reshape(embRaw, [B, G, this.hidden]);
|
|
503
|
+
embRaw.dispose();
|
|
504
|
+
// Gemma4TextScaledWordEmbedding.forward: embed(ids) * embed_scale
|
|
505
|
+
let h = ops.mulScalar(embFlat, this.embedScale);
|
|
506
|
+
embFlat.dispose();
|
|
507
|
+
|
|
508
|
+
for (let li = 0; li < this.#layers.length; li++) {
|
|
509
|
+
const layer = this.#layers[li]!;
|
|
510
|
+
|
|
511
|
+
const residual = h;
|
|
512
|
+
const x = this.#rms(h, layer.inputNorm);
|
|
513
|
+
|
|
514
|
+
// q = q_norm(q_proj(x).view(B,q_len,nHeads,headDim)).transpose(1,2)
|
|
515
|
+
const qFlat = matmulW(x, layer.qProj); // [1,G,nHeads*headDim]
|
|
516
|
+
const q4 = ops.reshape(qFlat, [B, G, this.nHeads, this.headDim]);
|
|
517
|
+
qFlat.dispose();
|
|
518
|
+
const qNormed = this.#rms(q4, layer.qNorm);
|
|
519
|
+
q4.dispose();
|
|
520
|
+
const qT = ops.transposeAxes(qNormed, [0, 2, 1, 3]); // [1,nHeads,G,headDim]
|
|
521
|
+
qNormed.dispose();
|
|
522
|
+
// rope on q uses the LAST q_len positions (cos[:, -q_len:, :]) — here
|
|
523
|
+
// q_len == G == the whole block, starting at each row's position.
|
|
524
|
+
const qRoped = typeof position === "number"
|
|
525
|
+
? ops.rope(qT, this.headDim, null, position, this.ropeFreqs)
|
|
526
|
+
: ops.ropeDynamic(qT, this.headDim, null, position, this.ropeFreqs);
|
|
527
|
+
qT.dispose();
|
|
528
|
+
|
|
529
|
+
// k_noise = k_proj(x); norm+rope IDENTICALLY to the cached context
|
|
530
|
+
// rows (concat-then-norm == norm-then-concat per the RMSNorm argument
|
|
531
|
+
// in projectContextKVRows's doc comment).
|
|
532
|
+
const kNoiseFlat = matmulW(x, layer.kProj);
|
|
533
|
+
const kNoise4 = ops.reshape(kNoiseFlat, [B, G, this.nKvHeads, this.headDim]);
|
|
534
|
+
kNoiseFlat.dispose();
|
|
535
|
+
const vNoiseNormed = this.#rms(kNoise4, null);
|
|
536
|
+
const kNoiseNormed = this.#rms(kNoise4, layer.kNorm);
|
|
537
|
+
kNoise4.dispose();
|
|
538
|
+
const kNoiseT = ops.transposeAxes(kNoiseNormed, [0, 2, 1, 3]);
|
|
539
|
+
kNoiseNormed.dispose();
|
|
540
|
+
const vNoiseT = ops.transposeAxes(vNoiseNormed, [0, 2, 1, 3]);
|
|
541
|
+
vNoiseNormed.dispose();
|
|
542
|
+
const kNoiseRoped = typeof position === "number"
|
|
543
|
+
? ops.rope(kNoiseT, this.headDim, null, position, this.ropeFreqs)
|
|
544
|
+
: ops.ropeDynamic(kNoiseT, this.headDim, null, position, this.ropeFreqs);
|
|
545
|
+
kNoiseT.dispose();
|
|
546
|
+
x.dispose();
|
|
547
|
+
|
|
548
|
+
const attnOut = context.attend(li, qRoped, kNoiseRoped, vNoiseT);
|
|
549
|
+
qRoped.dispose(); kNoiseRoped.dispose(); vNoiseT.dispose();
|
|
550
|
+
|
|
551
|
+
const attnT = ops.transposeAxes(attnOut, [0, 2, 1, 3]); // [1,G,nHeads,headDim]
|
|
552
|
+
attnOut.dispose();
|
|
553
|
+
const attnFlat = ops.reshape(attnT, [B, G, this.nHeads * this.headDim]);
|
|
554
|
+
attnT.dispose();
|
|
555
|
+
let attn = matmulW(attnFlat, layer.oProj);
|
|
556
|
+
attnFlat.dispose();
|
|
557
|
+
attn = disposing(attn, this.#rms(attn, layer.postAttnNorm));
|
|
558
|
+
h = ops.add(residual, attn);
|
|
559
|
+
residual.dispose();
|
|
560
|
+
attn.dispose();
|
|
561
|
+
|
|
562
|
+
const res2 = h;
|
|
563
|
+
const f = this.#rms(h, layer.preFfNorm);
|
|
564
|
+
let mlp = this.#geluTanhMlp(f, layer);
|
|
565
|
+
f.dispose();
|
|
566
|
+
mlp = disposing(mlp, this.#rms(mlp, layer.postFfNorm));
|
|
567
|
+
h = ops.add(res2, mlp);
|
|
568
|
+
res2.dispose();
|
|
569
|
+
mlp.dispose();
|
|
570
|
+
|
|
571
|
+
// Gemma4DSparkDecoderLayer.forward: `return hidden_states * self.layer_scalar`
|
|
572
|
+
// — the scalar multiplies the WHOLE layer output (residual-sum
|
|
573
|
+
// INCLUDED, not just the sublayer delta).
|
|
574
|
+
h = disposing(h, ops.mul(h, layer.layerScalar));
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return disposing(h, this.#rms(h, this.#norm));
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** lm_head(h) then softcap: `tanh(logits/cap)*cap` (compute_logits). */
|
|
581
|
+
#computeLogits(h: MlxArray): MlxArray {
|
|
582
|
+
const logits = matmulW(h, this.#lmHead);
|
|
583
|
+
if (this.cfg.final_logit_softcapping === null) return logits;
|
|
584
|
+
const cap = this.cfg.final_logit_softcapping;
|
|
585
|
+
const capArr = ops.scalarLike(cap, logits);
|
|
586
|
+
const scaled = ops.div(logits, capArr);
|
|
587
|
+
logits.dispose();
|
|
588
|
+
const t = ops.tanh(scaled);
|
|
589
|
+
scaled.dispose();
|
|
590
|
+
const out = ops.mul(t, capArr);
|
|
591
|
+
t.dispose();
|
|
592
|
+
capArr.dispose();
|
|
593
|
+
return out;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** B_k = markov_w2(markov_w1(prevTok)) — VanillaMarkov.compute_step_bias /
|
|
597
|
+
* project_bias(get_prev_embeddings(token_ids)). Returns [1,vocab] in MODEL
|
|
598
|
+
* dtype (bf16 on the real checkpoint) — the reference samples over the
|
|
599
|
+
* bf16 `logits + bias` sum, and softcapped logits in [-30,30] have bf16
|
|
600
|
+
* steps ~0.125-0.25, so an f32 sum here reorders near-ties vs torch and
|
|
601
|
+
* derails the sequential block (2026-07-06 port review, fidelity fix). */
|
|
602
|
+
#markovStepBias(previous: MlxArray): MlxArray {
|
|
603
|
+
if (!this.#markovW1 || !this.#markovW2)
|
|
604
|
+
throw new Error("markovStepBias: markov_rank == 0 (no markov head)");
|
|
605
|
+
const idxU32 = previous.astype(Dtype.uint32);
|
|
606
|
+
const e1 = gatherW(this.#markovW1, idxU32); // [1,rank]
|
|
607
|
+
idxU32.dispose();
|
|
608
|
+
const bias = matmulW(e1, this.#markovW2); // [1,vocab], model dtype
|
|
609
|
+
e1.dispose();
|
|
610
|
+
return bias;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** c_k = sigmoid(proj([h_k; markov_w1[prevTok]])). h1 is [1,hidden]
|
|
614
|
+
* (already the right dtype/shape row for this position). AcceptRatePredictor
|
|
615
|
+
* is nn.Linear(confDim,1) — proj.weight is [1,confDim]; we compute
|
|
616
|
+
* features @ proj.weight^T + bias without transposing storage (row-vector
|
|
617
|
+
* dot via matmul against a [confDim,1] view). */
|
|
618
|
+
#confidence(h1: MlxArray, previous: MlxArray): MlxArray {
|
|
619
|
+
if (!this.#confProj || !this.#confB)
|
|
620
|
+
throw new Error("confidence: confidence head disabled");
|
|
621
|
+
let feat = h1;
|
|
622
|
+
let ownFeat = false;
|
|
623
|
+
if (this.cfg.confidence_head_with_markov) {
|
|
624
|
+
if (!this.#markovW1) throw new Error("confidence_head_with_markov requires markov_rank > 0");
|
|
625
|
+
const idxU32 = previous.astype(Dtype.uint32);
|
|
626
|
+
const e1 = gatherW(this.#markovW1, idxU32); // [1,rank]
|
|
627
|
+
idxU32.dispose();
|
|
628
|
+
const e1f = e1.dtype === h1.dtype ? e1 : disposing(e1, e1.astype(h1.dtype));
|
|
629
|
+
feat = ops.concatAxis([h1, e1f], 1); // [1, hidden+rank]
|
|
630
|
+
e1f.dispose();
|
|
631
|
+
ownFeat = true;
|
|
632
|
+
}
|
|
633
|
+
// Reference precision (AcceptRatePredictor / predict_confidence_step):
|
|
634
|
+
// the nn.Linear runs in MODEL dtype (bf16 on the real checkpoint) and is
|
|
635
|
+
// .float()ed AFTER — computing it in f32 here flipped borderline
|
|
636
|
+
// threshold comparisons vs torch (2026-07-06 port review). So: matmul +
|
|
637
|
+
// bias in feat's dtype (matmulW: the once-built transpose view for bf16,
|
|
638
|
+
// qmm transpose=true for a quantized head), then cast.
|
|
639
|
+
let z = matmulW(feat, this.#confProj);
|
|
640
|
+
if (ownFeat) feat.dispose();
|
|
641
|
+
z = disposing(z, ops.add(z, this.#confB));
|
|
642
|
+
if (z.dtype !== Dtype.float32) z = disposing(z, z.astype(Dtype.float32));
|
|
643
|
+
z = disposing(z, ops.sigmoid(z));
|
|
644
|
+
return z;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* The whole per-round draft. Two-pass structure, matching the source
|
|
649
|
+
* exactly (draft_ops.py build_dspark_proposal calls sample_draft_tokens
|
|
650
|
+
* for the FULL block first, THEN predicts confidence over the full
|
|
651
|
+
* sampled sequence, THEN truncates — confidence does not short-circuit
|
|
652
|
+
* sampling):
|
|
653
|
+
*
|
|
654
|
+
* base_draft_logits = model.compute_logits(proposal_hidden_states) # [1,γ,V], softcapped
|
|
655
|
+
* sampled_tokens, draft_logits = model.sample_draft_tokens( # full γ, sequential Markov
|
|
656
|
+
* base_draft_logits, first_prev_token_ids=anchor, temperature=0)
|
|
657
|
+
* confidence_logits = predict_confidence_step( # full γ, over the SAMPLED prevs
|
|
658
|
+
* proposal_hidden_states,
|
|
659
|
+
* prev_token_ids=cat([anchor, sampled_tokens[:, :-1]]))
|
|
660
|
+
* proposal_draft_tokens = _confident_prefix_length(confidence_logits, threshold)
|
|
661
|
+
* verify_input_ids = cat([anchor, sampled_tokens[:, :proposal_draft_tokens]])
|
|
662
|
+
*
|
|
663
|
+
* Transcribed sequential Markov sampling (modeling.py sample_draft_tokens
|
|
664
|
+
* → markov_head.py VanillaMarkov.sample_block_tokens, temperature=0 ⇒
|
|
665
|
+
* sample_tokens's argmax branch — RNG-free):
|
|
666
|
+
* prev = first_prev_token_ids # == anchorTok
|
|
667
|
+
* for k in range(block_size):
|
|
668
|
+
* step_logits = base_logits[:,k] + markov_w2(markov_w1(prev))
|
|
669
|
+
* tok = argmax(step_logits)
|
|
670
|
+
* prev = tok
|
|
671
|
+
*
|
|
672
|
+
* Transcribed confidence truncation (draft_ops.py _confident_prefix_length):
|
|
673
|
+
* if threshold <= 0: return block_size # disabled — full γ
|
|
674
|
+
* below = sigmoid(confidence_logits) < threshold
|
|
675
|
+
* if not below.any(): return block_size
|
|
676
|
+
* return first index where below is True # ℓ can be 0 (EMPTY proposal)
|
|
677
|
+
*
|
|
678
|
+
* Here the graph and the sequential proposal head run at the active row
|
|
679
|
+
* count, one block per anchor (the just-verified or bonus token starting
|
|
680
|
+
* it); confidence selects each row's length after the full device chain.
|
|
681
|
+
* `context` reads the rows' cached context K/V (projectContextKVRows; the
|
|
682
|
+
* caller owns its lifetime and the crop after the round); `position` is
|
|
683
|
+
* each block's first absolute position.
|
|
684
|
+
*/
|
|
685
|
+
draftRows(context: DeepspecContextAttention, anchors: readonly number[], position: number | MlxArray,
|
|
686
|
+
collectLogits = false): DeepspecDraftRows {
|
|
687
|
+
const B = anchors.length, G = this.gamma, V = this.cfg.vocab_size;
|
|
688
|
+
using ids = ops.fromInt32(anchors.flatMap(anchor => [anchor, ...Array(G - 1).fill(this.cfg.mask_token_id)]), [B, G]);
|
|
689
|
+
using hidden = this.#forwardBackbone(context, ids, position);
|
|
690
|
+
using base = this.#computeLogits(hidden);
|
|
691
|
+
using anchorIds = ops.fromInt32([...anchors], [B]);
|
|
692
|
+
const sampled: MlxArray[] = [], confidence: MlxArray[] = [];
|
|
693
|
+
let previous = anchorIds;
|
|
694
|
+
try {
|
|
695
|
+
for (let step = 0; step < G; step++) {
|
|
696
|
+
using row = base.slice([0, step, 0], [B, step + 1, V]);
|
|
697
|
+
using logits = ops.reshape(row, [B, V]);
|
|
698
|
+
const token = this.#selectStep(logits, previous);
|
|
699
|
+
sampled.push(token); previous = token;
|
|
700
|
+
}
|
|
701
|
+
// Serving does not consume confidence when truncation is disabled.
|
|
702
|
+
if (this.#confProj && (collectLogits || this.cfg.confidence_threshold > 0)) for (let step = 0; step < G; step++) {
|
|
703
|
+
using row = hidden.slice([0, step, 0], [B, step + 1, this.hidden]);
|
|
704
|
+
using flat = ops.reshape(row, [B, this.hidden]);
|
|
705
|
+
confidence.push(this.#confidence(flat, step ? sampled[step - 1]! : anchorIds));
|
|
706
|
+
}
|
|
707
|
+
using packed = ops.concatAxis(sampled, 0);
|
|
708
|
+
const tokens = packed.toIntTokens();
|
|
709
|
+
using packedConfidence = confidence.length ? ops.concatAxis(confidence, 0) : null;
|
|
710
|
+
const conf = packedConfidence?.toFloat32();
|
|
711
|
+
const rows = anchors.map((_, row) => {
|
|
712
|
+
const values = conf ? Array.from({ length: G }, (_, step) => conf[step * B + row]!) : [];
|
|
713
|
+
const below = this.cfg.confidence_threshold > 0 ? values.findIndex(value => value < this.cfg.confidence_threshold) : -1;
|
|
714
|
+
const length = below < 0 ? G : below;
|
|
715
|
+
return { tokens: Array.from({ length }, (_, step) => tokens[step * B + row]!), conf: values.slice(0, length) };
|
|
716
|
+
});
|
|
717
|
+
return { tokens: rows.map(row => row.tokens), conf: rows.map(row => row.conf),
|
|
718
|
+
...(collectLogits ? { baseLogits: base.astype(Dtype.float32) } : {}) };
|
|
719
|
+
} finally { for (const array of [...sampled, ...confidence]) array.dispose(); }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
dispose(): void {
|
|
723
|
+
disposeW(this.#embed);
|
|
724
|
+
disposeW(this.#fc);
|
|
725
|
+
this.#hiddenNorm.dispose();
|
|
726
|
+
this.#norm.dispose();
|
|
727
|
+
disposeW(this.#lmHead);
|
|
728
|
+
this.ropeFreqs.dispose();
|
|
729
|
+
for (const l of this.#layers) {
|
|
730
|
+
disposeW(l.qProj); disposeW(l.kProj); disposeW(l.oProj);
|
|
731
|
+
l.qNorm.dispose(); l.kNorm.dispose();
|
|
732
|
+
l.inputNorm.dispose(); l.postAttnNorm.dispose();
|
|
733
|
+
l.preFfNorm.dispose(); l.postFfNorm.dispose();
|
|
734
|
+
disposeW(l.gateProj); disposeW(l.upProj); disposeW(l.downProj);
|
|
735
|
+
l.layerScalar.dispose();
|
|
736
|
+
}
|
|
737
|
+
disposeW(this.#markovW1);
|
|
738
|
+
disposeW(this.#markovW2);
|
|
739
|
+
disposeW(this.#confProj);
|
|
740
|
+
this.#confB?.dispose();
|
|
741
|
+
this.#w.dispose();
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|