Skip to content

feat(kvcache): spec 041 phase 5 + spec 040 follow-up — parity across Mamba families + KV-shared models - #214

Merged
ekryski merged 2 commits into
alphafrom
ek/spec-041-040-followup
May 14, 2026
Merged

ekryski merged 2 commits into
alphafrom
ek/spec-041-040-followup

Conversation

@ekryski

@ekryski ekryski commented May 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

Follow-up to #213 that closes the parity gaps so every applicable model can use KV compression / KV state replay with the fused C kernels — without losing coherence.

Changes

Spec 040 (Mamba state-replay) follow-up

  1. Conv-state capture for partial-accept rollback — the load-bearing fix. SSMStateCache.recordMambaConvPadded(_:) captures the per-record padded conv input from each Mamba mixer's applyConv; rollback(acceptedPrefix: k) slices padded[k : k + K - 1] back into cache[0]. Without this, partial-accept rollback restored the conv state to pre-record while the recurrent state advanced to k — produced output drift on Nemotron-30B-A3B + ngram speculative.

    • Before: "Hello! What is your and ( ( this this This is a large language model..." (loop-pattern drift)
    • After: "We need to respond with name and capabilities, concise..." (coherent, 21.4% draft acceptance)
  2. GraniteMoeHybrid integrated — same if cache.isRecording { ssmStepRecord } else { ssmUpdate } branch as NemotronH. Plus the recordMambaConvPadded call in applyConv.

  3. FalconH1 integrated — same pattern; _ssm gains an optional cache parameter so the recording branch can see it.

Spec 041 Phase 5 extension

  1. Gemma 3n: Gemma3nAttention.callAsFunction fast path detects AffineQuantizedKVCache donors and routes through quantizedScaledDotProductAttention on the donor's quantised tuple. newCache drops forceRawKV: true → donors stay compressed under --kv affine*.

  2. Gemma 4 VLM: the VLM's Gemma4TextAttention already had the .quantized(...) Gemma4SharedKVState variant baked in; just flipping forceRawKV: false in newCache activates it.

Parity matrix (state after this PR lands)

