Repository navigation
Conversation
…reader quantised path Closes the `--kv affine*` `StandardKVCache` fallback that Gemma 4 LLM (E2B / E4B) was routing through on KV-sharing donor layers. Donors now stay `AffineQuantizedKVCache` and their readers consume the donor's quantised `(packed, scales, biases)` tuple via `quantizedScaledDotProductAttention` — the discrete-path qSDPA that already supports sinks (PR #210). Trade-off: discrete path materialises the [B, nKVH, nRep, L, T] score matrix during the second matmul. Spec 041 phase 1 (the flash quantised SDPA kernel) will swap the call out without changing the reader API, recovering the score-tensor memory the same way `MLXFast.scaledDotProductAttention` does for FP16 K/V today. ## Changes - `Gemma4TextAttention.callAsFunction(useSharedKV:...)` gains `quantizedSharedKVArrays` / `quantizedSharedKVConfig` parameters. When set, takes precedence over the existing FP16 `sharedKVArrays` branch and routes through `quantizedScaledDotProductAttention`. - `Gemma4ModelInner.callAsFunction` populates a parallel `intermediateQuantizedKVs` array — when the donor cache is `AffineQuantizedKVCache`, we grab `getQuantizedState()` after the donor's `attentionWithCacheUpdate` runs and hand it to the reader. - `Gemma4Model.newCache(...)` flips its callers' `forceRawKV` flag to `false` — the donor path no longer needs the `StandardKVCache` fallback under affine. - `makeAttentionCache(...)`'s `forceRawKV` flag is now a "caller's contract": "my reader can / cannot consume quantised donor state." Gemma 4 LLM (this PR) sets `false`; Gemma 3n and Gemma 4 VLM still set `true` until their reader paths are similarly extended. ## Verification (M1 Max 64GB) Gemma 4 E2B affine4 summarization @ ctx=8192: | Metric | pass1 (alpha, pre-fixes) | this PR | |---|---:|---:| | Decode tok/s | 44.0 (gibberish) | 87.3 (coherent) | | Peak GPU | 9.62 GB | 5.47 GB | | KV cache | 48 MB | 26 MB | | Output | garbage | "This is a fascinating collection of excerpts, clearly drawn from Nick Carraway's perspective..." | Gemma 4 E4B affine4 + turbo4v2 summarization @ ctx=4096 — both coherent. Spec 041 doc updated: Phase 5 marked as shipped for Gemma 4 LLM; Gemma 3n / Gemma 4 VLM extension is a mechanical follow-up tracked alongside Phase 1. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 session evaluating a one-shot spec 040 implementation: - Couldn't ship Option 1 (kernel pair) without the Metal toolchain installed on this dev machine (`xcodebuild -downloadComponent MetalToolchain` required). - Sketched Option 2 in detail enough to surface a design tension: Mamba state replay needs both recurrent-state capture AND conv-state capture (`applyConv` cache slot 0) to support mid-window rollback; that's the part that pushes Option 2 past the spec's "cheap fallback" estimate. Both blockers captured at the top of the spec so the next attempt can plan around them. No code change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This was referenced May 13, 2026
ekryski
added a commit
that referenced
this pull request
May 14, 2026
… on spec 039 Updates phase statuses to reflect what landed in `feat(affine-sdpa): spec 041 phases 1+2+4`: - Phase 1: stop-gap shipped (dequant-then-MLXFastSDPA). Fused-kernel optimisation deferred to Phase 1.1. - Phase 2: shipped for free — `dequantized()` already covers 2/3/4/5/6/8 bit + mxfp4. - Phase 3: deferred. `compressedAttention(L>1)` never fires today (`attentionWithCacheUpdate` routes L>1 through raw FP16 prefix prefill); spec 039's compressed-prefix hydration is the gating piece. - Phase 4: shipped for free — MLXFast SDPA folds sinks natively in the flash path. Discrete path's explicit fold (PR #210) is retained as the L=1 fallback. - Phase 5: shipped via PR #211 (Gemma 4 LLM affine donor compression). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 14, 2026
…equant-then-SDPA (#212) * feat(affine-kv): attention-sink support in quantizedScaledDotProductAttention GPT-OSS-20B and MiMo (when attentionSinkBias is non-zero) under `--kv affine*` previously hit `fatalError("Affine quantized attention does not support non-zero sinks.")` and crashed the bench. The affine SDPA now folds sinks into its softmax denominator via a fused softmax-of-augmented-scores: M = max(max_t s_t, sink_h) p_t = exp(s_t - M) / (Σ_t exp(s_t - M) + exp(sink_h - M)) output_h = Σ_t p_t · V_t Implementation: append the per-head sink as a (T+1)th score column, run MLX's fused `softmax` over T+1, slice off the sink column on the way to the V matmul. The sink's V is implicit zero, so its softmax mass simply absorbs probability from the real-token columns and doesn't contribute to the output. Why softmax-of-augmented-scores instead of an explicit manual softmax (max → subtract → exp → sum-with-sink → divide): MLX's softmax is a single fused Metal op that doesn't materialize per-token exp / running sum intermediates. The naive manual version peaks at ~3 copies of the score tensor. Sink broadcasting: - GQA: scores [B, nKVH, nRep, L, T], sinks [nQH=nKVH·nRep] → reshape sinks to [1, nKVH, nRep, 1, 1]; broadcast to [B, nKVH, nRep, L, 1] for concat along T. - MHA: scores [B, nQH, L, T], sinks [nQH] → reshape sinks to [1, nQH, 1, 1]; broadcast to [B, nQH, L, 1]. Sinks are cast to `scores.dtype` before subtraction — bf16/fp16 end-to-end, matching the negative-infinity sentinel fix above. Plumbed through: - `quantizedScaledDotProductAttention` new optional `sinks:` parameter - `attentionWithCacheUpdate` removes the affine fatalError, passes `sinks` through. - `MiMoV2Flash`'s private `attentionWithCacheUpdateAndSinks` drops its matching precondition for the affine path. Four new regression tests cover: - sinks=-INF reduces to no-sinks output - finite sinks shrink output magnitude (sanity) - GQA broadcast (8Q × 2KV) with mixed -INF / finite sinks per-head - 8-bit affine SDPA-with-sinks tracks unquantized `MLXFast.scaledDotProductAttention(...sinks:)` within affine-quantization noise Verified end-to-end on GPT-OSS-20B 4bit at ctx=4096 simple and ctx=8192 summarization: coherent output, decode 60-72 tok/s vs 63.6 tok/s no-quant baseline. Peak GPU 20 GB at ctx=8192 reflects the affine path's intrinsic score-matrix materialisation cost, not the sinks fold (no-sinks affine on Qwen3.5-0.8B 8k = 2.71 GB; matches expected scaling). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(turbo-kv): retain-and-append in updateAndDequant for sliding-window correctness The α (dequant-first) rotating-buffer branch of `updateAndDequant` silently corrupted output on GPT-OSS-20B `--kv turbo4v2`. Two bugs in the same code path: 1. **Buffer size mismatch with `update()`.** Prefill goes through `update()`, which (post-PR #209) sizes the raw FP16 buffer at `bufferTokens + S` via retain-and-append. `updateAndDequant`'s rotating branch assumed the buffer was pre-allocated to `maxSz` and wrote at `[writePos:writePos+S]` where `writePos = rotatingIdx`. On the first decode call with `prevOffset=101`, `maxSz=128`, `rotatingIdx=101`, the slice assignment indexed past the end of the 101-token buffer. 2. **Slot-order vs time-order.** Even after fixing the size, the modular-rotation layout returned the buffer in slot-position order, not time order: after wrap, slot 0 holds the *newest* token and the oldest tokens trail at the higher slot indices. RoPE-encoded keys read in scrambled positional order produce garbage attention scores and the model collapses into repetition (the smoke-test signature was `<|channel|>analysis<|message|>commentaryanalysis<|message|>…?`). Replaced with retain-and-append matching `update()` and `StandardKVCache.updateConcat`: drop only enough oldest tokens to leave room for the append, keep the rest in time order. The returned slice is always chronologically sorted, so RoPE positions and SDPA (with sliding-window or causal mask) attend correctly. Verified end-to-end: - GPT-OSS-20B 4bit turbo4v2 ctx=128 (sliding window wraps repeatedly): no longer gibberish, decode 71.9 tok/s. - ctx=4096 simple: coherent. - ctx=8192 summarization: coherent, decode 59.8 tok/s, peak GPU 11.94 GB, KV cache 46 MB. - ctx=32768 summarization: coherent, decode 29.8 tok/s, peak GPU 12.5 GB. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(gemma4): spec 041 phase 5 — affine donor compression via shared-reader quantised path Closes the `--kv affine*` `StandardKVCache` fallback that Gemma 4 LLM (E2B / E4B) was routing through on KV-sharing donor layers. Donors now stay `AffineQuantizedKVCache` and their readers consume the donor's quantised `(packed, scales, biases)` tuple via `quantizedScaledDotProductAttention` — the discrete-path qSDPA that already supports sinks (PR #210). Trade-off: discrete path materialises the [B, nKVH, nRep, L, T] score matrix during the second matmul. Spec 041 phase 1 (the flash quantised SDPA kernel) will swap the call out without changing the reader API, recovering the score-tensor memory the same way `MLXFast.scaledDotProductAttention` does for FP16 K/V today. ## Changes - `Gemma4TextAttention.callAsFunction(useSharedKV:...)` gains `quantizedSharedKVArrays` / `quantizedSharedKVConfig` parameters. When set, takes precedence over the existing FP16 `sharedKVArrays` branch and routes through `quantizedScaledDotProductAttention`. - `Gemma4ModelInner.callAsFunction` populates a parallel `intermediateQuantizedKVs` array — when the donor cache is `AffineQuantizedKVCache`, we grab `getQuantizedState()` after the donor's `attentionWithCacheUpdate` runs and hand it to the reader. - `Gemma4Model.newCache(...)` flips its callers' `forceRawKV` flag to `false` — the donor path no longer needs the `StandardKVCache` fallback under affine. - `makeAttentionCache(...)`'s `forceRawKV` flag is now a "caller's contract": "my reader can / cannot consume quantised donor state." Gemma 4 LLM (this PR) sets `false`; Gemma 3n and Gemma 4 VLM still set `true` until their reader paths are similarly extended. ## Verification (M1 Max 64GB) Gemma 4 E2B affine4 summarization @ ctx=8192: | Metric | pass1 (alpha, pre-fixes) | this PR | |---|---:|---:| | Decode tok/s | 44.0 (gibberish) | 87.3 (coherent) | | Peak GPU | 9.62 GB | 5.47 GB | | KV cache | 48 MB | 26 MB | | Output | garbage | "This is a fascinating collection of excerpts, clearly drawn from Nick Carraway's perspective..." | Gemma 4 E4B affine4 + turbo4v2 summarization @ ctx=4096 — both coherent. Spec 041 doc updated: Phase 5 marked as shipped for Gemma 4 LLM; Gemma 3n / Gemma 4 VLM extension is a mechanical follow-up tracked alongside Phase 1. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(spec-040): record session blockers + sharpen Option 2 design notes 2026-05-13 session evaluating a one-shot spec 040 implementation: - Couldn't ship Option 1 (kernel pair) without the Metal toolchain installed on this dev machine (`xcodebuild -downloadComponent MetalToolchain` required). - Sketched Option 2 in detail enough to surface a design tension: Mamba state replay needs both recurrent-state capture AND conv-state capture (`applyConv` cache slot 0) to support mid-window rollback; that's the part that pushes Option 2 past the spec's "cheap fallback" estimate. Both blockers captured at the top of the spec so the next attempt can plan around them. No code change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(affine-sdpa): spec 041 phases 1+2+4 — flash quantized SDPA via dequant-then-SDPA Closes the `--kv affine*` peak-GPU gap that the discrete `quantizedMM → softmax → quantizedMM` path was causing — the [B, H, L, T] score matrix is the dominant contributor at long context (~1 GiB per layer at L=2048, T=32k on Qwen 3.5-0.8B). The new flash path dequantises K and V to FP16 once per call and routes through `MLXFast.scaledDotProductAttention`, which tiles K/V internally and runs an online softmax — never materialising the score matrix. Why "phases 1+2+4 all at once": MLX's `dequantized()` op already supports `bits ∈ {2,3,4,5,6,8}` and mxfp4 — Phase 2's broader bit-widths come for free. `MLXFast.scaledDotProductAttention(... sinks:)` natively folds sinks — Phase 4 is also free under this strategy. The single implementation path covers all three phases that spec 041 originally scoped as separate kernel work. **Auto-strategy selection** (`MLX_AFFINE_SDPA=auto`, default): - **L > 1 (prefill)**: flash path. Big peak-GPU win. - **L = 1 (decode)**: discrete path. Small score matrix; dequanting K/V per step is ~15% decode tok/s regression at long context. Override via env: `MLX_AFFINE_SDPA={auto,flash,discrete}`. **Phase 1 acceptance gate measurements** (M1 Max 64 GB): | Model | ctx | no-quant | affine4 (before) | affine4 (after) | |---|---:|---:|---:|---:| | Qwen 3.5-0.8B | 32k | 1.97 GiB | 4.03 GiB | **1.68 GiB** | | Qwen 3.5-9B | 32k | 6.91 GiB | 8.81 GiB | **6.21 GiB** | | GPT-OSS-20B | 8k | 11.94 GiB | 20.41 GiB | **11.85 GiB** | | Gemma 4-31B | 8k | 28.10 GiB | 33.43 GiB (gibberish) | **27.52 GiB coherent** | All five rows close the spec's acceptance gate ("peak GPU within 200 MiB of `--kv none`"). Three rows go FURTHER and drop peak BELOW no-quant (the 4-bit K/V cache is 4× smaller than the FP16 cache that no-quant allocates, so the smaller stored cache offsets the dequant transient). Decode (auto picks discrete for L=1): - GPT-OSS-20B 8k: 60.7 → 62.2 tok/s (improvement, not regression) - Gemma 4-31B 8k: 7.0 → 12.9 tok/s (+85% — yesterday's gibberish output was running the broken sinks path; the kv=none and turbo4v2 baselines were ~14 tok/s, so we're now in striking distance) Two new regression tests: - `testFlashQuantizedSDPAMatchesDiscreteAtPrefillLength` — flash vs discrete on L=16 (no sinks): max-diff < 5e-2. - `testFlashQuantizedSDPASinksMatchesDiscreteSinks` — flash vs discrete with sinks: same tolerance. Spec 041 updated: Phase 1 marked shipped (stop-gap via dequant-then-SDPA); Phase 1.1 fused-kernel optimisation deferred (saves the per-call K_fp + V_fp transient at long ctx, all kernel-level optimisations in the original Phase 1 design still apply to that follow-up). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(spec-041): mark phases 1, 2, 4 shipped; clarify phase 3 deferred on spec 039 Updates phase statuses to reflect what landed in `feat(affine-sdpa): spec 041 phases 1+2+4`: - Phase 1: stop-gap shipped (dequant-then-MLXFastSDPA). Fused-kernel optimisation deferred to Phase 1.1. - Phase 2: shipped for free — `dequantized()` already covers 2/3/4/5/6/8 bit + mxfp4. - Phase 3: deferred. `compressedAttention(L>1)` never fires today (`attentionWithCacheUpdate` routes L>1 through raw FP16 prefix prefill); spec 039's compressed-prefix hydration is the gating piece. - Phase 4: shipped for free — MLXFast SDPA folds sinks natively in the flash path. Discrete path's explicit fold (PR #210) is retained as the L=1 fallback. - Phase 5: shipped via PR #211 (Gemma 4 LLM affine donor compression). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(kv-cache): document MLX_AFFINE_SDPA env-var override Add the MLX_AFFINE_SDPA={auto,flash,discrete} env var to the kv-cache.md env-var table. Documents the auto-strategy selection (flash for L>1 prefill, discrete for L=1 decode) introduced by the spec 041 phases 1+2+4 work in this PR, the override modes, and the empirical peak-GPU savings on long-context prefill. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(affine-sdpa): AffineQuantizedKVCache.sdpaStrategy constructor parameter Promote the SDPA strategy selector from a global env-var-only override to a first-class per-cache constructor parameter. Callers that want to pin a strategy on a specific cache instance no longer need to mutate process env. API additions: * `AffineSDPAStrategy` enum (`.auto`, `.flash`, `.discrete`) promoted from private file-scope to a public top-level type. * `AffineQuantizedKVCache.sdpaStrategy: AffineSDPAStrategy` public property + `sdpaStrategy: AffineSDPAStrategy = .auto` constructor parameter. * `quantizedScaledDotProductAttention(..., strategy:)` parameter threads the per-cache strategy through the free function. Default `.auto` preserves backward compatibility for direct callers. * `AttentionUtils.attentionWithCacheUpdate` reads `quantizedKVCache.sdpaStrategy` and forwards it to the SDPA call. Precedence (matches the `TurboQuantizedKVCache.useDequantSDPA` / `TURBO_DEQUANT_SDPA` pattern): env var when set ▶ per-cache `sdpaStrategy` ▶ `.auto` default Env var stays the diagnostic global override (set once, applies to every cache in the process). Constructor parameter is the per-call opt-in (no env mutation required). Tests in `KVCacheTests.swift`: * `testAffineQuantizedKVCacheSDPAStrategyDefaultIsAuto` — default is `.auto` as documented. * `testAffineQuantizedKVCacheSDPAStrategyConstructorOverride` — `.flash` and `.discrete` round-trip through the property. * `testAffineSDPAStrategiesProduceEquivalentOutput` — both strategies produce non-NaN equivalent output (within 15% relative on 8-bit affine; tile-summation differences + quant noise compound). Seeded for determinism. Docs (`documentation/kv-cache.md`): * New behaviour-knob row for `AffineQuantizedKVCache.sdpaStrategy`. * `MLX_AFFINE_SDPA` env var row noted as overriding the per-cache constructor parameter. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(spec-040): drop stale Metal toolchain blocker note `make build-tests` going through `xcrun metal` was a temporary build-env issue on one dev machine, not a spec-level concern. Reduce the "session blockers" section to just the SSMStateCache layout tension which is a real ongoing design decision. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 14, 2026
…Mamba families + KV-shared models Closes the parity gaps identified in the post-#213 audit so every model that can benefit from KV compression / KV state replay gets the fused kernels under the hood without losing coherence. ## Spec 040 follow-up 1. **Conv-state capture for partial-accept rollback** (the load-bearing fix). `SSMStateCache` gains `recordMambaConvPadded(_:)` and `mambaConvPadded` storage; each Mamba mixer's `applyConv` pushes the full `[B, K-1 + T, conv_dim]` padded input when the cache is recording. `rollback(acceptedPrefix: k)` slices `padded[k : k + K - 1]` back into `cache[0]` — the conv state now advances by k accepted tokens instead of staying at the pre-record value. Without this slice the Nemotron-30B-A3B + `--ngram 3` smoke produced loop-pattern drift on partial accept; with it the same prompt produces fully coherent output at 21.4% draft-acceptance rate. Before: `"Hello! What is your and ( ( this this This is a large language model..."` After: `"We need to respond with name and capabilities, concise..."` 2. **GraniteMoeHybrid + FalconH1 integrated** alongside NemotronH — both already use the shared `ssmUpdate` Mamba 2 selective-state formulation, so the integration is the same conditional branch: `if T > 1, cache.isRecording { ssmStepRecord } else { ssmUpdate }`. Plus the `recordMambaConvPadded` call in their `applyConv` / `_applyConv`. Jamba's mamba mixer uses a 2D `A_log` shape that doesn't match the `ssm_step_record` kernel's `[H]` ALog signature; remains TODO. ## Spec 041 phase 5 extension 3. **Gemma 3n**: shared-layer fast path in `Gemma3nAttention.callAsFunction` detects `AffineQuantizedKVCache` donors and routes through `quantizedScaledDotProductAttention` on the donor's quantised tuple. `newCache` drops `forceRawKV: true` → donors stay compressed under `--kv affine*`. 4. **Gemma 4 VLM**: the `Gemma4SharedKVState.quantized` variant already existed in the VLM's `Gemma4TextAttention.callAsFunction`; just flipping `forceRawKV: false` in `newCache` activates it. ## Parity status (KV compression × KV state replay) | Family | Affine compression | TurboQuant compression | Mamba state replay | |---|---|---|---| | Qwen 3.5 (GDN) | ✓ | ✓ | ✓ (spec 020) | | GPT-OSS-20B (sinks) | ✓ (PR #210) | ✓ via α | n/a | | Gemma 4 LLM (KV-shared) | ✓ donor compressed (#211) | ✓ | n/a | | **Gemma 3n (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | **Gemma 4 VLM (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | Nemotron-30B-A3B (Mamba) | ✓ | ✓ | **✓ coherent on partial accept (this PR)** | | **GraniteMoeHybrid (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | **FalconH1 (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | Jamba (alt Mamba) | ✓ | ✓ | ⏸ (different ssmStep signature, separate kernel work) | ## Test plan - [x] `swift build` clean across all targets. - [x] Existing Mamba state-replay round-trip unit tests pass (no regression from the conv-state addition). - [x] Existing fused flash-quantized SDPA tests pass. - [x] Nemotron-30B-A3B + `--ngram 3` end-to-end: coherent output, 21.4% draft acceptance (was loop-pattern drift pre-fix). - [x] Nemotron-30B-A3B autoregressive baseline (no ngram) at 4k summarization: coherent — no regression on the baseline path. ## Out of scope (follow-ups) - Jamba mamba-mixer integration — 2D `A_log` kernel variant or Swift- side reformulation needed. - Sliding-window fused kernel path for Gemma 4 sliding layers + GPT-OSS sliding layers under affine (closes the `architecturalSlidingWindow` StandardKVCache fallback). - Spec 041 Phase 1.2 simdgroup_matrix_multiply_accumulate MMA + threadgroup codebook + INT8 score accumulator perf optimisations (closes the 18–47% gap vs the dequant-then-SDPA flash path). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 14, 2026
…Mamba families + KV-shared models (#214) * feat(kvcache): spec 041 phase 5 + spec 040 follow-up — parity across Mamba families + KV-shared models Closes the parity gaps identified in the post-#213 audit so every model that can benefit from KV compression / KV state replay gets the fused kernels under the hood without losing coherence. ## Spec 040 follow-up 1. **Conv-state capture for partial-accept rollback** (the load-bearing fix). `SSMStateCache` gains `recordMambaConvPadded(_:)` and `mambaConvPadded` storage; each Mamba mixer's `applyConv` pushes the full `[B, K-1 + T, conv_dim]` padded input when the cache is recording. `rollback(acceptedPrefix: k)` slices `padded[k : k + K - 1]` back into `cache[0]` — the conv state now advances by k accepted tokens instead of staying at the pre-record value. Without this slice the Nemotron-30B-A3B + `--ngram 3` smoke produced loop-pattern drift on partial accept; with it the same prompt produces fully coherent output at 21.4% draft-acceptance rate. Before: `"Hello! What is your and ( ( this this This is a large language model..."` After: `"We need to respond with name and capabilities, concise..."` 2. **GraniteMoeHybrid + FalconH1 integrated** alongside NemotronH — both already use the shared `ssmUpdate` Mamba 2 selective-state formulation, so the integration is the same conditional branch: `if T > 1, cache.isRecording { ssmStepRecord } else { ssmUpdate }`. Plus the `recordMambaConvPadded` call in their `applyConv` / `_applyConv`. Jamba's mamba mixer uses a 2D `A_log` shape that doesn't match the `ssm_step_record` kernel's `[H]` ALog signature; remains TODO. ## Spec 041 phase 5 extension 3. **Gemma 3n**: shared-layer fast path in `Gemma3nAttention.callAsFunction` detects `AffineQuantizedKVCache` donors and routes through `quantizedScaledDotProductAttention` on the donor's quantised tuple. `newCache` drops `forceRawKV: true` → donors stay compressed under `--kv affine*`. 4. **Gemma 4 VLM**: the `Gemma4SharedKVState.quantized` variant already existed in the VLM's `Gemma4TextAttention.callAsFunction`; just flipping `forceRawKV: false` in `newCache` activates it. ## Parity status (KV compression × KV state replay) | Family | Affine compression | TurboQuant compression | Mamba state replay | |---|---|---|---| | Qwen 3.5 (GDN) | ✓ | ✓ | ✓ (spec 020) | | GPT-OSS-20B (sinks) | ✓ (PR #210) | ✓ via α | n/a | | Gemma 4 LLM (KV-shared) | ✓ donor compressed (#211) | ✓ | n/a | | **Gemma 3n (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | **Gemma 4 VLM (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | Nemotron-30B-A3B (Mamba) | ✓ | ✓ | **✓ coherent on partial accept (this PR)** | | **GraniteMoeHybrid (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | **FalconH1 (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | Jamba (alt Mamba) | ✓ | ✓ | ⏸ (different ssmStep signature, separate kernel work) | ## Test plan - [x] `swift build` clean across all targets. - [x] Existing Mamba state-replay round-trip unit tests pass (no regression from the conv-state addition). - [x] Existing fused flash-quantized SDPA tests pass. - [x] Nemotron-30B-A3B + `--ngram 3` end-to-end: coherent output, 21.4% draft acceptance (was loop-pattern drift pre-fix). - [x] Nemotron-30B-A3B autoregressive baseline (no ngram) at 4k summarization: coherent — no regression on the baseline path. ## Out of scope (follow-ups) - Jamba mamba-mixer integration — 2D `A_log` kernel variant or Swift- side reformulation needed. - Sliding-window fused kernel path for Gemma 4 sliding layers + GPT-OSS sliding layers under affine (closes the `architecturalSlidingWindow` StandardKVCache fallback). - Spec 041 Phase 1.2 simdgroup_matrix_multiply_accumulate MMA + threadgroup codebook + INT8 score accumulator perf optimisations (closes the 18–47% gap vs the dequant-then-SDPA flash path). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(spec-040 + kv-cache): clarify conv-state replay semantics The conv-state-on-partial-accept slice was implemented inline in the preceding commit (`fad50f1`'s `SSMStateCache.rollback` body) but the slot-assignment comment block at the top of the function still claimed "the conv state is re-initialised by the layer on the next forward" — which only holds for GDN. Tighten: * `SSMStateCache.rollback` comment now distinguishes GDN (no separate conv slot — conv update folds into the recurrent delta log) from Mamba (replays `state[0]` from the `mambaConvPadded` per-step capture introduced in this PR). * Spec 040 "Known limitations" section now reflects that the conv-state limitation is closed by this PR. Issue #218 (opened in error before grepping the rebased branch) closed with reference to the inline fix. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4 tasks done
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
…ki#211) Three assertions in the MiMo tests disagree with the code that the same PR (ekryski#171) added: - The MiMo cache conforms to CBv2MTPRectangularSerializing, and MiMoV26RectangularVerifyTests asserts that the bank supports rectangular MTP verification. The test asserted the opposite. - CBv2PrefillRequirement.evaluationOnly returns a [B, 1] handle (EngineLoopV2.prefillOutput). The test expected shape [1]. - MiMoV26MTPAssistant conforms to CBv2HistoricalMTPPrefixCheckpointCoding (MiMoV26MTPPrefixCheckpoint). The test asserted that it is not a prefix checkpoint drafter. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
ml-explore#289) * fix(cache): preserve demanded fork checkpoints and bound short capture * test: let expected paged work refusals reach the caller (ekryski#209) PagedWorkFixture.prepare wrapped prepareAttentionWork in XCTUnwrap. XCTUnwrap records a test failure when its expression throws, also when the caller expects the throw with XCTAssertThrowsError. Three tests expect prepare to refuse, so each expected refusal was recorded as a failure. prepare now throws the refusal to the caller and fails only when prepareAttentionWork returns nil. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit b7bbdc2) * fix(paged): write a full destination for broadcast direct KV (ekryski#210) Materialize broadcast retained KV into a complete contiguous destination while preserving bit values, ownership validation, and reservation bounds. Focused differential paging, lifetime, and bit-exact validation completed during review. (cherry picked from commit 3799b11) * test(mimo): skip native-lane tests on machines without the lane (ekryski#192) Since eeba2af (ekryski#178), 31 XCTest cases in five MiMo suites throw nativeLaneRequired on the hosted CI runner, so every run of Fork Tests on main fails. The tests need the exclusive native GPU lane, which the runner does not have. This change turns each of those throws into an XCTSkipUnless on the same environment variables. The tests now skip, with the reason, on a machine without the lane, and run as before where the variables are set. The unused nativeLaneRequired enum case is removed from each suite. Tests only. No production code change. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> (cherry picked from commit c288f53) * test(mimo): assert the MiMo contracts that ekryski#171 shipped (ekryski#211) Three assertions in the MiMo tests disagree with the code that the same PR (ekryski#171) added: - The MiMo cache conforms to CBv2MTPRectangularSerializing, and MiMoV26RectangularVerifyTests asserts that the bank supports rectangular MTP verification. The test asserted the opposite. - CBv2PrefillRequirement.evaluationOnly returns a [B, 1] handle (EngineLoopV2.prefillOutput). The test expected shape [1]. - MiMoV26MTPAssistant conforms to CBv2HistoricalMTPPrefixCheckpointCoding (MiMoV26MTPPrefixCheckpoint). The test asserted that it is not a prefix checkpoint drafter. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 5e9d268) * test: run bit-exact reference tests only on reference hardware (ekryski#174) * style: format DiffusionGemmaVisionOracleTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: format DiffusionGemmaFactoryTests.swift Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: run bit-exact reference tests only on reference hardware Nine DiffusionGemma tests compare float bits with frozen references. On the hosted macos-26 runner (Apple M1 VM) they differ in the low bits, with no change in shape, dtype or sign. Add a `.referenceHardware` Swift Testing trait that runs a test only when MLX_REFERENCE_HARDWARE=1, and mark the nine tests with it. Elsewhere they report as skipped with the reason. No assertion, tolerance or reference changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: gate only the bit comparisons of mixed DiffusionGemma tests Three gated tests also held checks that pass on any hardware. Split them so only the bit-for-bit comparison is gated: - prefixIdentityTokensOwnerAndEmptyStateFailClosed() runs its fail-closed probes on all hardware. The donor-logits bit comparison moves to failClosedProbesLeaveDonorLogitsBitExact(). - nativeFactoryLoadsExactStateAndReleasesItsModel() keeps the load and model-release checks on all hardware. The logits bit comparison moves to nativeFactoryDenoiseMatchesReferenceBits(). - The two parameterized vision tests run their bf16 case on all hardware. The fp32 case moves to a separate gated test. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: gate only the reference comparisons of three more DiffusionGemma tests Split the three tests that were still gated whole, so their checks that pass on any hardware run everywhere: - chunkedSessionBoundsPrefillAndCanCancelAfterPrefill() keeps the prefill bounds, the complete flag, the counters, cancel, the emitted checkpoint and the released cache for widths 1, 3 and 7. The KV and logits bit comparisons move to chunkedSessionMatchesIndependentNativeReference(). - sharedWeightsConditioningKeepsCommittedCacheState() keeps the fixture checks, both cache positions and the unchanged encoder KV after the provisional canvas. The reference comparisons stay in sharedWeightsConditioningAndCommittedCacheMatchReference(). - committedPrefixRestoreKeepsPositionsAfterDonorRetirement() keeps the token count, retained bytes, donor release and both positions. The reference comparisons stay in committedPrefixRestoreIsExactAfterDonorAppendAndRetirement(). Each pair shares one helper. The fixture reference, case-count and parameter-count checks of the block and fp32 vision fixtures also run everywhere now, in blockOracleFixtureIsPinned() and fp32FixtureIsPinned(). CONTRIBUTING.md says which comparisons the gate covers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit a046367) * docs: describe demanded checkpoints and their shared fixture * fix(cache): honor request participation in short checkpoint scheduling * Preserve demanded checkpoint eligibility through preemption and packing * test: size the slot-cap request from what the ledger accepts slotCapLeavesRoomForServing() sized its request from bytesReserved. bytesReserved includes the paged pool's physical-floor overhead, which a request's target KV replaces when it reserves. The overhead depends on the buffer sizes the MLX allocator returns: a 36,864-byte segment gets a 49,152-byte buffer, or a 65,536-byte buffer reused from the process-wide cache. When earlier work left 64 KiB buffers in the cache, the capped arm left more than 5.5 windows of real slack instead of half a window, and the uncapped arm's reservation fit. Find the largest request the ledger accepts beside the capped set with trial reservations, then take half a window off it. The assertions do not change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 06224a8) * Retain demanded native frontiers and preserve observed prefill endpoints * Document current SDK parameters and generation links * Disambiguate the task generation documentation link --------- Co-authored-by: David Tai <dtaipublic@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Stacks on top of #210 (GPT-OSS sinks). Closes spec 041 Phase 5 (KV-sharing reader path) for Gemma 4 LLM — donors stay `AffineQuantizedKVCache` and the reader consumes their quantised `(packed, scales, biases)` tuple directly via `quantizedScaledDotProductAttention`. No dequant, no compression loss.
The discrete-path qSDPA is the stop-gap; spec 041 Phase 1's flash quantised SDPA kernel will swap the actual SDPA call in without changing the reader API. Phase 5 for Gemma 3n and Gemma 4 VLM remains as mechanical follow-up.
Verification (M1 Max 64GB)
Gemma 4 E2B `--kv affine4` summarization @ ctx=8192:
Gemma 4 E4B `--kv affine4` + `turbo4v2` summarization @ ctx=4096: both coherent ("The provided text includes excerpts from two different pieces of writing..." and "The provided text contains two main parts:").
Test plan
Stacked dependency
This PR is based on the GPT-OSS sinks branch (#210). Merging requires #210 to land first.