@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,75 @@
|
|
|
1
|
+
import { runtimeConfig, withRuntimeConfig, type RuntimeConfig } from "../runtime/config";
|
|
2
|
+
import { snapshotGenerationPolicy } from "./request-policy";
|
|
3
|
+
import type { GenerationOutput, InferenceMethod, MethodResult } from "../contracts/portable/generation";
|
|
4
|
+
import { throwIfCancelled } from "./cancellation";
|
|
5
|
+
import { generateAutoregressive, generateDenoising, type GenerateOptions, type GenerateStats } from "../generation/index";
|
|
6
|
+
import type { MlxAutoregressiveBinding } from "../generation/bindings/autoregressive";
|
|
7
|
+
import type { MlxDenoisingBinding } from "../generation/bindings/denoising";
|
|
8
|
+
|
|
9
|
+
/** The native algorithm owns cleanup in its finally. This host adapter owns
|
|
10
|
+
* cancellation subscriptions and waits for the algorithm before closing. */
|
|
11
|
+
function nativeMethod<Metrics>(
|
|
12
|
+
id: string,
|
|
13
|
+
execute: (output: GenerationOutput, signal: AbortSignal) => Promise<MethodResult<Metrics>>,
|
|
14
|
+
runtime: RuntimeConfig,
|
|
15
|
+
): InferenceMethod<Metrics> {
|
|
16
|
+
return {
|
|
17
|
+
id,
|
|
18
|
+
async createRun(cancellation) {
|
|
19
|
+
throwIfCancelled(cancellation);
|
|
20
|
+
const abort = new AbortController();
|
|
21
|
+
const unsubscribe = cancellation.subscribe((reason) => abort.abort(
|
|
22
|
+
new DOMException(`generation cancelled: ${reason}`, "AbortError"),
|
|
23
|
+
));
|
|
24
|
+
let work: Promise<MethodResult<Metrics>> | undefined;
|
|
25
|
+
let closing: Promise<void> | undefined;
|
|
26
|
+
return {
|
|
27
|
+
execute(output) {
|
|
28
|
+
if (work || closing) return Promise.reject(new Error("method run can execute only once"));
|
|
29
|
+
work = withRuntimeConfig(runtime, () => execute(output, abort.signal));
|
|
30
|
+
return work;
|
|
31
|
+
},
|
|
32
|
+
close() {
|
|
33
|
+
return closing ??= (async () => {
|
|
34
|
+
abort.abort(new DOMException("method closed", "AbortError"));
|
|
35
|
+
try { await work; } catch { /* execute owns the algorithm's error */ }
|
|
36
|
+
finally { unsubscribe(); }
|
|
37
|
+
})();
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Each plan supplies its prepared per-run resources. Caches/media in options
|
|
45
|
+
* retain the same ownership contract as generateAutoregressive. */
|
|
46
|
+
export function createAutoregressiveMethod(
|
|
47
|
+
binding: MlxAutoregressiveBinding, promptIds: readonly number[], options: GenerateOptions,
|
|
48
|
+
): InferenceMethod<GenerateStats> {
|
|
49
|
+
const prompt = [...promptIds];
|
|
50
|
+
options = snapshotGenerationPolicy(options);
|
|
51
|
+
return nativeMethod("mlx-autoregressive", async (output, signal) => {
|
|
52
|
+
const generation = generateAutoregressive(binding, prompt, { ...options, signal });
|
|
53
|
+
for await (const item of generation)
|
|
54
|
+
if (await output.commit([item.token], item.logprobs ? [item.logprobs] : undefined) === false) break;
|
|
55
|
+
const metrics = generation.stats;
|
|
56
|
+
if (!metrics) throw new Error("AR method did not settle its metrics");
|
|
57
|
+
return { finishReason: metrics.finishReason ?? (metrics.generatedTokens >= (options.maxTokens ?? 512) ? "length" : "stop"), metrics };
|
|
58
|
+
}, binding.runtime ?? runtimeConfig());
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The canvas stays private. This method publishes only the finished result. */
|
|
62
|
+
export function createDenoisingMethod<State>(
|
|
63
|
+
binding: MlxDenoisingBinding<State>, promptIds: readonly number[], options: GenerateOptions,
|
|
64
|
+
): InferenceMethod<GenerateStats> {
|
|
65
|
+
const prompt = [...promptIds];
|
|
66
|
+
options = snapshotGenerationPolicy(options);
|
|
67
|
+
return nativeMethod("mlx-denoising", async (output, signal) => {
|
|
68
|
+
const generation = generateDenoising(binding, prompt, { ...options, signal });
|
|
69
|
+
for await (const item of generation)
|
|
70
|
+
if (await output.commit([item.token]) === false) break;
|
|
71
|
+
const metrics = generation.stats;
|
|
72
|
+
if (!metrics) throw new Error("denoising method did not settle its metrics");
|
|
73
|
+
return { finishReason: metrics.generatedTokens >= (options.maxTokens ?? 256) ? "length" : "stop", metrics };
|
|
74
|
+
}, binding.runtime ?? runtimeConfig());
|
|
75
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { MlxArray } from "@mlx-bun/mlx/array";
|
|
2
|
+
import type { MlxPhaseGroup, MlxMixedRange, MlxSeparateMixed } from "../contracts/mlx/graph";
|
|
3
|
+
import type { MlxForwardStep, MlxForwardWork } from "../contracts/mlx/forward-work";
|
|
4
|
+
|
|
5
|
+
/** Join two method-owned work producers at their forward boundary: the first
|
|
6
|
+
* forward preparation offers and the first forward decode makes run as one
|
|
7
|
+
* mixed forward (`mixed`, the composition's), each group in its own phase;
|
|
8
|
+
* every other forward runs on its own (`step.own`). Decode finishes
|
|
9
|
+
* sampling/publication/retirement before preparation can join rows. The model
|
|
10
|
+
* owns packing; this coordinator never merges caches or samples. A
|
|
11
|
+
* restored/cancelled preparation need not produce a forward at all. */
|
|
12
|
+
export async function runMixedTokenIteration(options: {
|
|
13
|
+
prepare(forward: MlxForwardWork): Promise<void>;
|
|
14
|
+
decode(forward: MlxForwardWork): Promise<void>;
|
|
15
|
+
mixed(groups: readonly MlxPhaseGroup[], rows: number): MlxArray[];
|
|
16
|
+
}): Promise<boolean> {
|
|
17
|
+
let notify!: () => void;
|
|
18
|
+
const offered = new Promise<void>(resolve => { notify = resolve; });
|
|
19
|
+
let pending: { group: MlxPhaseGroup; step: MlxForwardStep; resolve(hidden: MlxArray): void; reject(error: unknown): void } | undefined;
|
|
20
|
+
let captured = false;
|
|
21
|
+
let preparationError: unknown;
|
|
22
|
+
let preparationFailed = false;
|
|
23
|
+
const groupOf = (ids: MlxArray, state: MlxPhaseGroup["state"], step: MlxForwardStep): MlxPhaseGroup =>
|
|
24
|
+
({ phase: step.phase, rows: step.rows, ids, state, capture: step.capture });
|
|
25
|
+
const preparing = options.prepare(async (ids, cache, step) => {
|
|
26
|
+
if (captured) return step.own();
|
|
27
|
+
captured = true;
|
|
28
|
+
return new Promise<MlxArray>((resolve, reject) => {
|
|
29
|
+
pending = { group: groupOf(ids, cache, step), step, resolve, reject }; notify();
|
|
30
|
+
});
|
|
31
|
+
}).catch(error => { preparationFailed = true; preparationError = error; }).finally(notify);
|
|
32
|
+
await offered;
|
|
33
|
+
if (!pending) {
|
|
34
|
+
await preparing;
|
|
35
|
+
if (preparationFailed) throw preparationError;
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
const held = pending;
|
|
39
|
+
let preparedHidden: MlxArray | undefined;
|
|
40
|
+
let mixed = false;
|
|
41
|
+
try {
|
|
42
|
+
await options.decode(async (ids, cache, step) => {
|
|
43
|
+
if (mixed) return step.own();
|
|
44
|
+
const outputs = options.mixed([groupOf(ids, cache, step), held.group], step.rows + held.step.rows);
|
|
45
|
+
mixed = true; preparedHidden = outputs[1]!;
|
|
46
|
+
return outputs[0]!;
|
|
47
|
+
});
|
|
48
|
+
// A final unread token can retire decode without another model call.
|
|
49
|
+
preparedHidden ??= await held.step.own();
|
|
50
|
+
held.resolve(preparedHidden); preparedHidden = undefined;
|
|
51
|
+
await preparing;
|
|
52
|
+
if (preparationFailed) throw preparationError;
|
|
53
|
+
return true;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
preparedHidden?.dispose(); held.reject(error);
|
|
56
|
+
await preparing;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export { type MlxForwardWork, type MlxPreparationWork } from "../contracts/mlx/forward-work";
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
/** The scheduler routes declared packed work and preserves each separate group's geometry. */
|
|
65
|
+
export function dispatchMixedGroups(groups: readonly MlxPhaseGroup[], rows: number,
|
|
66
|
+
packed: readonly MlxMixedRange[], separate?: MlxSeparateMixed): MlxArray[] {
|
|
67
|
+
const packedOperation = (ranges: readonly MlxMixedRange[], packedRows: number) => {
|
|
68
|
+
const operation = ranges.find(range => packedRows >= range.from && packedRows <= range.to
|
|
69
|
+
&& rows >= (range.totalFrom ?? 1) && rows <= (range.totalTo ?? Infinity))?.operation;
|
|
70
|
+
if (!operation) throw new Error(`graph has no mixed operation for ${packedRows} packed rows (${rows} total rows)`);
|
|
71
|
+
return operation;
|
|
72
|
+
};
|
|
73
|
+
if (!separate || (packed.length > 0 && !groups.some(group => group.phase === "verify")))
|
|
74
|
+
return packedOperation(packed, rows)(groups, rows);
|
|
75
|
+
const outputs: Array<MlxArray | undefined> = Array(groups.length);
|
|
76
|
+
try {
|
|
77
|
+
const candidates = separate.packed?.length
|
|
78
|
+
? groups.flatMap((group, index) => group.phase !== "verify" ? [index] : []) : [];
|
|
79
|
+
if (candidates.length > 1) {
|
|
80
|
+
const joined = candidates.map(index => groups[index]!);
|
|
81
|
+
const packedRows = joined.reduce((sum, group) => sum + group.rows, 0);
|
|
82
|
+
const returned = packedOperation(separate.packed!, packedRows)(joined, rows);
|
|
83
|
+
for (const [position, index] of candidates.entries()) outputs[index] = returned[position]!;
|
|
84
|
+
}
|
|
85
|
+
for (const [index, group] of groups.entries()) {
|
|
86
|
+
if (outputs[index]) continue;
|
|
87
|
+
const operation = separate[group.phase].find(range => group.rows >= range.from && group.rows <= range.to)?.operation;
|
|
88
|
+
if (!operation) throw new Error(`graph has no separate ${group.phase} operation for ${group.rows} rows`);
|
|
89
|
+
outputs[index] = operation(group);
|
|
90
|
+
}
|
|
91
|
+
return outputs as MlxArray[];
|
|
92
|
+
} catch (error) {
|
|
93
|
+
for (const output of outputs) output?.dispose();
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { ExecutionCapabilities, ExecutionFeatures, ExecutionReason, ExecutionRequirements, ResolvedExecution } from "../contracts/portable/execution";
|
|
2
|
+
|
|
3
|
+
/** Select the request method, then place it using executor capabilities. The
|
|
4
|
+
* composition's caches serve every method; nothing here reads how they store
|
|
5
|
+
* keys and values. */
|
|
6
|
+
export function resolveExecution(
|
|
7
|
+
request: ExecutionRequirements, capabilities: ExecutionCapabilities,
|
|
8
|
+
features: ExecutionFeatures = { fill: false },
|
|
9
|
+
): ResolvedExecution {
|
|
10
|
+
const reasons: ExecutionReason[] = [];
|
|
11
|
+
const sharedRequestExclusions = [
|
|
12
|
+
[request.hasVision && !capabilities.mediaBatch, "media-batch-unsupported"],
|
|
13
|
+
[request.hasGrammar && !capabilities.grammarBatch, "grammar-batch-unsupported"],
|
|
14
|
+
] as const;
|
|
15
|
+
const excluded = sharedRequestExclusions.some(([exclusion]) => exclusion);
|
|
16
|
+
const sharedAdapterMethod = capabilities.sharedSpeculativeAdapters === true && !excluded &&
|
|
17
|
+
capabilities.groupedMethods?.includes("speculative") === true;
|
|
18
|
+
const grammarProposals = features.grammarJump === true && request.hasGrammar && !request.hasDraft && !request.hasVision &&
|
|
19
|
+
(!request.wantsLogprobs || capabilities.speculativeLogprobs === true) && capabilities.method === "autoregressive" &&
|
|
20
|
+
capabilities.sharedGrammarProposals === true && capabilities.groupedMethods?.includes("speculative") === true &&
|
|
21
|
+
(!request.hasAdapters || sharedAdapterMethod) && !excluded;
|
|
22
|
+
const speculative = grammarProposals || (capabilities.method === "autoregressive" && request.hasDraft &&
|
|
23
|
+
!request.hasVision && (!request.hasAdapters || sharedAdapterMethod) &&
|
|
24
|
+
(!request.wantsLogprobs || capabilities.speculativeLogprobs === true));
|
|
25
|
+
const method = speculative ? "speculative" : capabilities.method;
|
|
26
|
+
// Token-level request features act on sampled tokens. A method that does not
|
|
27
|
+
// sample tokens refuses them instead of silently discarding them.
|
|
28
|
+
const tokenMethod = capabilities.method === "autoregressive";
|
|
29
|
+
const continuousExclusions = [
|
|
30
|
+
[!(capabilities.groupedMethods ?? ["autoregressive"]).includes(method), "method-batch-unsupported"],
|
|
31
|
+
[request.hasDraft && !tokenMethod, "draft-method-unsupported"],
|
|
32
|
+
[request.wantsLogprobs && !tokenMethod, "logprobs-method-unsupported"],
|
|
33
|
+
[request.hasRepetitionPenalty && !tokenMethod, "repetition-penalty-method-unsupported"],
|
|
34
|
+
[request.hasLogitsExtras && !tokenMethod, "logits-extras-method-unsupported"],
|
|
35
|
+
[features.fill && !tokenMethod, "fill-method-unsupported"],
|
|
36
|
+
...sharedRequestExclusions,
|
|
37
|
+
] as const;
|
|
38
|
+
for (const [exclusion, reason] of continuousExclusions) if (exclusion) reasons.push(reason);
|
|
39
|
+
const mechanism = reasons.length ? "unsupported" : "continuous";
|
|
40
|
+
if (request.hasDraft && !speculative && tokenMethod) reasons.push("draft-incompatible-with-request");
|
|
41
|
+
// Prefix reuse restores autoregressive token caches only.
|
|
42
|
+
const promptCache = method === "autoregressive" && (!request.hasVision ||
|
|
43
|
+
(mechanism === "continuous" && request.hasPreparedPrefixIdentity === true && capabilities.mediaPrefixCache === true));
|
|
44
|
+
const sharedFill = mechanism === "continuous" && capabilities.sharedFill === true;
|
|
45
|
+
const speculativeEcho = method === "speculative" && mechanism === "continuous" &&
|
|
46
|
+
capabilities.sharedSpeculativeEcho === true;
|
|
47
|
+
const fill = features.fill && !request.hasVision && !request.hasGrammar && !request.wantsLogprobs &&
|
|
48
|
+
(speculativeEcho || (method === "autoregressive" && sharedFill && !request.hasDraft));
|
|
49
|
+
if (features.fill && !fill && tokenMethod) reasons.push("fill-incompatible-with-request");
|
|
50
|
+
const checkpoint = capabilities.checkpoints && method === "autoregressive" && !request.hasVision &&
|
|
51
|
+
capabilities.sharedCheckpoints === true && promptCache && !request.hasGrammar &&
|
|
52
|
+
!features.fill && !request.wantsLogprobs;
|
|
53
|
+
const compiledDecode = features.compiledDecode === true && capabilities.compiledDecode === true &&
|
|
54
|
+
method === "autoregressive" && !request.hasAdapters && !(sharedFill && fill);
|
|
55
|
+
if (features.compiledDecode && !compiledDecode) reasons.push("compiled-decode-unavailable-for-request");
|
|
56
|
+
const directGrammarJump = features.grammarJump === true && request.hasGrammar &&
|
|
57
|
+
!request.wantsLogprobs && method === "autoregressive" && mechanism === "continuous" &&
|
|
58
|
+
capabilities.sharedGrammarJump === true;
|
|
59
|
+
const grammarJump = grammarProposals || directGrammarJump;
|
|
60
|
+
if (features.grammarJump && request.hasGrammar && !grammarJump)
|
|
61
|
+
reasons.push("grammar-jump-incompatible-with-request");
|
|
62
|
+
return Object.freeze({ method, mechanism, promptCache, checkpoint, fill,
|
|
63
|
+
compiledDecode, grammarJump,
|
|
64
|
+
reasons: Object.freeze(reasons) });
|
|
65
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import type { Cache } from "../contracts/mlx/cache";
|
|
2
|
+
import type { MlxArray } from "@mlx-bun/mlx/array";
|
|
3
|
+
import { nextPrefillStep, prefillPhase } from "../contracts/portable/prefill";
|
|
4
|
+
import { disposeResources, cleanupFailure } from "../runtime/resources";
|
|
5
|
+
import type { Row } from "./batch-types";
|
|
6
|
+
import type { KvMaintenance } from "../contracts/mlx/cache";
|
|
7
|
+
import type { ContinuationState, RequestStateCache } from "../state/cache-service";
|
|
8
|
+
import { MlxPrefillRows, type MlxPrefillForward, type MlxPrefillState } from "./prefill-rows";
|
|
9
|
+
|
|
10
|
+
import { promptWorkStep } from "../generation/phase-dispatch";
|
|
11
|
+
|
|
12
|
+
export interface PrefillState extends MlxPrefillState {
|
|
13
|
+
snapAt: number | null;
|
|
14
|
+
continuation?: ContinuationState;
|
|
15
|
+
closePrefill?: () => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface PrefillHost {
|
|
19
|
+
chunkSize: number;
|
|
20
|
+
tailSplit: boolean;
|
|
21
|
+
/** Each row's state comes from the cache service, and boundary snapshots return to it. */
|
|
22
|
+
cache: RequestStateCache;
|
|
23
|
+
maintain?: KvMaintenance;
|
|
24
|
+
/** One cohort forward of `ids` [sequences, tokens] in the phase its planner named. */
|
|
25
|
+
forward(ids: MlxArray, caches: Cache[], step: MlxPrefillForward): Promise<MlxArray>;
|
|
26
|
+
/** Target projection preserves the forward batch geometry before sampling. */
|
|
27
|
+
project(hidden: MlxArray, caches: Cache[], completed: readonly PrefillState[], step: MlxPrefillForward): MlxArray;
|
|
28
|
+
/** Borrows [1,1,V] logits; takes ownership of the completed request caches. */
|
|
29
|
+
complete(state: PrefillState, logits: MlxArray): Promise<void>;
|
|
30
|
+
resume?(state: PrefillState): Promise<void>;
|
|
31
|
+
reject(row: Row, error: unknown): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Ordinary sampling/cache policy over the shared target preparation driver. */
|
|
35
|
+
export class MlxPrefillCohort extends MlxPrefillRows<PrefillState> {
|
|
36
|
+
override get canAdmit(): boolean {
|
|
37
|
+
return super.canAdmit && this.supportsMixedWork;
|
|
38
|
+
}
|
|
39
|
+
get supportsMixedWork(): boolean { return !this.rows.some(row => row.req.promptInput); }
|
|
40
|
+
constructor(readonly host: PrefillHost) {
|
|
41
|
+
super({
|
|
42
|
+
codecs: host.cache.codecs, maintain: host.maintain,
|
|
43
|
+
open(row) {
|
|
44
|
+
let owned: { caches: Cache[]; retain?: () => void } | undefined;
|
|
45
|
+
let closeCache: (() => void) | undefined;
|
|
46
|
+
let closePrefill: (() => void) | undefined;
|
|
47
|
+
try {
|
|
48
|
+
closeCache = row.req.trace?.begin("cache.lookup_restore", { mechanism: "continuous" });
|
|
49
|
+
// The row's resumed generation, a reused prefix composed again as the
|
|
50
|
+
// graph's caches, or fresh state: each converts inside its own appends.
|
|
51
|
+
const acquired = owned = host.cache.acquire(row.req, row.cacheNamespace ?? "");
|
|
52
|
+
if (acquired.continuation)
|
|
53
|
+
return { row, solo: acquired.caches, pos: row.req.promptIds.length,
|
|
54
|
+
snapAt: null, continuation: acquired.continuation };
|
|
55
|
+
closeCache?.(); closeCache = undefined;
|
|
56
|
+
row.cachedTokens = acquired.reusedTokens;
|
|
57
|
+
const length = row.req.promptIds.length;
|
|
58
|
+
const boundary = Math.min(row.req.snapshotAt ?? length, length - 1);
|
|
59
|
+
const snapAt = host.cache.keeps(row.req) && boundary >= 256 && boundary > acquired.reusedTokens ? boundary : null;
|
|
60
|
+
closePrefill = row.req.trace?.begin("prefill.total", {
|
|
61
|
+
mechanism: "continuous", promptTokens: row.promptTokens, cachedTokens: row.cachedTokens,
|
|
62
|
+
});
|
|
63
|
+
return { row, solo: acquired.caches, pos: acquired.reusedTokens, retain: acquired.retain, snapAt, closePrefill };
|
|
64
|
+
} catch (error) {
|
|
65
|
+
return cleanupFailure(error, () => disposeResources([...(owned?.caches ?? []),
|
|
66
|
+
{ dispose: () => owned?.retain?.() }, { dispose: () => closePrefill?.() }]));
|
|
67
|
+
} finally { closeCache?.(); }
|
|
68
|
+
},
|
|
69
|
+
ready: state => !!state.continuation,
|
|
70
|
+
plan(state) {
|
|
71
|
+
if (state.row.req.promptInput) return { kind: "final", start: state.pos,
|
|
72
|
+
end: state.row.promptTokens, snapshot: false, batchYield: false, atomic: true,
|
|
73
|
+
phase: prefillPhase(state.pos, state.row.promptTokens, false) };
|
|
74
|
+
return nextPrefillStep({ length: state.row.promptTokens, position: state.pos,
|
|
75
|
+
chunkSize: state.row.req.prefillChunkSize ?? host.chunkSize,
|
|
76
|
+
tailSplit: host.tailSplit, snapshotAt: state.snapAt }); },
|
|
77
|
+
forward: (ids, caches, states, step, work) => states[0]?.row.req.promptInput
|
|
78
|
+
? Promise.resolve(states[0].row.req.promptInput.prefill(ids, caches, states[0].pos,
|
|
79
|
+
step.phase === "decode" ? "decode" : "tail", (step.tokens)))
|
|
80
|
+
: work ? work(ids, caches, promptWorkStep(step, null, () => host.forward(ids, caches, step))) : host.forward(ids, caches, step),
|
|
81
|
+
// A media prompt input returns its prompt's last position: one row per sequence to project.
|
|
82
|
+
project: (hidden, caches, completed, step) => host.project(hidden, caches, completed,
|
|
83
|
+
completed.some(state => state.row.req.promptInput) ? { ...step, tokens: 1 } : step),
|
|
84
|
+
complete: (state, logits) => state.continuation ? host.resume!(state) : host.complete(state, logits!), reject: host.reject.bind(host),
|
|
85
|
+
checkpoint(state, capture) {
|
|
86
|
+
let snapshot: Cache[] | undefined;
|
|
87
|
+
try {
|
|
88
|
+
snapshot = capture();
|
|
89
|
+
host.cache.publish(state.row.req, state.row.cacheNamespace ?? "", state.row.req.promptIds.slice(0, state.pos), { caches: snapshot });
|
|
90
|
+
snapshot = undefined;
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (snapshot) disposeResources(snapshot);
|
|
93
|
+
console.warn(`batch-lane boundary snapshot skipped: ${(error as Error).message}`);
|
|
94
|
+
}
|
|
95
|
+
state.snapAt = null;
|
|
96
|
+
},
|
|
97
|
+
close(state) { const close = state.closePrefill; state.closePrefill = undefined; close?.(); },
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import type { BatchableCache, Cache } from "../contracts/mlx/cache";
|
|
2
|
+
import type { MlxArray } from "@mlx-bun/mlx/array";
|
|
3
|
+
import * as ops from "@mlx-bun/mlx/ops";
|
|
4
|
+
import { clearCache } from "@mlx-bun/mlx/ffi";
|
|
5
|
+
import type { PrefillStep } from "../contracts/portable/prefill";
|
|
6
|
+
import type { MlxPromptStep } from "../generation/phase-dispatch";
|
|
7
|
+
import { cloneKvCaches } from "../state/persistence";
|
|
8
|
+
import { type CacheCodecProvider } from "../state/persistence-types";
|
|
9
|
+
import { disposeResources, cleanupFailure } from "../runtime/resources";
|
|
10
|
+
import type { MlxGroupPreparation, Row } from "./batch-types";
|
|
11
|
+
import { evalCacheState } from "../generation/prefill";
|
|
12
|
+
import { prefillCacheLayout } from "../state/layout";
|
|
13
|
+
import { MlxStateRows } from "../state/rows";
|
|
14
|
+
import type { P2RTracePhase, P2RTraceAttributes } from "../runtime/trace";
|
|
15
|
+
import type { MlxForwardWork, MlxPreparationWork } from "../contracts/mlx/forward-work";
|
|
16
|
+
import type { KvMaintenance } from "../contracts/mlx/cache";
|
|
17
|
+
|
|
18
|
+
// Shared work is recorded on every participating request. workId identifies
|
|
19
|
+
// duplicates when constructing a process timeline; row spans are not additive.
|
|
20
|
+
let nextWorkId = 0;
|
|
21
|
+
function traceRows(states: readonly MlxPrefillState[], phase: P2RTracePhase, attributes: P2RTraceAttributes) {
|
|
22
|
+
if (!states.some(state => state.row.req.trace)) return null;
|
|
23
|
+
const closes = states.map(state => state.row.req.trace?.begin(phase, attributes));
|
|
24
|
+
return { [Symbol.dispose]() { for (const close of closes) close?.(); } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface MlxPrefillStep extends PrefillStep {
|
|
28
|
+
/** A non-causal input cannot be split at a scheduler token budget.
|
|
29
|
+
* Its preparation must decline joins until this step completes. */
|
|
30
|
+
readonly atomic?: boolean;
|
|
31
|
+
/** Some methods maintain their final target chunk before sampling. */
|
|
32
|
+
readonly maintain?: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface MlxPrefillState {
|
|
36
|
+
row: Row;
|
|
37
|
+
solo: Cache[];
|
|
38
|
+
pos: number;
|
|
39
|
+
retain?: () => void;
|
|
40
|
+
planned?: MlxPrefillStep;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** One cohort forward: the rows' common phase and their positions per row. */
|
|
44
|
+
export type MlxPrefillForward = MlxPromptStep;
|
|
45
|
+
|
|
46
|
+
/** The method owns initialization, planning, companion state, snapshots and
|
|
47
|
+
* completion. This driver owns common target batching and work boundaries.
|
|
48
|
+
* Checkpoint factories return owned cache state; close/dispose are idempotent. */
|
|
49
|
+
export interface MlxPrefillRowsHost<State extends MlxPrefillState> {
|
|
50
|
+
/** The snapshot form of the composition's caches (the cache service's), for a single row's boundary snapshot. */
|
|
51
|
+
codecs?: CacheCodecProvider;
|
|
52
|
+
maintain?: KvMaintenance;
|
|
53
|
+
open(row: Row): State;
|
|
54
|
+
plan(state: State): MlxPrefillStep;
|
|
55
|
+
/** Already prepared state can complete without any target forward. */
|
|
56
|
+
ready?(state: State): boolean;
|
|
57
|
+
/** Run one cohort forward of `ids` [sequences, tokens] in `step.phase`. */
|
|
58
|
+
forward(ids: MlxArray, caches: Cache[], states: readonly State[], step: MlxPrefillForward,
|
|
59
|
+
work?: MlxForwardWork): Promise<MlxArray>;
|
|
60
|
+
/** Project the cohort forward `step` produced (its rows: sequences times tokens). */
|
|
61
|
+
project(hidden: MlxArray, caches: Cache[], completed: readonly State[], step: MlxPrefillForward): MlxArray | null;
|
|
62
|
+
/** Consume method context after target maintenance, before snapshots. */
|
|
63
|
+
afterForward?(ids: MlxArray, caches: Cache[], states: readonly State[], hidden: MlxArray): void | Promise<void>;
|
|
64
|
+
checkpoint(state: State, capture: () => Cache[], row: number): void;
|
|
65
|
+
complete(state: State, logits: MlxArray | null, row: number): Promise<void>;
|
|
66
|
+
reject(row: Row, error: unknown): void;
|
|
67
|
+
close(state: State): void;
|
|
68
|
+
filterRows?(keep: readonly number[]): void;
|
|
69
|
+
dispose?(): void;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** One target preparation lifecycle at B1/B>1. Late joins retain each row's
|
|
73
|
+
* planned chunk endpoint, precision transition and checkpoint boundary. */
|
|
74
|
+
export class MlxPrefillRows<State extends MlxPrefillState> implements MlxGroupPreparation {
|
|
75
|
+
#states: State[] = [];
|
|
76
|
+
#rows: Row[] = [];
|
|
77
|
+
#stateRows?: MlxStateRows;
|
|
78
|
+
constructor(readonly operations: MlxPrefillRowsHost<State>) {}
|
|
79
|
+
get rows(): readonly Row[] { return this.#rows; }
|
|
80
|
+
get canAdmit(): boolean { return this.#rows.length > 0; }
|
|
81
|
+
/** Keep a request's prefill weight until retirement so a nearly completed
|
|
82
|
+
* request does not repeatedly attract another long prefill into its tail. */
|
|
83
|
+
get tokenWeight(): number { return this.#states.reduce((sum, state) => sum + state.row.promptTokens - state.row.cachedTokens, 0); }
|
|
84
|
+
|
|
85
|
+
admit(row: Row): void {
|
|
86
|
+
this.#states.push(this.operations.open(row));
|
|
87
|
+
this.#rows.push(row);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#release(state: State): void {
|
|
91
|
+
const caches = state.solo; state.solo = [];
|
|
92
|
+
const retain = state.retain; state.retain = undefined;
|
|
93
|
+
disposeResources([...caches, { dispose: () => retain?.() }, { dispose: () => this.operations.close(state) }]);
|
|
94
|
+
}
|
|
95
|
+
#filter(keep: number[]): void {
|
|
96
|
+
if (keep.length) this.#stateRows?.filterRows(keep);
|
|
97
|
+
else { const rows = this.#stateRows; this.#stateRows = undefined; rows?.dispose(); }
|
|
98
|
+
this.operations.filterRows?.(keep);
|
|
99
|
+
this.#states = keep.map(row => this.#states[row]!);
|
|
100
|
+
this.#rows = keep.map(row => this.#rows[row]!);
|
|
101
|
+
}
|
|
102
|
+
/** Admission changes membership only between forwards. Existing planned
|
|
103
|
+
* endpoints survive a join, including partially consumed drain chunks. */
|
|
104
|
+
#synchronizeRows(): void {
|
|
105
|
+
if (!this.#stateRows && this.#states.length === 1) return;
|
|
106
|
+
if (!this.#stateRows) {
|
|
107
|
+
for (const state of this.#states) this.operations.maintain?.preparePrefill?.(state.solo);
|
|
108
|
+
const layouts: BatchableCache[] = [];
|
|
109
|
+
try { for (const cache of this.#states[0]!.solo) layouts.push(prefillCacheLayout(cache)); }
|
|
110
|
+
catch (error) { return cleanupFailure(error, () => disposeResources(layouts)); }
|
|
111
|
+
this.#stateRows = new MlxStateRows(layouts);
|
|
112
|
+
this.#stateRows.mergeRows(this.#states.map(state => state.solo));
|
|
113
|
+
} else {
|
|
114
|
+
for (const state of this.#states.slice(this.#stateRows.rowCount)) {
|
|
115
|
+
this.operations.maintain?.preparePrefill?.(state.solo);
|
|
116
|
+
this.#stateRows.append(state.solo);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// Resolve input-backed copies before releasing SSD restore leases.
|
|
120
|
+
if (this.#states.some(state => state.solo.length)) {
|
|
121
|
+
evalCacheState(this.#stateRows.caches);
|
|
122
|
+
for (const state of this.#states) {
|
|
123
|
+
const caches = state.solo; state.solo = [];
|
|
124
|
+
const retain = state.retain; state.retain = undefined;
|
|
125
|
+
disposeResources([...caches, { dispose: () => retain?.() }]);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
for (const cache of this.#stateRows.caches) cache.prefillMaintenance?.beginPrefill();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async advance(workLimit?: MlxPreparationWork): Promise<boolean> {
|
|
132
|
+
let remaining = workLimit?.maxTokens ?? Infinity;
|
|
133
|
+
// Complete restored inputs before merging: their cache coverage must not
|
|
134
|
+
// introduce padding or a zero-width forward into unrelated cold rows.
|
|
135
|
+
if (this.operations.ready && this.#states.some(state => this.operations.ready!(state))) {
|
|
136
|
+
const remaining: State[] = [];
|
|
137
|
+
for (const state of this.#states) {
|
|
138
|
+
if (!this.operations.ready(state)) { remaining.push(state); continue; }
|
|
139
|
+
try {
|
|
140
|
+
state.row.req.signal?.throwIfAborted();
|
|
141
|
+
await this.operations.complete(state, null, -1);
|
|
142
|
+
state.solo = []; state.retain = undefined;
|
|
143
|
+
} catch (error) { this.operations.reject(state.row, error); this.#release(state); }
|
|
144
|
+
finally { this.operations.close(state); }
|
|
145
|
+
}
|
|
146
|
+
this.#states = remaining; this.#rows = remaining.map(state => state.row);
|
|
147
|
+
if (!remaining.length) { this.dispose(); return true; }
|
|
148
|
+
}
|
|
149
|
+
{
|
|
150
|
+
using span = traceRows(this.#states, "prefill.row_sync", { workId: ++nextWorkId, batchSize: this.#states.length });
|
|
151
|
+
this.#synchronizeRows();
|
|
152
|
+
}
|
|
153
|
+
const keep: number[] = [];
|
|
154
|
+
for (const [index, state] of this.#states.entries()) {
|
|
155
|
+
if (!state.row.req.signal?.aborted) { keep.push(index); continue; }
|
|
156
|
+
this.#release(state); this.operations.reject(state.row, state.row.req.signal.reason);
|
|
157
|
+
}
|
|
158
|
+
if (keep.length !== this.#states.length) this.#filter(keep);
|
|
159
|
+
if (!this.#states.length) { this.dispose(); return true; }
|
|
160
|
+
while (this.#states.length) {
|
|
161
|
+
for (const state of this.#states) state.planned ??= this.operations.plan(state);
|
|
162
|
+
const count = Math.min(this.#states.some(state => state.planned!.atomic) ? Infinity
|
|
163
|
+
: Math.max(1, Math.floor(remaining / this.#states.length)),
|
|
164
|
+
...this.#states.map(state => state.planned!.end - state.pos));
|
|
165
|
+
// A planned step stays the unit of maintenance: a row whose step is longer
|
|
166
|
+
// than this forward (a sibling's step is shorter, or the budget is) runs
|
|
167
|
+
// `count` of its positions now and is maintained at the step's planned end,
|
|
168
|
+
// so its caches convert where its own plan put the boundary, whatever rows
|
|
169
|
+
// it shares the forward with. Only every row's whole planned chunk is a
|
|
170
|
+
// chunk forward; any other piece of more than one position is a tail.
|
|
171
|
+
const whole = this.#states.every(state => state.planned!.phase === "chunk" &&
|
|
172
|
+
state.pos === state.planned!.start && state.pos + count === state.planned!.end);
|
|
173
|
+
const step: MlxPrefillForward = { sequences: this.#states.length, tokens: count,
|
|
174
|
+
phase: count === 1 ? "decode" : whole ? "chunk" : "tail" };
|
|
175
|
+
const work = { workId: ++nextWorkId, batchSize: this.#states.length, tokensPerRow: count };
|
|
176
|
+
const closes = this.#states.map(state => state.row.req.trace?.begin("prefill.chunk", {
|
|
177
|
+
mechanism: "continuous", startToken: state.pos, ...work,
|
|
178
|
+
}));
|
|
179
|
+
const caches = this.#stateRows?.caches ?? this.#states[0]!.solo;
|
|
180
|
+
try {
|
|
181
|
+
using ids = count ? ops.fromInt32(this.#states.flatMap(state => state.row.req.promptIds.slice(state.pos, state.pos + count)),
|
|
182
|
+
[this.#states.length, count]) : null;
|
|
183
|
+
let forwarded: MlxArray | null;
|
|
184
|
+
{
|
|
185
|
+
using span = traceRows(this.#states, "prefill.forward", work);
|
|
186
|
+
forwarded = ids ? await this.operations.forward(ids, caches, this.#states, step, workLimit?.forward) : null;
|
|
187
|
+
}
|
|
188
|
+
using hidden = forwarded;
|
|
189
|
+
const drains: number[] = [], finals: number[] = [];
|
|
190
|
+
let batchYield = false;
|
|
191
|
+
for (const [row, state] of this.#states.entries()) {
|
|
192
|
+
state.pos += count;
|
|
193
|
+
if (state.pos !== state.planned!.end) continue;
|
|
194
|
+
if (state.planned!.kind === "final") finals.push(row);
|
|
195
|
+
else drains.push(row);
|
|
196
|
+
batchYield ||= state.planned!.batchYield;
|
|
197
|
+
}
|
|
198
|
+
const maintained = [...drains, ...finals.filter(row => this.#states[row]!.planned!.maintain)];
|
|
199
|
+
if (count && (maintained.length || !finals.length)) {
|
|
200
|
+
{
|
|
201
|
+
using span = traceRows(this.#states, "prefill.evaluate", work);
|
|
202
|
+
evalCacheState(caches);
|
|
203
|
+
}
|
|
204
|
+
using span = traceRows(this.#states, "prefill.kv_maintenance", work);
|
|
205
|
+
// Cohort rows convert at their planned boundaries; a single row's
|
|
206
|
+
// composed caches converted inside their own appends.
|
|
207
|
+
if (this.#stateRows) for (const cache of caches) cache.prefillMaintenance?.commitPrefill(maintained);
|
|
208
|
+
// A scheduler budget can split one planned chunk into many pieces.
|
|
209
|
+
// Resolve state at each yield, but retain allocator reuse until the
|
|
210
|
+
// method's maintenance boundary instead of purging it every piece.
|
|
211
|
+
if (maintained.length) clearCache();
|
|
212
|
+
}
|
|
213
|
+
if (ids && this.operations.afterForward) {
|
|
214
|
+
using span = traceRows(this.#states, "prefill.companion", work);
|
|
215
|
+
const companion = this.operations.afterForward?.(ids, caches, this.#states, hidden!);
|
|
216
|
+
if (companion) await companion;
|
|
217
|
+
}
|
|
218
|
+
for (const row of [...drains, ...finals]) {
|
|
219
|
+
const state = this.#states[row]!;
|
|
220
|
+
if (state.planned!.snapshot) {
|
|
221
|
+
using span = traceRows([state], "prefill.checkpoint", { ...work, row });
|
|
222
|
+
this.operations.checkpoint(state, () =>
|
|
223
|
+
this.#stateRows ? this.#stateRows.extractRow(row) : cloneKvCaches(state.solo, this.operations.codecs), row);
|
|
224
|
+
}
|
|
225
|
+
if (!finals.includes(row)) state.planned = undefined;
|
|
226
|
+
}
|
|
227
|
+
let projected: MlxArray | null = null;
|
|
228
|
+
if (hidden && finals.length) {
|
|
229
|
+
using span = traceRows(this.#states, "prefill.project", work);
|
|
230
|
+
projected = this.operations.project(hidden, caches, finals.map(row => this.#states[row]!), step);
|
|
231
|
+
}
|
|
232
|
+
using logits = projected;
|
|
233
|
+
for (const row of finals) {
|
|
234
|
+
const state = this.#states[row]!;
|
|
235
|
+
using span = traceRows([state], "prefill.complete", { ...work, row });
|
|
236
|
+
if (this.#stateRows) state.solo = this.#stateRows.extractRow(row);
|
|
237
|
+
using part = logits ? logits.slice([row, logits.shape[1]! - 1, 0], [row + 1, logits.shape[1]!, logits.shape[2]!]) : null;
|
|
238
|
+
try {
|
|
239
|
+
state.row.req.signal?.throwIfAborted();
|
|
240
|
+
await this.operations.complete(state, part, row);
|
|
241
|
+
state.solo = []; state.retain = undefined;
|
|
242
|
+
} catch (error) {
|
|
243
|
+
this.operations.reject(state.row, error);
|
|
244
|
+
this.#release(state);
|
|
245
|
+
} finally { this.operations.close(state); }
|
|
246
|
+
}
|
|
247
|
+
for (const cache of caches) (cache as { releaseRopeArr?: () => void }).releaseRopeArr?.();
|
|
248
|
+
if (finals.length) this.#filter(this.#states.flatMap((_, row) => finals.includes(row) ? [] : [row]));
|
|
249
|
+
if (!this.#states.length) { this.dispose(); return true; }
|
|
250
|
+
remaining -= count * work.batchSize;
|
|
251
|
+
if (batchYield || finals.length || remaining < this.#states.length) return false;
|
|
252
|
+
} finally { for (const close of closes) close?.(); }
|
|
253
|
+
}
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
dispose(): void {
|
|
258
|
+
const states = this.#states; this.#states = []; this.#rows = [];
|
|
259
|
+
const rows = this.#stateRows; this.#stateRows = undefined;
|
|
260
|
+
disposeResources([...(rows ? [rows] : []), ...states.map(state => ({ dispose: () => this.#release(state) })),
|
|
261
|
+
{ dispose: () => this.operations.dispose?.() }]);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { GenerateOptions } from "../generation/index";
|
|
2
|
+
|
|
3
|
+
/** Copy policy data without cloning native caches, controllers or callbacks. */
|
|
4
|
+
export function snapshotGenerationPolicy<T extends GenerateOptions & { stopSequences?: readonly string[] }>(options: T): T {
|
|
5
|
+
const snapshot = { ...options };
|
|
6
|
+
const freeze = (value: unknown): void => {
|
|
7
|
+
if (!value || typeof value !== "object") return;
|
|
8
|
+
for (const item of Object.values(value)) freeze(item);
|
|
9
|
+
Object.freeze(value);
|
|
10
|
+
};
|
|
11
|
+
for (const key of ["stopSequences", "eosTokenIds", "adapters", "xtcSpecialTokens", "logitBias",
|
|
12
|
+
"hlg", "curve", "decodePolicy"] as const) {
|
|
13
|
+
if (snapshot[key] === undefined) continue;
|
|
14
|
+
const value = structuredClone(snapshot[key]);
|
|
15
|
+
freeze(value);
|
|
16
|
+
Object.assign(snapshot, { [key]: value });
|
|
17
|
+
}
|
|
18
|
+
return Object.freeze(snapshot);
|
|
19
|
+
}
|