Skip to content

feat(prefix-cache): resolve #185 + #196 + #197 — Gemma 4 + TurboQuant + windowed - #198

Merged
ekryski merged 8 commits into
alphafrom
ek/spec-017-known-limitations
May 12, 2026
Merged

ekryski merged 8 commits into
alphafrom
ek/spec-017-known-limitations

Conversation

@ekryski

@ekryski ekryski commented May 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes spec 017's three blocking known-limitations on the prefix KV cache and lands the Option A snapshot-timing fix that resolves spec 017's residual quality / coverage issues:

Closes #185, #196, #197.

Adds specs 039 + 040 and promotes two model-family-parity tracks into Tier 1 of the implementation plan (see "Follow-ups" below). Files #201 for a pre-existing affine+KV-sharing bug surfaced by the fleet bench (not introduced by this PR).

Root causes and fixes

#197 — compressed-mode snapshot

serialiseTurbo threw snapshotInvariantViolation when cache.isCompressed == true. Every TurboQuant cache is compressed by request end, so prefix-caching never engaged for --kv turbo4v2.

Fix: serialiseTurbo dequants K/V back to raw FP16 at snapshot time via the new TurboQuantizedKVCache.dequantToRaw() — fallback path only. The hot path (Option A below) snapshots before compression ever triggers, so the dequant fallback is reserved for callers that serialise on a non-Option-A path.

#196 — Gemma 4 26B/31B lookup miss

Root cause: the default AssistantOpener.gemma4 opener <start_of_turn>model\n didn't tokenise to a single special token on the Gemma 4 tokenizer (Gemma 4 uses <|turn>, not <start_of_turn>), and the 26B/31B chat template's add_generation_prompt emits an extra <|channel>thought\n<channel|> scaffold that the policy never trimmed.

Fix: split AssistantOpener into three Gemma cases:

  • .gemma4 → <start_of_turn>model\n (legacy Gemma 1-3)
  • .gemma4Turn → <|turn>model\n (Gemma 4 small: E2B / E4B)
  • .gemma4WithThought → <|turn>model\n<|channel>thought\n<channel|> (Gemma 4 large: 26B-A4B / 31B)

AssistantOpener.detect(forModelID:) routes by id substring.

#185 — Gemma 4 + windowed-turbo gibberish

Bisected to three distinct bugs (the third surfaced during fleet-bench validation):

  1. KV-shared donor plumbing on update() — TurboQuantizedKVCache.update() didn't set lastReturnedKeys / lastReturnedValues (only updateAndDequant() did). Gemma 4's LLM-side KV-shared layers read those fields after every donor update; shared layers in E2B / E4B received nil arrays and SDPA produced garbage during prefill.
  2. Hydrate → suffix prefill mode mismatch — TurboQuant transitions to compressed mode on first decode. Snapshot captured compressed state; hydrate restored it; suffix prefill called update(...) (raw path) and overwrote the hydrated state with a fresh zero buffer. Fixed transitively by perf(prefix-cache): support compressed-mode TurboQuant in serialise/hydrate (spec 017 phase 1B+) #197's dequant-on-snapshot + Option A's pre-decode snapshot timing.
  3. KV-shared donor plumbing on compressedAttention() — once TurboQuant transitioned to compressed mode (first decode step), compressedAttention never refreshed lastReturnedKeys / lastReturnedValues. Donor's own compressed-domain SDPA ran correctly, but every shared attention layer kept reading the prefill-only K/V snapshot for the rest of the request. Output looked clean on turn 1 (single decode step doesn't drift much) but accumulated repetition from turn 2 onward — surfaced as the --method simple --kv turbo4v2 repetition on E2B / E4B that initially looked like compression-quality degradation but was actually a staleness bug.

Fix for #3: at the end of compressedAttention, refresh lastReturnedKeys / lastReturnedValues to dequanted views of the current compressed state. MSECodec.decode(...) ops are lazy in MLX, so the cost only materialises when a shared layer actually consumes the result. Gated on isDonor — non-KV-sharing caches (Qwen 3.5, Gemma 4 26B / 31B) skip the dequant entirely.

Also: added TurboQuantizedKVCache.innerState() so Gemma 4's prefill eval-barrier (issue #169) flushes pending writes. Flipped makeAttentionCache(.turbo + maxSize) to dispatch a windowed TurboQuantizedKVCache by default. Env override MLX_TURBO_WINDOWED=0 restores the legacy fallback.

Option A — snapshot post-prefill, before decode wraps anything

PrefixCacheRouteState.snapshotPostPrefill(cache:) fires immediately after model.prepare(...) returns, replacing the AsyncStream-wrap-on-completion pattern. At post-prefill timing:

  • TurboQuantizedKVCache.isCompressed == false — compression triggers on the first decode step. Snapshot is in raw mode; no dequant, no precision loss.
  • Sliding-window buffers have not yet wrapped — decode-time wrap was the failure mode tracked down during the 1K→8K Gemma 4 26B gibberish chase (prompt that fills the window triggers wrap on the first decode step; position 0 of buffer overwritten with sequence token maxSize, scrambling the prefix). trim(...) only decrements offset, doesn't undo rotation. Option A's timing dodges this entirely.
  • SSMStateCache (Qwen 3.5 / 3.6 GDN) reflects only the prompt's evolution — fixes spec 017 limitation fix affine KV quantization on hybrid Mamba/attention models #5.

Implementation:

  • New upTo: Int? parameter on serialiseLayerCacheState / serialisePrefixSnapshot. Slices each per-layer state array to stableLen along dim-2 without mutating the cache. slicedStateForSnapshot(...) handles 4D K/V/packed + 3D norm shapes uniformly.
  • hasWrappedRotatingBuffer flag on both StandardKVCache and TurboQuantizedKVCache, set at every wrap site (update, updateAndDequant, encodeNewToken, windowTrim). Defence-in-depth on the fallback path: serialiseStandard / serialiseTurbo refuse on either offset > maxSize or the flag.

Test plan

  • All existing tests pass — full suite at 317 tests after this PR (1 expected harness failure: MLX_BENCH_MODEL not set — interactive-only)
  • New tests for the spec 017 fix scope:
    • Tests/MLXLMTests/KVCacheTests.swift — testTurboQuantUpdateSetsLastReturnedKeys, testTurboQuantInnerStateExposesLiveBuffers, testTurboQuantCompressedAttentionRefreshesLastReturnedKeysOnDonor, testTurboQuantCompressedAttentionSkipsRefreshOnNonDonor, testTurboQuantDonorLastReturnedKeysGrowsAcrossDecodeSteps
    • Tests/MLXLMTests/PrefixKVCacheSerialisationTests.swift — dequantToRaw round-trip, compressed-mode snapshot dequants to raw (Option A path), rawKeyMode / windowed variants
    • Tests/MLXLMTests/PrefixKVCacheTests.swift — Gemma 4 opener variants (.gemma4 / .gemma4Turn / .gemma4WithThought)
    • makeAttentionCache windowed dispatch
    • MSECodec rotation matrix determinism
  • Spec 017 known-limitations section updated to reflect the three resolved issues + Option A
  • summarization bench method plumbs --cache-prefix (runs each context cold + warm for direct measurement)

Follow-ups (separate specs + new Tier 1 rows)

Specs 039 + 040 written + two existing tracks promoted to Tier 1 to close the "all model families at feature parity" gap before the Tier 2 wave starts:

  • New row 6a — spec 039: compressed-domain prefix KV cache. Snapshot KV in TurboQuant compressed form (~4× smaller bytes via valueBits=2 packed indices + norms) instead of raw FP16. Reuses spec 017 phase 5's post-prefill hook, TurboQuantizedKVCache.fusedEncodeDispatch (batch encode at snapshot time), and compressedAttention(L>1) (the L>1 path already exists in TurboQuant; the current AttentionUtils dispatcher routes L>1 to the raw path). Lossless, zero new Metal kernels — pure dispatcher rewire. Bumps PrefixKey.formatVersion 2 → 3. Side benefit: makes the staleness fix in this PR (isDonor-gated dequant in compressedAttention) zero-cost — shared layers attend in the compressed domain directly, no dequant needed.
  • New row 6b — spec 040: Mamba / Mamba 2 state-replay rollback. Native ssm_step_record + ssm_replay Metal pair, parallel to spec 020's shipped GDN chain (preferred option 1 in spec 020's "Mamba / Mamba 2 follow-up"). 4-repo PR chain. Lights up canStateReplay = true on Nemotron Cascade 2 / Jamba / Granite-MoE-Hybrid / FalconH1 → n-gram + prefix-cache + DFlash all start working on those families at once. Extracted out of spec 020's "Mamba / Mamba 2 follow-up" section.
  • Row 6c (promoted from Tier 4 row 16) — GPT-OSS-20B attention-sinks on TurboQuant path B. Four-repo PR chain already OPEN (mlx#16 / mlx-c#8 / mlx-swift#18 / mlx-swift-lm#99). Closes the last Path-A-only constraint on sinks-using models — also unblocks spec 039 covering GPT-OSS-20B (today spec 039 falls through to raw on sinks-using models).

Bugs surfaced (not in this PR)

  • #201 — affine4 / affine8 produce gibberish on Gemma 4 E2B / E4B. Pre-existing, same correctness class as resolved TurboQuant + sliding-window eviction produces incoherent output on Gemma 4 #185: AffineQuantizedKVCache has no lastReturnedKeys field and Gemma4ModelInner.intermediateKVs has no Affine branch. Out of scope here; fix sketch in the issue body (lean toward passing quantized state through the shared-layer pipeline and dispatching via quantizedScaledDotProductAttention like the donor's own attention does).

Residual quality / coverage limitations (documented in spec 017)

  • GPT-OSS-20B sliding_window = 128 wraps during prefill itself (not a decode-time wrap that Option A fixes). Mitigation requires in-prefill snapshot — bigger architectural change. Documented as no-benefit outcome, not blocking.
  • PrefixKey.kvHeadDim placeholder — currently 1; cross-config rejection works via modelID + kvBits so incorrect reuse doesn't happen in practice.

@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label May 12, 2026
ekryski added a commit that referenced this pull request May 12, 2026
Adds spec 039 (compressed-domain prefix KV cache) and promotes two
adjacent items into Tier 1 so every supported model family hits the
same baseline before the Tier 2 wave starts.

New Tier 1 rows:

- **6a — spec 039.** Snapshot KV in TurboQuant compressed form
  instead of FP16. Reuses spec 017 phase 5's post-prefill hook,
  TurboQuant's existing `fusedEncodeDispatch` for the snapshot-time
  batch encode, and `compressedAttention(L>1)` for warm suffix
  prefill (the L>1 path already ships in TurboQuantKVCache; the
  current `AttentionUtils` dispatcher just routes L>1 to the raw
  path). Lossless, no new Metal kernels — pure dispatcher rewire +
  metaState round-trip. ~3.4× smaller snapshot bytes on turbo4v2.
- **6b — spec 020 phase 4: Mamba / Mamba 2 state-replay kernel.**
  Native `ssm_step_record` + `ssm_replay` Metal pair, parallel to
  spec 020's shipped GDN chain. Flips `canStateReplay = true` on
  Nemotron Cascade 2 / Jamba / Granite-MoE-Hybrid / FalconH1 →
  n-gram + prefix-cache + DFlash all start working on those
  families at once.
- **6c — GPT-OSS-20B attention-sinks on TurboQuant path B.**
  Promoted from Tier 4 row 16. Four-repo PR chain already OPEN
  (mlx#16 / mlx-c#8 / mlx-swift#18 / mlx-swift-lm#99). Closes the
  last Path-A-only constraint on sinks-using models.

Together these close the "every Tier-1-supported model family runs
at the same baseline" gap that's been deferred since spec 020 +
spec 017 shipped.

Updates the row 6 (spec 017) status to "shipped" with the Option A
bench numbers and PR #198 reference. Removes the now-redundant
Tier 4 row 16 (lifted to row 6c).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski and others added 8 commits May 12, 2026 11:32
…+ windowed)

Spec 017's three blocking known-limitations all close on this branch.

#197 — TurboQuant compressed-mode snapshot/hydrate
- Drop the `cache.isCompressed` guard in `serialiseTurbo`. Instead of
  refusing compressed snapshots (Qwen 3.5 / NemotronH never got a
  prefix-cache hit because every TurboQuant cache is compressed by
  request end), dequant K/V back to raw FP16 at snapshot time via the
  new `TurboQuantizedKVCache.dequantToRaw()` helper. Every snapshot is
  now a 2-array raw payload regardless of the cache's mode.
- Extend `TurboQuantizedKVCache.metaState` with the runtime state needed
  to round-trip a compressed cache (kept for the codec-deterministic
  path — useful for future lossless work). `internal` access on
  `compressRawCache()` so tests can drive the raw→compressed transition.

#196 — Gemma 4 26B-A4B / 31B prefix-cache lookup miss
- The default `.gemma4` opener `<start_of_turn>model\n` didn't tokenise
  to a single special token in the Gemma 4 tokenizer (it encodes as 7
  literal-text fragments) and the 26B / 31B chat template emits an
  extra `<|channel>thought\n<channel|>` scaffold that the policy never
  trimmed. Snapshots covered the full 41-token prompt instead of the
  34-token stable prefix and every warm-turn lookup missed.
- Add two new openers and route by model id substring:
  - `.gemma4Turn` → `<|turn>model\n` (Gemma 4 small: E2B / E4B)
  - `.gemma4WithThought` → `<|turn>model\n<|channel>thought\n<channel|>`
    (Gemma 4 large: 26B-A4B / 31B)
  - Legacy `.gemma4` keeps `<start_of_turn>model\n` for Gemma 1-3.

#185 — Gemma 4 + TurboQuant + sliding-window incoherent output
- Bisected to two distinct bugs:
  1. `TurboQuantizedKVCache.update()` didn't set `lastReturnedKeys` /
     `lastReturnedValues`, only `updateAndDequant()` did. Gemma 4's
     KV-shared LLM path reads those fields after every donor update;
     shared sliding layers in E2B / E4B received nil and SDPA produced
     garbage logits.
  2. After hydration, suffix prefill's `attentionWithCacheUpdate(L>1)`
     calls `update(...)` (raw path), which overwrote a hydrated
     compressed cache with a fresh zero buffer. Fixed by #197's
     dequant-on-snapshot — hydrate now always lands in raw mode.
- Also add `TurboQuantizedKVCache.innerState()` so Gemma 4's prefill
  eval-barrier (issue #169) actually flushes pending K/V writes.
- Flip `makeAttentionCache(.turbo + maxSize)` to dispatch a windowed
  `TurboQuantizedKVCache` by default. `MLX_TURBO_WINDOWED=0` env knob
  restores the legacy `StandardKVCache` fallback.

Fleet bench (`--kv turbo4v2 --cache-prefix`, multi-turn, 2 turns):

| Model            | KV-share | Turn 1   | Turn 2 (hit) | Output    |
|------------------|----------|----------|--------------|-----------|
| Qwen3.5-35B-A3B  | n/a      | 1077 ms  | 405 ms (~2.7×) | coherent |
| Gemma 4 E2B      | 20/35    | 162 ms   | 366 ms       | coherent* |
| Gemma 4 E4B      | 18/42    | 220 ms   | 470 ms       | coherent  |
| Gemma 4 26B-A4B  | none     | 491 ms   | 651 ms       | coherent  |
| Gemma 4 31B      | none     | 1248 ms  | 1505 ms      | coherent  |

* Small Gemma 4 variants show mild compression-induced repetition under
  `valueBits=2`. `--kv turbo4` (symmetric) or `--kv none` are clean.

Tests: 16 new (TurboQuant update / dequant / innerState round-trip,
Gemma 4 opener variants, `makeAttentionCache` windowed dispatch).
All 314 tests pass; the one expected bench-harness failure remains
(`MLX_BENCH_MODEL not set` — interactive-only).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The summarization method previously ignored `MLX_BENCH_CACHE_PREFIX` /
`--cache-prefix`. With the spec 017 fixes landing in this branch we
want to validate the prefix cache across a fleet of context sizes,
not just the multi-turn smoke prompts.

When `--cache-prefix` is set, summarization now runs each context size
**twice** against the same prompt:
  1. Cold pass — pays the prefill + (issue #197) end-of-stream dequant
     cost. `[PREFIX-CACHE] ctx=N cold` line marks it.
  2. Warm pass — hydrates from the cold snapshot, prefills only the
     tail tokens. `[PREFIX-CACHE] ctx=N warm` line marks it.

The two TTFT numbers are directly comparable: cold ⇒ warm ratio is the
cache's contribution at that context size. The cold-turn-total minus
warm-turn-total approximates the dequant-on-snapshot overhead under
investigation.

Usage:
  ./scripts/benchmark.sh --model qwen35-0.8b --method summarization \
    --kv turbo4v2 --cache-prefix --context 1024,32768

Bench (Qwen3.5 0.8B [4bit] --kv turbo4v2):
  ctx=1024  cold TTFT 0.417s → warm TTFT 0.193s (~2.2×)
  ctx=32768 cold TTFT 19.39s → warm TTFT 0.252s (~77×)

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

Moves the prefix-cache snapshot from end-of-stream to right after
`model.prepare(...)` returns. The cache at that point is in its
pre-decode state, which means:

- `TurboQuantizedKVCache` is still in **raw mode** — compression
  only triggers on the first decode step's `compressedAttention(...)`
  call. The cold-path dequant added by issue #197 is now a fallback
  for callers that serialise on a non-Option-A path. Lossless on the
  hot path; precision-preserving on a re-snapshot of an already-
  compressed cache via `dequantToRaw()`.

- Sliding-window caches have **not yet wrapped**. Decode-time wrap
  is the failure mode I tracked down chasing the 1K→8K Gemma 4 26B
  gibberish earlier in this session: a prompt that exactly fills
  the window (`offset == maxSize` after prefill) triggers wrap on
  the first decode step — position 0 of the buffer gets overwritten
  with sequence token `maxSize`, scrambling the prefix. `trim(...)`
  only decrements `offset`, it does **not** undo rotation, so the
  pre-fix `offset <= maxSize` check let the corrupted snapshot
  through. Now we just don't write any decode tokens before
  snapshotting, so the bug can't be expressed. Added
  `hasWrappedRotatingBuffer` to both `StandardKVCache` and
  `TurboQuantizedKVCache` as a defence-in-depth flag set at every
  wrap site — `serialiseStandard` / `serialiseTurbo` refuse on
  either `offset > maxSize` *or* the flag (catches both prefill-time
  and decode-time wrap, even if a caller serialises after `trim`).
  GPT-OSS-20B (`sliding_window = 128`) gets the same treatment.

- `SSMStateCache` (Qwen 3.5 / 3.6 GDN) reflects only the prompt's
  evolution at this timing — the assistant reply hasn't run yet.
  Fixes spec 017 known-limitation #5 (SSM stale state on snapshot).

Implementation:
- New `upTo: Int?` parameter on `serialiseLayerCacheState` /
  `serialisePrefixSnapshot`. Each per-class serialiser slices its
  state arrays to the stable-prefix length along dim-2 without
  mutating the cache. `slicedStateForSnapshot(...)` handles the
  4D K/V/packed and 3D norm shape variants uniformly.
- `PrefixCacheRouteState.snapshotPostPrefill(cache:)` replaces the
  AsyncStream-wrap-on-completion pattern. Caller invokes it right
  after `TokenIterator` / `NGramSpeculativeTokenIterator` init.
  `wrapStreamForSnapshot` is gone — three call sites in
  `MLXLMCommon.generate(...)` updated.
- `dequantToRaw()` retained as the fallback path in `serialiseTurbo`
  (still triggered when `cache.isCompressed == true`). Documents
  Option A vs fallback split in the function doc.

Fleet validation (`--kv turbo4v2 --cache-prefix`):

| Model           | ctx  | Cold TTFT | Warm TTFT | Speedup |
|-----------------|------|-----------|-----------|---------|
| Qwen3.5-0.8B    | 1K   | 459 ms    | 222 ms    | 2.1×    |
| Qwen3.5-0.8B    | 32K  | 18.9 s    | 322 ms    | **59×** |
| Gemma 4 26B-A4B | mt-1 | 703 ms    | n/a       | n/a     |
| Gemma 4 26B-A4B | mt-2 | n/a       | 1007 ms   | hit     |
| Gemma 4 31B     | mt-1 | 2026 ms   | n/a       | n/a     |
| Gemma 4 31B     | mt-2 | n/a       | 2703 ms   | hit     |

Qwen 3.5 multi-turn coherent across 4 turns with topic-aware
follow-ups — SSM stale fix validated. All Gemma 4 variants coherent
(E2B/E4B retain the known compression-quality repetition under
`valueBits=2`, unchanged).

All 314 tests pass (one expected harness failure: `MLX_BENCH_MODEL
not set`).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds spec 039 (compressed-domain prefix KV cache) and promotes two
adjacent items into Tier 1 so every supported model family hits the
same baseline before the Tier 2 wave starts.

New Tier 1 rows:

- **6a — spec 039.** Snapshot KV in TurboQuant compressed form
  instead of FP16. Reuses spec 017 phase 5's post-prefill hook,
  TurboQuant's existing `fusedEncodeDispatch` for the snapshot-time
  batch encode, and `compressedAttention(L>1)` for warm suffix
  prefill (the L>1 path already ships in TurboQuantKVCache; the
  current `AttentionUtils` dispatcher just routes L>1 to the raw
  path). Lossless, no new Metal kernels — pure dispatcher rewire +
  metaState round-trip. ~3.4× smaller snapshot bytes on turbo4v2.
- **6b — spec 020 phase 4: Mamba / Mamba 2 state-replay kernel.**
  Native `ssm_step_record` + `ssm_replay` Metal pair, parallel to
  spec 020's shipped GDN chain. Flips `canStateReplay = true` on
  Nemotron Cascade 2 / Jamba / Granite-MoE-Hybrid / FalconH1 →
  n-gram + prefix-cache + DFlash all start working on those
  families at once.
- **6c — GPT-OSS-20B attention-sinks on TurboQuant path B.**
  Promoted from Tier 4 row 16. Four-repo PR chain already OPEN
  (mlx#16 / mlx-c#8 / mlx-swift#18 / mlx-swift-lm#99). Closes the
  last Path-A-only constraint on sinks-using models.

Together these close the "every Tier-1-supported model family runs
at the same baseline" gap that's been deferred since spec 020 +
spec 017 shipped.

Updates the row 6 (spec 017) status to "shipped" with the Option A
bench numbers and PR #198 reference. Removes the now-redundant
Tier 4 row 16 (lifted to row 6c).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Spec 020's "Mamba / Mamba 2 follow-up (post-MVP)" section was a
hidden spec — three implementation options, a cross-repo PR chain
plan, and an "until then" mitigation, all buried in the body of a
spec that's already shipped. Easy to miss when scanning the specs
directory.

Promoted to its own file: [specs/040-mamba-state-replay.md].

Includes:
- The same recurrence comparison (GDN sequential vs Mamba parallel
  scan) that explained why the GDN kernels don't apply.
- The three implementation options ranked (native kernel pair
  preferred over sequential fallback or `ssmAttn` augmentation).
- Full cross-repo PR chain table (mlx → mlx-c → mlx-swift →
  mlx-swift-lm) parallel to spec 020's.
- Cross-links to spec 015 phase 3 (DFlash), spec 017 (prefix cache),
  spec 039 (compressed prefix cache) — every spec that lights up
  for Mamba families when 040 lands.

Updates referencing the new spec:
- Spec 020 — status line + body references + Mamba section all
  replaced with a one-line link to spec 040.
- Spec 017 — `serialiseSSM` note now links to spec 040 for the
  Mamba flip.
- Spec 039 — phase 4 note + out-of-scope bullet link to spec 040.
- IMPLEMENTATION-PLAN — row 6b retitled from "020 phase 4 — ..." to
  "040 — Mamba / Mamba 2 state-replay rollback"; spec range
  013–039 → 013–040.

No behaviour change. Content moves, pointers updated.

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

The #185 fix made windowed-turbo dispatch on KV-shared sliding
donors *coherent* (donor's `lastReturnedKeys` was nil pre-fix → SDPA
garbage), but output quality regressed vs the pre-PR fallback path:
the donor's `valueBits=2` compressed K/V flows through 16 shared
attention layers on E2B (20 of 35 layers shared, ~16 sliding among
those), each amplifying the quantisation noise. Result on `simple` +
`summarization 1K` benches:

- E2B turbo4v2 (this branch, pre-fix): "Hello! I am Gemma 4. I am
  a helpful AI assistant. I can help you can help you with various
  tasks..." — heavy repetition
- E2B turbo4v2 (post-fix, this commit): "Hello! I am a large
  language model. I can help you with a wide variety of tasks,
  such as answering questions, generating text, summarizing text,
  trans..." — clean

`isDonor: Bool` already exists on the `KVCache` protocol but is set
post-construction, so the cache class can't react to it. The fix
routes around `makeAttentionCache(...)` directly:

- **VLM** (`Libraries/MLXVLM/Models/Gemma4.swift::newCache`):
  `numKVSharedLayers > 0` ⇒ sliding layers go through
  `StandardKVCache(maxSize:)` directly; full-attention layers stay
  on the dispatcher (smaller read fan-out, no observable quality
  drop).
- **LLM** (`Libraries/MLXLLM/Models/Gemma4.swift::newCache`):
  precise per-layer check — only the cache *indices* present in
  `previousKVs` as donor targets get routed to Standard (rather
  than every sliding layer). Marginally less aggressive than the
  VLM version because the LLM path lets us identify donors
  exactly via the existing `previousKVs` map.

Verified clean on all four Gemma 4 variants:

| Model     | turbo4v2 simple bench (post-fix)                      |
|-----------|-------------------------------------------------------|
| E2B       | "Hello! I am a large language model..."               |
| E4B       | "I am a large language model, and I can assist..."    |
| 26B-A4B   | "I don't have a formal name, but I am an AI..."       |
| 31B       | "I am a large language model, a helpful AI..."        |

26B/31B (no KV-sharing) still use windowed turbo via the dispatcher;
E2B/E4B (KV-sharing) use Standard for sliding layers. Memory delta
is small (Gemma 4 sliding caches are ≤ 512 × 1 KV-head × 256
head-dim × 2 bytes ≈ 256 KB per layer).

Multi-turn cache hits still work on E2B post-fix (`hits=1
saved_tokens=34` on turn 2). All 314 tests pass.

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

Reverts the previous workaround in favour of the actual fix.

Real bug: when Gemma 4's LLM-side `Gemma4ModelInner` threads each
donor's K/V into KV-shared attention layers, it reads
`cache.lastReturnedKeys` / `lastReturnedValues`. Those fields are
set inside `update(...)` during prefill, but `compressedAttention`
(which handles L=1 decode for TurboQuant caches) never refreshed
them. Once the cache transitioned to compressed mode on the first
decode step, the *donor's own SDPA* ran correctly in the
compressed domain — but every shared attention layer kept reading
the **prefill-only K/V snapshot** for the rest of the request.

Output looked clean on turn 1 (single decode step) and accumulated
repetition from turn 2 onward as the attended K/V drifted further
from what the donor itself saw. Not a compression-aggressiveness
issue; not a KV-sharing-incompatible-with-compression issue.
Indexing / staleness bug, as suspected.

Fix: at the end of `compressedAttention`, refresh
`lastReturnedKeys` / `lastReturnedValues` to dequanted views of
the current compressed state. `MSECodec.decode(...)` ops are lazy
in MLX, so the cost only materialises when a shared layer
actually consumes the result.

Gated on `isDonor`: caches not flagged as donors have no shared
readers, so the dequant work is pure overhead under MLX's normal
forward-pass eval barriers (Gemma 4 prefill's `eval(cache
.innerState() + [logits])` from issue #169 forces evaluation
even of unused lazy ops). Non-KV-sharing models (Qwen 3.5,
Gemma 4 26B / 31B) leave `isDonor = false` and pay zero.

Fleet validation (`simple --kv turbo4v2`):

| Model                | Output (post-fix)                                       |
|----------------------|---------------------------------------------------------|
| Qwen3.5-0.8B         | Clean. TTFT 126 ms (vs 179 ms first-fix, 145 ms baseline) |
| Gemma 4 E2B (KV-share) | Clean. TTFT 285 ms (vs 694 ms ungated; 143 ms had REPETITION) |
| Gemma 4 26B-A4B      | Clean. TTFT 583 ms (vs 866 ms ungated; 408 ms baseline) |
| Gemma 4 31B          | Clean.                                                  |

E2B multi-turn with cache hits coherently (turn 2 `hits=1
saved_tokens=34`). The 285 ms TTFT on E2B is the inherent cost of
running shared-layer attention over dequanted compressed K/V — fix
properly resolved by spec 039 (compressed-domain L>1 attention for
shared readers).

All 314 tests pass.

Reverts: `Libraries/MLXVLM/Models/Gemma4.swift` + `Libraries/
MLXLLM/Models/Gemma4.swift` workaround.

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

Locks the contract added by ba749c8 (TurboQuant.compressedAttention
refreshes lastReturnedKeys for KV-sharing donor reads). Three tests:

- testTurboQuantCompressedAttentionRefreshesLastReturnedKeysOnDonor —
  Mark cache as donor, prefill, run one decode step via
  compressedAttention, assert lastReturnedKeys/Values reflect the
  *current* (prompt + 1) sequence length, not the prefill snapshot.
  Catches the pre-fix bug directly: shape would stay at prompt_len
  instead of prompt_len + 1.

- testTurboQuantCompressedAttentionSkipsRefreshOnNonDonor —
  Companion: non-donor caches (Qwen 3.5 / Gemma 4 26B / 31B path)
  skip the dequant refresh for perf. Assert lastReturnedKeys shape
  stays at the prefill snapshot size after decode — confirms the
  isDonor gate is doing its job.

- testTurboQuantDonorLastReturnedKeysGrowsAcrossDecodeSteps —
  Five-step decode loop: every step's lastReturnedKeys length
  matches prompt_len + step_number. Locks the contract across
  multiple decode steps, not just the first one (where the bug
  was least observable — single-step drift is hard to notice).

All three tests pass; full suite remains at 314 + 3 = 317 tests.

Fleet bench validation, `simple --kv {none, affine8, affine4, turbo8,
turbo3, turbo4, turbo4v2}`:

| Model            | none | affine4/8 | turbo3 | turbo4 | turbo4v2 | turbo8 |
|------------------|------|-----------|--------|--------|----------|--------|
| Qwen3.5-0.8B     | ✅   | ✅        | ✅     | ✅     | ✅       | ✅     |
| Gemma 4 E2B      | ✅   | ❌ #201   | ✅     | ✅     | ✅       | ✅     |
| Gemma 4 26B-A4B  | ✅   | ✅        | n/a    | n/a    | ✅       | n/a    |
| Gemma 4 31B      | ✅   | ✅        | ✅     | ✅     | ✅       | ✅     |

Pre-existing affine+KV-sharing bug on Gemma 4 E2B / E4B filed as
[#201](#201). Same correctness class as resolved #185 (TurboQuant +
KV-sharing): AffineQuantizedKVCache has no `lastReturnedKeys`
mechanism and the Gemma 4 LLM `intermediateKVs` setter has no
Affine branch. Out of scope for this PR — separate follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski force-pushed the ek/spec-017-known-limitations branch from 88b2bf4 to 8e7adcc Compare May 12, 2026 17:39
@ekryski
ekryski merged commit eb317ba into alpha May 12, 2026
5 checks passed
ekryski added a commit that referenced this pull request May 12, 2026
Adds spec 039 (compressed-domain prefix KV cache) and promotes two
adjacent items into Tier 1 so every supported model family hits the
same baseline before the Tier 2 wave starts.

New Tier 1 rows:

- **6a — spec 039.** Snapshot KV in TurboQuant compressed form
  instead of FP16. Reuses spec 017 phase 5's post-prefill hook,
  TurboQuant's existing `fusedEncodeDispatch` for the snapshot-time
  batch encode, and `compressedAttention(L>1)` for warm suffix
  prefill (the L>1 path already ships in TurboQuantKVCache; the
  current `AttentionUtils` dispatcher just routes L>1 to the raw
  path). Lossless, no new Metal kernels — pure dispatcher rewire +
  metaState round-trip. ~3.4× smaller snapshot bytes on turbo4v2.
- **6b — spec 020 phase 4: Mamba / Mamba 2 state-replay kernel.**
  Native `ssm_step_record` + `ssm_replay` Metal pair, parallel to
  spec 020's shipped GDN chain. Flips `canStateReplay = true` on
  Nemotron Cascade 2 / Jamba / Granite-MoE-Hybrid / FalconH1 →
  n-gram + prefix-cache + DFlash all start working on those
  families at once.
- **6c — GPT-OSS-20B attention-sinks on TurboQuant path B.**
  Promoted from Tier 4 row 16. Four-repo PR chain already OPEN
  (mlx#16 / mlx-c#8 / mlx-swift#18 / mlx-swift-lm#99). Closes the
  last Path-A-only constraint on sinks-using models.

Together these close the "every Tier-1-supported model family runs
at the same baseline" gap that's been deferred since spec 020 +
spec 017 shipped.

Updates the row 6 (spec 017) status to "shipped" with the Option A
bench numbers and PR #198 reference. Removes the now-redundant
Tier 4 row 16 (lifted to row 6c).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski deleted the ek/spec-017-known-limitations branch May 12, 2026 17: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>
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.

TurboQuant + sliding-window eviction produces incoherent output on Gemma 4

1 participant