Family Affine compression TurboQuant Mamba state replay
Qwen 3.5 (GDN) ✓ ✓ ✓ (spec 020)
GPT-OSS-20B (sinks) ✓ (#210) ⏸ * 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

* GPT-OSS-20B turbo: supportsTurboQuantization = false on alpha as of this PR — the model still falls back to no-quant on --kv turbo*. The work that flips this to true and routes attention through the dequant-SDPA + DC-bias-correction path (required because the zero-mean Lloyd-Max codebook can't represent the structured DC offset that K/V carry out of RMSNorm → Linear(bias=True) projections) lands in the next PR in this chain, #215. Once #215 merges, this cell becomes ✓ (B path: dequant + Apple's SDPA + bias).

Test plan

  • swift build clean across all targets.
  • Existing Mamba state-replay round-trip unit tests pass.
  • Existing fused flash-quantized SDPA tests pass.
  • Nemotron-30B-A3B + --ngram 3 end-to-end: coherent, 3/14 draft accepted (21.4%).
  • Nemotron-30B-A3B autoregressive baseline (no ngram): coherent at 4k summarization — no regression.

Out of scope (follow-ups)

  • Jamba mamba-mixer integration — uses 2D A_log shape that doesn't match the ssm_step_record kernel's [H] ALog signature; needs either a kernel variant or a Swift-side reformulation. No active issue — tracked inline in spec 040 "Known limitations".

The other two items previously listed here are no longer accurate at the chain level:

Chain context

This PR is now based directly on alpha. The cross-repo work it depends on (mlx#30 / mlx-c#16 / mlx-swift#31, plus the phase 1.2 set mlx#31 / mlx-c#17 / mlx-swift#32) is already in alpha. Closed PRs #210 and #211 had their content folded into #212; the chain on mlx-swift-lm reads as:

…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>
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>
@ekryski
ekryski force-pushed the ek/spec-041-040-followup branch from 8e8aac8 to 08e5718 Compare May 14, 2026 22:50
@ekryski
ekryski changed the base branch from ek/spec-041-040-fused-kernels to alpha May 14, 2026 22:50
@ekryski
ekryski merged commit 7c911d8 into alpha May 14, 2026
11 checks passed
ekryski added a commit that referenced this pull request May 14, 2026
…pped

Five stale claims caught in an audit pass:

* **TurboQuant row (line 14)**: dropped "sliding-window held back until
  #185" (#185 CLOSED, codec rotating buffer works); replaced the old
  "A path (raw fp16) / B path (compressed, default)" framing with the
  post-rework naming (A = TurboFlash compressed default; B = dequant
  + SDPA opt-in).

* **Spec 020 'what shipped' bullet (line 22)**: dropped "Mamba opt-out
  via canStateReplay=false on NemotronH / Jamba" (only Jamba is partial
  now; NemotronH / GraniteMoeHybrid / FalconH1 are integrated end-to-end
  via spec 040). Added a new bullet for spec 040 with the actual
  state-replay coverage.

* **SSMStateCache mention (line 71)**: expanded "Qwen 3.5/3.6 GDN"-only
  framing to include Mamba families (NemotronH / GraniteMoeHybrid /
  FalconH1; Jamba partial).

* **AffineQuantizedKVCache class row (line 130)**: previous note said
  "sliding-window + KV-shared donor layers automatically fall back to
  StandardKVCache under .affine(...)" and referenced open issue #202.
  All wrong now: #202 CLOSED, sliding-window keeps affine compression
  via the rotating-window cache (spec 041 phase 1.2), donors keep
  affine compression via spec 041 phase 5 (Gemma 4 LLM + VLM + Gemma 3n
  all integrated; no model still passes forceRawKV: true). Replaced
  with an accurate description of rotating eviction via the optional
  `maxSize` constructor parameter.

No new content; just bringing the doc in line with what alpha now
ships post #213/#214 and this PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski deleted the ek/spec-041-040-followup branch May 15, 2026 03:39
ekryski added a commit that referenced this pull request May 15, 2026
…to Tier 2 (#222)

* docs(specs + skills): refresh status against alpha (specs 040/041/043, spec 006/017/020/023 shipped; skills/kv-cache rewrite)

Spec status headers:
- 006: ✅ Shipped via PRs #163–#166 (KV cache type consolidation)
- 014/015/016/019/021/022: 🚧 Phase 1 scaffolds landed; phase 2+ open
- 017: ✅ All phases (1, 1B, 2, 3, 4, 5 Option A) shipped via #144 + #198
- 023: ✅ Phase 1 shipped via #154; Phase 3 subsumed by #153
- 041: ✅ Phases 1, 1.1, 1.2, 2, 4, 5 shipped via #212→#213→#214→#215;
  Phase 1.2 perf uplift moved to spec 042 Phase 1b; Phase 3 deferred
  to spec 039

IMPLEMENTATION-PLAN.md:
- Last-updated bump 2026-05-13 → 2026-05-14
- New 2026-05-14 update note covering the spec 040/041/6c/043 ship wave
- Row 6c (GPT-OSS sinks) rewritten with actual landing PRs (#213 + #215
  chain — prior row cited fabricated commit SHAs)
- Row 6d (spec 043) updated to "doc shipped via #219; impl not started"
- Spec 041 promoted from Tier 4 row 25 to Tier 2 row 10g (landed early
  as a gate-keeper for spec 040, Tier 1 row 6c, Gemma 4 KV-sharing
  fallback retirement, spec 042/043 kernel-uplift wave)
- Tier 4 renumbered: 042 is now row 25 (was row 26)
- Status snapshot rewritten: Tier 2 row 10g spec 041 ship state,
  Tier 1 row 6b spec 040 ship state, Tier 1 row 6d spec 043 doc ship,
  expanded closed-issue list, new Kernel-uplift-wave priority bullet
- Dependency graph: spec 040 reframed from "future work" to "shipped";
  spec 017 phase 3 marked shipped
- Issue #185 marked ✅ CLOSED (was 🟡 OPEN); resolution path cited
- Issue #77 cross-linked to #160 + spec 043 Phase 1
- Issue #61 confirmed still relevant
- Fixed stale "Tier 4 row 26 spec 042" refs across the doc to "Tier 4 row 25"

Skills directory:
- references/kv-cache.md: major rewrite. Old text had AffineQuantizedKVCache
  as "unbounded only" (now rotating-window via spec 041 phase 1.2),
  TurboQuantizedKVCache windowed eviction "until #185 is fixed" (#185
  closed 2026-05-12), stale "Gemma 4 produces incoherent output under
  windowed turbo", wrong makeAttentionCache signature. Added sections
  for AffineSDPAStrategy + MLX_AFFINE_SDPA env var, useBias/DC-bias
  correction, TurboFlash A/B decode paths, state-replay rollback
  (specs 020 + 040), cross-request prefix cache (spec 017),
  prefillStep parameter threading.
- references/supported-models.md: GPT-OSS row no longer claims
  supportsTurboQuantization: false; documents DC-bias + hybrid
  sliding-FP16 policy + turbo_flash_sdpa_v sinks kernel.
- SKILL.md: GenerateParameters maxKVSize comment updated to reflect
  uniform rotating-eviction across .none/.affine/.turbo; added
  prefixCacheEnabled to example + Optional Configuration table.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(specs): bulletize Status / Branch / Depends-on frontmatter blocks

Convert the **Field:** paragraph blocks at the top of each spec to a bullet
list (`- **Field:** ...`). Same content, easier to scan — fields render as
a unified list instead of stacked bold-prefix lines.

Sub-bullets under "Depends on:" indent under their parent. Wrapped
continuation lines indent to align with the bullet body.

Spec 040 also restructured: the multi-paragraph ship details that lived
under the Status field moved to a new "## Ship details (2026-05-13)"
section below the metadata bullets, so Status / Branch / Depends-on
form a clean top-of-file block.

Spec 020 closed the blank line that separated Status from Branch so the
metadata renders as a single tight bullet list.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…#214)

Merge the prepared, signed cache-copy correction after green CI and combined integration validation. Preserve ancestry for dependent cache PRs. No provider pin or deployment changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant