Repository navigation
feat(kvcache): spec 041 phase 1.2 — rotating affine cache + sliding-window fused kernel - #215
Merged
Merged
Conversation
ekryski
added a commit
that referenced
this pull request
May 13, 2026
After landing the rotating affine cache + sliding-window kernel route in #215, I A/B tested all three paths on GPT-OSS-20B `--kv affine4` ctx=4096 simple and found: | Strategy | Prefill | Decode | Output | |---|---|---|---| | discrete | 143.8 | 29.4 | **broken — 6 tokens then EOS** | | **flash** | 138.3 | **35.0** | **coherent** | | kernel | 125.6 | 32.7 | partially coherent | The `.discrete` augmented-softmax-with-sinks fold on the sliding-window mask combination produces garbage on GPT-OSS-20B. The flash (dequant-then-MLXFastSDPA) path is BOTH faster on decode AND coherent because the cache is bounded (rotating affine at 128 tokens) so the dequant transient is small and MLXFast SDPA's native sliding-window kernel handles the mask correctly. This commit teaches `AffineSDPAStrategy.choose(L:mask:)` to detect `.slidingWindow(_)` and route through `.flash` regardless of L. Other mask modes keep the previous L-based heuristic (flash for L>1 prefill, discrete for L=1 decode on unbounded caches). Bench post-fix: - GPT-OSS-20B `--kv affine4` ctx=8192 sum: decode 32.2 tok/s, **coherent output** (was loop-pattern at 31.7 with discrete). Peak GPU 11.81 GB unchanged. - Gemma 4-E2B `--kv affine4` ctx=8192 sum: 41.3 tok/s, coherent ("This is an excerpt from The Great Gatsby..."). Discrete-path sliding+sinks bug is the load-bearing reason the auto-pick is wrong; the actual fix to that fold is a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This was referenced May 14, 2026
ekryski
force-pushed
the
ek/spec-041-040-followup
branch
from
May 14, 2026 22:50
8e8aac8 to
08e5718
Compare
5 tasks done
…indow fused kernel route
Closes the `architecturalSlidingWindow + affine → StandardKVCache`
fallback that previously cost affine compression on Gemma 4 sliding
layers, GPT-OSS sliding layers, and any other architectural-sliding
model. Sliding layers now retain affine compression with bounded
memory.
`init(...)` gains `maxSize: Int? = nil`. When set, `updateQuantized`
mirrors `StandardKVCache.updateConcat`'s window-mode shape:
- **Internal storage**: trimmed to last `maxSize` quantised tokens
(bounded memory, regardless of context length).
- **Return tuple**: keeps `maxSize - 1` existing + concat new (up to
`maxSize - 1 + numSteps` tokens) so the SDPA mask shape from
`cache.makeMask(...)` matches the (queries × T_kv) layout.
New `makeMask(...)` override mirrors `StandardKVCache.makeMask`'s
window mode: caps `cappedOffset = min(maxSize - 1, offset)` before
calling `createCausalMask` so chunk-N prefill produces a mask of shape
`(n, cappedOffset + n)` that broadcasts against the trimmed concat.
`quantizedScaledDotProductAttention`'s mask-mode switch no longer falls
back on `.slidingWindow(let size)` — it now threads `windowSize: size`
into `MLXFast.flashQuantizedSDPA` (kernel-side function-constant 46 +
buffer 26 from the matching mlx PR). Causal + sliding evaluate in a
single kernel dispatch with no separate mask materialisation.
`architecturalSlidingWindow + affine` now returns
`AffineQuantizedKVCache(maxSize: slidingWindow, ...)` instead of
`StandardKVCache(maxSize:)`. `forceRawKV` retains the StandardKVCache
fallback for the donor-reader callers that haven't migrated to
quantised donor consumption yet (Gemma 3n VLM, etc.).
3 new unit tests pass:
- `testAffineQuantizedKVCacheLargePrefillChunkTrimsToWindow` — prefill
chunk of 2048 against windowSize=128 returns concat-shaped tuple
(StandardKVCache pattern) and stores trimmed window internally.
- `testAffineQuantizedKVCacheRotatingWindow` — 5×8 = 40 tokens against
windowSize=16 internally stores exactly 16.
- `testFlashQuantizedSDPASlidingWindow` — fused-kernel sliding-window
path matches MLXFast SDPA reference (max diff < 5e-2).
End-to-end bench:
- GPT-OSS-20B `--kv affine4` ctx=8192 summarization: **11.81 GB peak
(-42% vs the 20.41 GB pre-fix discrete path)**, decode 31.7 tok/s,
coherent output. Sliding layers now run on rotating affine cache
instead of the StandardKVCache FP16 fallback.
- Gemma 4-E2B `--kv affine4` ctx=8192 summarization: 5.42 GB peak,
coherent ("This is an excerpt from **The Great Gatsby**...").
- GPT-OSS-20B `--kv none` + `--kv turbo4v2` baselines unchanged.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After landing the rotating affine cache + sliding-window kernel route in #215, I A/B tested all three paths on GPT-OSS-20B `--kv affine4` ctx=4096 simple and found: | Strategy | Prefill | Decode | Output | |---|---|---|---| | discrete | 143.8 | 29.4 | **broken — 6 tokens then EOS** | | **flash** | 138.3 | **35.0** | **coherent** | | kernel | 125.6 | 32.7 | partially coherent | The `.discrete` augmented-softmax-with-sinks fold on the sliding-window mask combination produces garbage on GPT-OSS-20B. The flash (dequant-then-MLXFastSDPA) path is BOTH faster on decode AND coherent because the cache is bounded (rotating affine at 128 tokens) so the dequant transient is small and MLXFast SDPA's native sliding-window kernel handles the mask correctly. This commit teaches `AffineSDPAStrategy.choose(L:mask:)` to detect `.slidingWindow(_)` and route through `.flash` regardless of L. Other mask modes keep the previous L-based heuristic (flash for L>1 prefill, discrete for L=1 decode on unbounded caches). Bench post-fix: - GPT-OSS-20B `--kv affine4` ctx=8192 sum: decode 32.2 tok/s, **coherent output** (was loop-pattern at 31.7 with discrete). Peak GPU 11.81 GB unchanged. - Gemma 4-E2B `--kv affine4` ctx=8192 sum: 41.3 tok/s, coherent ("This is an excerpt from The Great Gatsby..."). Discrete-path sliding+sinks bug is the load-bearing reason the auto-pick is wrong; the actual fix to that fold is a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…041)
Pre-fix `attentionWithCacheUpdate` silently re-routed sinks-using models
(GPT-OSS family) from `compressedAttention` to the raw-FP16 + MLXFast
SDPA fallback whenever `sinks != nil`, defeating the user's `--kv
turbo*` intent. Per user direction: "we SHOULD NOT continue to rely on
the dequant + fp16 working buffers monkey patch when the user specifies
a KV compression scheme. We SHOULD default to using the KV compression
scheme + optimized fused C kernels."
Wires:
- `TurboQuantKernelOps.turboFlashSDPAv` Swift wrapper around the new
single-pass `MLXFast.turboFlashSDPAv(... sinks:)` kernel (spec 041
phase 1.1 follow-up). Optional `valRotation` arg folds the inverse
Π_v^T into the wrapper so callers match the existing turboFlash*
ergonomics.
- `TurboQuantKVCache.compressedAttention` accepts `sinks` and
`windowSize`; when sinks are present and L=1 with a supported
(kb, vb) combo, routes through the new single-pass kernel. Supported
combos cover the bench's parseTurboScheme outputs:
(4,4), (4,2), (4,3), (3,2), (3,3), (8,2), (8,3), (8,4), (8,8),
(2,2).
- `AttentionUtils.attentionWithCacheUpdate` drops the `sinks == nil`
gate; the A path now handles sinks + sliding window in-kernel.
`mask.windowSize` (added to the MLXFast enum) is forwarded to
`compressedAttention`, which folds the window into the same
online-softmax loop.
Tests:
- `TurboQuantKernelTests.testTurboFlashSDPAvSinksSlidingWindow`
validates kernel correctness on GPT-OSS-shape decode (B=1, nQ=8,
nKV=2, T=64, D=64, windowSize=32) across (kb, vb) ∈ {(4,4), (4,2),
(3,3), (8,4)}. All four combos land at relErr < 5e-3 against the
dequant-then-SDPA reference.
- Adjacent: caught the bit-contiguous unpacking regression for kb=3
vb=3 in the kernel header (mlx commit `14728215`); the (3,3) test
row went from relErr=1.72 → 0.003 post-fix.
A/B path comments rewritten throughout to reflect the new contract:
A (default) = compressed-domain attention; B (opt-in) = raw-FP16
+ MLXFast SDPA. The legacy "monkey patch" is now explicit opt-out
only via `TURBO_COMPRESSED_ATTENTION=0` /
`useCompressedAttention=false`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds `testTurboQuantCompressedAttentionSinksMatchesReference` to catch the GPT-OSS-20B kv-head-1+ silent-zero bug end-to-end through `TurboQuantizedKVCache.compressedAttention(... sinks:)`. The cache slices packed K/V from a larger pre-allocated buffer (allocSteps >> tokenCount), so the kernel input is a strided view; the kernel's pointer arithmetic assumed contiguous layout and silently read zeros for kv-head >= 1. Fixed upstream in mlx commit `78011998` (`ensure_contiguous` on `turbo_flash_sdpa_v` inputs). Also extends `testTurboFlashSDPAvNoSinksMatchesTurboFlashAttention`: - sinks≈-INF probe (bit-exact match) - sinks=0 probe (kernel-level match to existing β no-sinks) - with-rotation probe (matches fused pass2_fused_rot) - bf16 Q probe (cast chain through fast.cpp) All four sub-probes pass at relErr < 0.05. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ks A path Empirical follow-up to the spec 041 phase 1.1 sinks β kernel. The new single-pass β kernel produces correct kernel-level output (matches turboFlashAttention bit-exactly on synthetic data and within bf16 precision on the cache flow), but the 4-bit MSE codec quantisation noise compounds across many K positions and produces incoherent output on GPT-OSS-20B at 8K+ context. The existing `bulkDequantRotated` + `MLXFast.scaledDotProductAttention` path keeps the cache compressed (no FP16 K/V monkey-patch — that's the path the user explicitly directed us away from), but materialises a per-layer FP16 K/V *temporary* buffer for one SDPA call before freeing it. Memory overhead is small (one layer of FP16 K/V, freed between layers); quality is full FP16 SDPA. With sinks now forwarded to MLXFast (was previously hard-coded to nil here), this path handles GPT-OSS-style models correctly while keeping the on-disk and on-GPU KV cache compressed. The β kernel remains available as an opt-in via `TURBO_DEQUANT_SDPA=0` for the memory-extreme case (avoids the per-layer FP16 temporary at the cost of decode coherence on long context with sinks). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…PT-OSS Two complementary fixes for the GPT-OSS-20B + turbo* coherence problem (sinks softmax was precision-sensitive enough that the MSE codec's quantisation noise compounded into incoherent decode output at moderate context, especially with structured K/V from RMSNorm + Linear-with- bias projections). **TurboQuant + DC bias (`TURBO_BIAS=1`)** Empirical probe (`testDualScaleMSEReduction`) compared two extensions: dual-scale (post-WHT per-half scales): 1-8% MSE reduction per-vector DC bias: 9-22% MSE reduction (structured K/V) The WHT rotation flattens per-half asymmetry, eating most of the dual-scale gain. Per-vector mean is what the Lloyd-Max codebook (zero-mean calibrated) can't represent — the structural mismatch with the rotation-centric codec was the root cause. Encoder: subtract per-vector mean before unit-norm + rotation. Store the mean (`bias`) alongside `norms`. Decoder: add `bias * rotatedOnes` in rotated space (or `bias * 1_vec` after inverse rotation) — `(c + b·1) @ R^T = c @ R^T + b·(1 @ R^T)` because rotation is linear, so the bias-aware dequant is the existing dequant plus one bias-scaled constant-vector add. `rotatedOnes` cached per codec. Storage cost: one fp32 per token-head alongside `norms`. ~6MB extra at 8K context across 24 layers — negligible next to packed indices. **Hybrid sliding-FP16 layer policy (GPT-OSS-20B specific)** Under `--kv turbo*`, GPT-OSS-20B's sliding-window layers now use `StandardKVCache(maxSize: slidingWindow, keep: 0)` (raw FP16) instead of `TurboQuantizedKVCache`. Sliding layers cap at 128 tokens, so the FP16 fallback adds ~1.5MB across all sliding layers vs the full-attention layers' 96MB+ FP16 baseline at 8K. Net memory savings preserved; the sinks-sensitive sliding-window precision is bought back. This is explicit per-layer-type policy, not silent algorithm substitution: full-attention layers keep `TurboQuantizedKVCache`, `--kv affine*` keeps both layer types on affine, and the policy fires only under `.turbo` compression on GPT-OSS specifically. **Empirical (GPT-OSS-20B, M1 Max, summarization)** Before: 1024 ctx turbo4*: degenerate output across all configs 8192 ctx turbo4*: degenerate output across all configs After (TURBO_BIAS=1 + hybrid sliding): 1024 ctx turbo4: coherent ~2/3 of trials 1024 ctx turbo4v2: coherent (closer to threshold) 1024 ctx turbo8v4: inconsistent 8192 ctx turbo4: coherent both trials 8192 ctx turbo4v2: coherent (KV: 46MB vs 195MB FP16 — 4× savings) 8192 ctx turbo8v4: inconsistent Memory peak / KV cache size unchanged within margin; decode tok/s within 3-5% of pre-bias path (the extra mean + subtract + bias-add work is negligible vs the existing dequant + SDPA path). **Opt-in surface** `TURBO_BIAS=1` (env): force per-vector bias correction on `TURBO_BIAS=0` (env): force off Constructor default: `useBias: false` (backward-compatible) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires the per-vector DC-bias correction default for GPT-OSS-20B's
full-attention turbo caches. The model's K/V projections have
`bias=True`, so the rotated K/V vectors carry a structured DC offset
that the zero-mean Lloyd-Max codebook can't represent — bias
correction recovers it and lifts decode output from degenerate to
coherent at 1k + 8k summarization (verified post-rebuild without
`TURBO_BIAS=1` env var).
Plumbing:
- `makeAttentionCache(..., useBias: Bool = false)` — new parameter,
defaults off to preserve behaviour for all other models. Forwarded
to `TurboQuantizedKVCache(useBias:)` when the scheme is `.turbo`.
- `GPTOSSModel.newCache(parameters:)` passes `useBias: isTurboScheme`
on full-attention layers. Sliding-window layers remain on raw FP16
`StandardKVCache` under turbo* (unchanged from the previous commit).
- `TURBO_BIAS=0` env var still overrides this back to off for A/B
comparison.
Documentation:
- `documentation/kv-cache.md` — new row in the behaviour-knobs table
documenting `useBias` defaults + env override; new entry in the
env-var table.
- `documentation/models.md` — updates the GPT-OSS-20B + turbo* row in
Known gaps to reflect that the codec coherence issue is mitigated
by the bias + hybrid-sliding policy combo (spec 041 phase 1.1
follow-up).
Empirical (M1 Max, GPT-OSS-20B `4bit` weights):
Pre-fix turbo4v2 1k: degenerate `<|channel|>analysis...??????`
Pre-fix turbo4v2 8k: degenerate
Post-fix turbo4v2 1k: coherent `<|channel|>analysis<|message|>We need to generate...`
67 tok/s, KV 10 MB
Post-fix turbo4v2 8k: coherent `<|channel|>analysis<|message|>We have a novel?...`
50 tok/s, KV 46 MB (vs ~200 MB FP16, ~4× savings preserved)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- specs/IMPLEMENTATION-PLAN.md Tier 1 row 6c updated to "✅ Shipped 2026-05-13" with the cross-repo commit chain (mlx 5c86d7ec / 14728215 / 78011998 / 283df4cf, mlx-swift 1886126 chain, mlx-swift-lm cf516e3 → 93f191b). Status snapshot section gets a new bullet. Superseded PR chain (mlx#16, mlx-c#8, mlx-swift#18, mlx-swift-lm#99) flagged for closure. - Trimmed verbose comment blocks across the session's new code: `AttentionUtils.attentionWithCacheUpdate`, `MSECodecState.bias`, `MSECodec.encode/decode/decodeRotated`, `TurboQuantizedKVCache.useBias` + `init` env-var handling + `compressedAttention` overview + dequant-SDPA branch, `GPTOSSModel.newCache`, and the kernel header in `mlx/backend/metal/kernels/turbo_flash_sdpa.h`. Replaced the outdated TQ4_1S TODO (which predicted 15-25% MSE gain) with a pointer to the empirical probe that showed 1-8%, plus the bias alternative that ended up shipping. - Test docstrings tightened in `TurboQuantKernelTests` (3 tests) and `KVCacheTests` (`testTurboQuantCompressedAttentionSinksMatchesReference`). All tests still pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…onfigs A-path (`TURBO_COMPRESSED_ATTENTION=1`, default — compressed-domain attention via `compressedAttention`): 78/78 runs coherent. Saved to `m1-max-64gb-2026-05-13.A-path.md` (162 KB). B-path (`TURBO_COMPRESSED_ATTENTION=0` — raw-FP16 cache fallback): 78/78 runs coherent. Saved to `m1-max-64gb-2026-05-13.B-path.md` (186 KB). Coverage in each: Qwen 3.5 (0.8B/2B/4B/9B/27B/35B-A3B), Qwen 3.6 (27B), Gemma 4 (E2B/E4B/26B-A4B/31B), Nemotron 30B-A3B, GPT-OSS-20B. All under `--method summarization --context 1024`. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…DPA opt-in via TURBO_DEQUANT_SDPA=1 Drop the `headDim < 256` gate that was silently routing small / medium models through dequant-SDPA. The previous default looked like "compressed attention" but was actually `bulkDequantRotated` → `MLXFast.scaledDotProductAttention`, which materialises a per-layer FP16 K/V working buffer each decode step — a real-but-hidden expansion of working memory dressed up as the "compressed" path. Changes: * `TurboQuantizedKVCache`: replace `useCompressedAttention: Bool = true` with `useDequantSDPA: Bool = false` (positive opt-in semantic). Env override `TURBO_COMPRESSED_ATTENTION=0` → `TURBO_DEQUANT_SDPA=1`. * `compressedAttention`: TurboFlash is the unconditional default for L=1 decode — `turboFlashSDPAv` for sinks-using models, otherwise `turboFlashAttention`. Dequant-SDPA only runs when `useDequantSDPA || useBias` (bias correction still needs the B path until TurboFlash kernels learn the per-vector DC term). * `AttentionUtils.attentionWithCacheUpdate`: drop the legacy raw-FP16-cache fallback branch entirely. `.turboCompressed` decode always routes through `compressedAttention`; prefill (L>1) keeps the raw update + standard SDPA shape and the cache compresses lazily on first decode. * Remove dead methods `updateAndDequant`, `prepareQueries`, `inverseRotateOutput` and the dangling `dequantKeys` / `dequantValues` storage they referenced. Strip `β` legacy nomenclature from code comments, test prints, and MARK headers. * `GPTOSSModel.supportsTurboQuantization` → `true`. The bias-correction + hybrid sliding-FP16 policy in `newCache(...)` makes `--kv turbo*` coherent end-to-end; the old "false" gate from before that landed was stale. * Documentation: rewrite the `TurboQuantizedKVCache` row, the behaviour-knob table, and the env-var table in `kv-cache.md` to describe the new A (TurboFlash, default) vs B (dequant-SDPA, opt-in) routing. Spot-bench post-rework (1k ctx, M1 Max 64GB): | model | turbo4v2 coherent | tok/s | KV | |--------------------|-------------------|---------------|-------| | GPT-OSS-20B | yes | 65.9 (B+bias) | 10 MB | | Qwen 3.5-9B-A1B | yes | 40.8 (A) | 34 MB | | Nemotron 30B-A3B | yes | 69.3 (A) | 26 MB | GPT-OSS auto-uses B (bias forces it). Qwen / Nemotron now genuinely run TurboFlash where the prior default secretly dequanted to FP16. The 8-10% slowdown vs the old hidden-dequant default is the real cost of true compressed-domain attention; recovering it is a kernel project, not a routing trick. All TurboQuant regression tests pass (`testTurboFlashSDPAvSinksSlidingWindow`, `testTurboFlashSDPAvNoSinksMatchesTurboFlashAttention`, `testTurboQuantCompressedAttentionSinksMatchesReference`, `testDualScaleMSEReduction`). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…l matrix Re-sweep at HEAD (85afa9b, post-rework) of 13 models × 6 KV configs × {1024, 8192} contexts = 156 cells each, with `--kv turbo*` paths now genuinely meaning what they say: - A-path (`TURBO_DEQUANT_SDPA` unset, default): TurboFlash compressed- domain Metal kernel scores directly against packed K/V — no per-layer FP16 K/V materialisation. This is the true Turbo algorithm. - B-path (`TURBO_DEQUANT_SDPA=1`): `bulkDequantRotated` materialises a transient FP16 K/V tensor per decode step, then MLXFast SDPA runs on it. Matmul-engine throughput at the cost of a per-step working buffer. Both sweeps: 156/156 coherent, zero NaN, zero FAIL, identical KV bytes and near-identical peak memory across paths (same packed storage). Headline turbo* decode tok/s deltas (A vs B, mean across the three turbo configs): | Model | 1k mean Δ | 8k mean Δ | 8k worst cell | |--------------------|---------:|---------:|---------------------| | GPT-OSS 20B¹ | +1.0% | +1.4% | flat | | Gemma 4 26B-A4B | +9.6% | -7.5% | turbo8v4 -20.3% | | Nemotron 30B-A3B | -4.9% | -15.4% | turbo8v4 -30.6% | | Qwen 3.5 27B | -6.2% | -17.8% | turbo8v4 -28.8% | | Qwen 3.6 27B | -8.7% | -16.7% | turbo8v4 -29.0% | | Qwen 3.5 9B | -11.3% | -21.2% | turbo8v4 -31.9% | | Qwen 3.5 4B | -13.4% | -28.3% | turbo8v4 -39.0% | | Qwen 3.5 35B-A3B | -17.1% | -28.3% | turbo8v4 -40.1% | | Qwen 3.5 0.8B | -20.3% | -40.6% | turbo8v4 -56.2% | | Gemma 4 31B | -22.8% | -38.6% | turbo8v4 -53.3% | | Qwen 3.5 2B | -23.7% | -33.8% | turbo8v4 -43.1% | | Gemma 4 E2B | -27.7% | -34.9% | turbo8v4 -38.6% | | Gemma 4 E4B | -27.1% | -33.4% | turbo8v4 -37.6% | ¹ GPT-OSS-20B forces B-path via `useBias: true`, so A≈B by code. The pattern is consistent: TurboFlash regresses 5-28% on average at 1k and 15-40% at 8k, with the worst single-cell case at -56% on Qwen 0.8B turbo8v4 8k. The penalty scales inversely with model size (matmul- engine SDPA dominates when the model is too small to be FLOP-bound) and grows linearly with context (per-decode-step compressed-domain scan is linear in cached tokens). Memory is unchanged — both paths share the packed K/V storage; only decode-time attention compute differs. The A-path numbers validate the rework decision: the default is now the honest TurboQuant algorithm; the speed gap is the real cost of shipping the algorithm we say we ship. Closing the gap is kernel work, not routing work — tracked in the follow-up spec 043 (TurboFlash decode-time kernel uplift). A-path archive regenerated from /tmp/bench-a-path.log via a Python parser because the bench writer's per-day state file hybridised yesterday's pre-rework rows with today's clean ones; B-path archive ran with cleared state and is the bench writer's direct output. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…cache" note The rotating-window affine cache landed in this same PR's commit `5055087` (the `architecturalSlidingWindow` arm immediately below). The TODO comment claiming the fallback was unavoidable until that work shipped is now out of date — affine compression IS retained on sliding-window layers. Rewrite the comment to describe the current state instead. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
force-pushed
the
ek/spec-041-phase1-2-perf-sliding
branch
from
May 14, 2026 23:03
f4d13bc to
5826d69
Compare
…with `slidingWindow` on makeAttentionCache The dual `(maxSize, architecturalSlidingWindow)` parameters on `makeAttentionCache(...)` conflated two semantically-distinct caps: * `maxSize` was overloaded as both an *architectural* sliding-window cap (model says: "this layer must attend over only last N tokens") and a user budget hint (user passes `--max-kv-size 8192` for memory budgeting). * `architecturalSlidingWindow` was the disambiguator — but only inspected on the affine path; turbo/none branches silently treated `maxSize` as a sliding-window cap regardless. This refactor promotes the disambiguation to the caller (Option 2 per the design discussion): * **New `slidingWindow: Int?` parameter** — architectural cap; passed per-layer only when the layer's attention path demands sliding-window semantics. When non-nil, rotating eviction at this cap regardless of compression algorithm. Non-negotiable. * **`parameters?.maxKVSize` read internally** — user budget cap. Honored uniformly for `.none` / `.turbo` (rotating eviction); ignored for `.affine` on non-sliding layers (affine has no rotation for arbitrary user caps). * `architecturalSlidingWindow` parameter removed. * `maxSize` parameter removed (replaced by `slidingWindow` for the architectural use, `parameters.maxKVSize` for the user-budget use). Precedence: `slidingWindow ?? parameters?.maxKVSize ?? unbounded`. The architectural cap wins because the user can't override the model's sliding-window contract. **Callsite updates** (15 model factories): all 13 sliding-window models (Gemma 3 / 3n / 4 LLM + VLM, GPT-OSS, Mistral 3 LLM + VLM, Olmo 3, BaichuanM1, Exaone 4, MiMoV2Flash, AfMoE) updated to pass `slidingWindow:` only on sliding layers. Non-sliding factories (Qwen 3.5 LLM + VLM, NemotronH, Pixtral, the generic `LanguageModel.newCache` default) drop the redundant `maxSize: parameters?.maxKVSize` since the function reads it internally. **Latent AfMoE bug fixed as a side-effect.** Previously AfMoE passed `maxSize: slidingWindow` without `architecturalSlidingWindow: true`, which meant sliding-window AfMoE layers under `--kv affine*` were falling into the unbounded affine branch and IGNORING the cap. The new `slidingWindow:` arg now routes through the rotating-window affine cache correctly. **Tests** (`KVCacheTests::testMakeAttentionCacheTurboWindowed`): extended to cover (a) turbo + architectural slidingWindow, (b) turbo with no cap, (c) none + architectural slidingWindow, (d) none + user budget cap via `parameters.maxKVSize` (new — validates the internally-read budget path), (e) affine + user budget cap (ignored, unbounded), (f) affine + architectural slidingWindow (new — rotating affine). **Docs** (`documentation/kv-cache.md`): new section explaining the two caps + precedence rule. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…he for non-sliding layers
Closes the UX wart where `GenerateParameters(maxKVSize: 8192,
compressionAlgorithm: .affine(...))` silently ignored the cap and
returned an unbounded `AffineQuantizedKVCache`. The user was left with
no way to get a bounded affine cache on non-sliding-window models
without dropping to `.none` or `.turbo*`.
The rotating-window `AffineQuantizedKVCache` we shipped in spec 041
phase 1.2 already supports rotating eviction via its own `maxSize`
parameter. Engaging it for the user-budget case is a one-line dispatch
change: the affine branch now collapses to "if effectiveMaxSize is
set, rotating affine; otherwise unbounded affine" — same dispatch for
both cap sources, because the cache class's rotation logic doesn't
care whether the cap came from the model architecture or
`parameters.maxKVSize`.
Behavioural change:
* `GenerateParameters(maxKVSize: 8192, compressionAlgorithm: .affine(...))`
on Qwen 3.5 / Llama / other non-sliding-window models:
- Before: unbounded `AffineQuantizedKVCache` (cap silently ignored)
- After: rotating `AffineQuantizedKVCache(maxSize: 8192)` + ~3.5×
affine compression
* Architectural sliding-window dispatch unchanged: same rotating
affine cache as before.
* Unbounded affine (no cap, no sliding) unchanged.
Test (`testMakeAttentionCacheTurboWindowed`): the "affine + user
budget" case flipped from `affineUnbounded` (maxSize == nil) to
`affineUserBudget` (maxSize == 4096). New "affine + no cap" case
added for the unbounded path.
Docs (`documentation/kv-cache.md`): the two-caps table now reads
"honored uniformly across every compression scheme"; added a new
"What you get per scheme when the user sets `maxKVSize`" section
showing concrete code + a per-scheme outcome table.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…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>
`TurboQuantizedKVCache.isTrimmable = true` and `trim(_:)` are both implemented (line 1009 + 2212 of `TurboQuantKVCache.swift`). `AffineQuantizedKVCache` is also trimmable now (always was for unbounded; spec 041 phase 1.2 made the rotating variant trimmable too). Replaced the inaccurate "TurboQuant and rotating StandardKVCache are not [trimmable]" paragraph with a per-class breakdown that: * Notes all three single-stream classes (`StandardKVCache`, `AffineQuantizedKVCache`, `TurboQuantizedKVCache`) are trimmable. * Spells out the rotating-buffer wrap-time caveat that applies to both `StandardKVCache(.window)` and `TurboQuantizedKVCache(maxSize:)` — trim adjusts absolute `offset` but doesn't re-slice physical buffer once it's wrapped. * Disambiguates from the cross-request `PrefixKVCache.snapshot()` path, which has its own narrower compatibility (TurboQuant raw-mode only for now; compressed-mode round-trip = spec 039 follow-up). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…he classes
Rename `affineStep` → `prefillStep` in `makeAttentionCache` (and `makeKVCache`),
and pass the resolved value into the `step:` constructor parameter of
**all three** cache classes — `StandardKVCache`, `AffineQuantizedKVCache`,
`TurboQuantizedKVCache`. Prior to this commit only the affine path threaded
the model's `defaultPrefillStepSize` into the cache; `StandardKVCache` kept
its 256 default and `TurboQuantizedKVCache` kept its 1024 default,
so the per-class grow-chunk depended on which scheme you picked, not on the
model's prefill chunk size.
Resolution: `parameters?.prefillStepSize ?? prefillStep ?? 256`
- `parameters.prefillStepSize` — user override (`GenerateParameters`)
- `prefillStep` (arg) — model default, typically the caller's
`defaultPrefillStepSize` (1024 for most LLMs)
- `256` — last-resort fallback
Net effect: `concatenated(...)` growth events collapse 1:1 with prefill
chunks for every scheme, eliminating the `chunkSize/256`× realloc overhead
on `.none` and `.turbo` paths.
Doc:
- Updated `kv-cache.md` factory signature reference (`affineStep` → `prefillStep`).
- Added a "Cache `step` (growth chunk)" row to the Constructor toggles
table documenting the uniform threading.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
commented
May 15, 2026
| offset += numSteps | ||
| } | ||
|
|
||
| // Kept for `memoryBytes` and `trim`/state references that survive from the |
Owner
Author
There was a problem hiding this comment.
This is now pushed to precompiled kernels rather than happening in Swift.
ekryski
added a commit
to ekryski/mlx-swift
that referenced
this pull request
May 15, 2026
Adds:
- tools/audit-mirror.sh: walks every .metal/.h in
`Source/Cmlx/mlx-generated/metal/` and diffs against the canonical
counterpart in `Source/Cmlx/mlx/mlx/backend/metal/kernels/`,
normalising the submodule's full include paths to the mirror's
short form before comparing. Exits 1 with remediation hint if any
file body differs from canonical.
- .github/workflows/audit-mirror.yml: runs the audit on every PR /
push to `alpha`. Linux runner (pure bash + diff, no Metal toolchain
needed), so the gate fires in ~10s vs. waiting for the macOS build
job in alpha-ci.yml to compile + fail later.
Failure mode this closes:
SwiftPM can't compile .metal files, so downstream consumers (mlx-
swift-lm) build their `mlx.metallib` from the mlx-generated mirror,
not from the submodule. When a submodule kernel body changes (bug
fix, perf) but `tools/update-mlx.sh` isn't re-run, the metallib
silently compiles the stale mirror — function signatures stay
compatible, only numerics diverge at runtime. This is the failure
pattern that broke 3-bit turbo flash SDPA on
ekryski/mlx-swift-lm#215. `make doctor` over there only catches
signature drift, not body drift.
What this audit does NOT cover (intentional scope):
- Top-level `mlx-generated/*.cpp` JIT preambles. Generated by cmake
and contain kernel source as raw strings — can't cheaply diff
without re-running cmake. Signature drift in those is caught by
downstream `make doctor`.
- mlx-swift-only fork kernels (Class B: `warp_moe_*`). No submodule
counterpart by design; skipped automatically.
- New kernel files added to the submodule but not yet mirrored
(coverage gap, not body drift). Handled by the deliberate
`update-mlx.sh` sync flow.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
7 tasks done
ekryski
added a commit
to ekryski/mlx-swift
that referenced
this pull request
May 15, 2026
…ody-drift gap (#34) Three stacked commits closing the kernel body-drift class of bug: - fix(turbo-flash-sdpa): bit-contiguous unpacking for non-aligned bit widths in the hand-maintained `mlx-generated/metal/turbo_flash_sdpa.h` mirror. The canonical fix had been in mlx@14728215; the mirror lagged. Caught downstream in ekryski/mlx-swift-lm#215. - chore(mlx-generated): full mirror sync via tools/update-mlx.sh. Folds in rms_norm.metal bf16 NaN fix for hidden ≥ 4096, plus clang-format normalisation + regenerated cmake JIT preambles. - ci(audit-mirror): tools/audit-mirror.sh + .github/workflows/audit- mirror.yml. Runs on every PR / push to alpha (Linux runner, ~10s, pure bash + diff) — gates against the body-drift failure mode that function-signature checks can't catch. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Merged
3 tasks done
ekryski
added a commit
that referenced
this pull request
May 15, 2026
…rs surface
Adds 4 missing fields, updates 2 stale claims, drops a closed-issue row,
and documents the MLX_NGRAM_* env var family.
Missing fields added:
- draftCompressionAlgorithm — speculative-decoding draft KV cache compression
(spec 006 PR 4, 2026-05-04). Independent from main `compressionAlgorithm`
so each model can use the cache class best suited to its size.
- presenceContextSize, frequencyContextSize — per-penalty windows. Were
documented inline but missing as separate rows.
- additionalProcessors — custom LogitProcessor injection point (EOS
suppression for thinking models, grammar-constrained decoding, etc.).
Stale claims fixed:
- maxKVSize: previously claimed it backs only StandardKVCache. Post-#215
(spec 041 phase 1.2), it engages rotating eviction at the cap uniformly
across **all three** cache classes (Standard / Affine / Turbo) — closed
the affine UX wart where .affine silently ignored the cap.
- compressionAlgorithm default: was documented as `.none`, actually `nil`
(which means none).
- prefillStepSize: notes the post-#215 uniform `step:` threading across
all three cache classes — concatenated(...) growth events now collapse
1:1 with prefill chunks for every scheme, not just affine.
Closed limitation row removed:
- Dropped `#185` (Gemma 4 + --kv turbo4v2 silent fallback) from the
prefix-cache known-limitations table — issue is CLOSED. #196 and #197
remain OPEN as the gate for re-enabling default-on.
New env-var section:
- MLX_NGRAM_* family (12 vars in NgramSpeculativeDecoding.swift, only 1
was mentioned inline). Documents the 5 user-facing knobs (opt-in,
debug, leviathan, adaptive, force-ar) with one-line summaries; lists
the 9 fine-grained tuning knobs with a pointer to the source for
per-knob defaults rather than reproducing the rabbit hole here.
- MLX_AFFINE_SDPA cross-linked from kv-cache.md (spec 041 phase 1+2+4
affine SDPA strategy selector).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 15, 2026
Two corrections across rows 6 and 6c. Row 6 (017 prefix KV cache): the "Closes #185 / #196 / #197" claim was over-optimistic. Phase 5 closed #185 (Gemma 4 turbo4v2 silent fallback), but #196 (Gemma 4 26B-A4B / 31B inserts but never hits) and #197 (compressed-mode TurboQuant snapshot refused) remain OPEN — both still documented as known limitations in `documentation/generate-parameters.md`, and both gate re-enabling default-on prefix cache. Updated to be accurate. Row 6c (GPT-OSS-20B sinks): - "Superseded PRs to close" → "Superseded PRs (closed)" — all four (mlx#16, mlx-c#8, mlx-swift#18, mlx-swift-lm#99) were already closed when the new approach landed. Umbrella #130 also closed 2026-05-14 with a comment pointing to spec 041 phase 1.1's `turbo_flash_sdpa_v` as the actual fix. - Added a "Defence-in-depth follow-up" bullet for mlx-swift#34 (audit-mirror.sh + CI gate). Catches the kernel-mirror body-drift class of bug that `mlx@14728215` (already in the row's commit list) surfaced — fix had been in mlx-core but not in the SPM-compatible mirror, producing the silent 3-bit numerics divergence on PR #215. Linux-runner audit (~10s, no Metal toolchain) closes the gap that `make doctor`'s signature-only check left open. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 15, 2026
…ft spec + cross-doc audit (#219) Spec/docs-only follow-up to #215. Five files, ~530 net lines, zero code or test changes. - spec(043): TurboFlash decode-time kernel uplift — 4-phase plan to close the -22% mean turbo* decode regression vs dequant-SDPA across the 156-cell A-vs-B bench matrix. Phase 4 adds bias-aware kernel work (unblocks GPT-OSS-20B on the A path). - docs(turbo-kernels): per-kernel reference for the 11 fork Metal kernels with A/B path map, source pointers, and Swift-side wrapper map. - spec(041 / 042 / 043): status realignment — 041 phase 1.2 → 042 phase 1b (kernel work consolidated), 040 marked shipped (Jamba caveat documented), 043 phase 4 added. - docs(generate-parameters): audit + sync with current GenerateParameters surface — adds 4 missing fields (draftCompressionAlgorithm, presence/frequencyContextSize, additionalProcessors); fixes 2 stale claims (maxKVSize uniform behaviour post-#215, compressionAlgorithm default); drops closed-issue limitation row #185; documents the MLX_NGRAM_* env var family (12 vars, 5 user-facing called out). - docs(plan): row 6 stale "Closes #185 / #196 / #197" claim corrected (only #185 actually closed); row 6c updated for #130 closed + added defence-in-depth bullet for mlx-swift#34 (audit-mirror.sh CI gate). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4 tasks done
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
Integrate an isolated non-serving model correction with its regression assertions. Preserve concurrent main changes and promote the resolved recording checks to ordinary assertions. No deployment or serving dependency update.
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
Closes the `architecturalSlidingWindow + affine → StandardKVCache` fallback that previously cost affine compression on Gemma 4 sliding layers, GPT-OSS sliding layers, and any other architectural-sliding model. Sliding layers now retain affine compression with bounded memory via a new rotating-window mode on `AffineQuantizedKVCache`, plus a sliding-window-aware fused kernel route.
Three pieces
AffineQuantizedKVCache rotating-window mode: `init(...)` gains `maxSize: Int? = nil`. When set, `updateQuantized` mirrors `StandardKVCache.updateConcat`'s window shape — internal storage trimmed to `maxSize`, return tuple keeps `maxSize - 1` existing + concat new (so the SDPA mask shape matches). New `makeMask` override caps offset at `maxSize - 1` for mask construction.
Sliding-window fused kernel route: `quantizedScaledDotProductAttention`'s `.slidingWindow` mask mode no longer falls back to dequant-then-SDPA — it threads `windowSize: size` into `MLXFast.flashQuantizedSDPA` (kernel function-constant 46 + buffer 26 from the matching mlx PR).
makeAttentionCache dispatcher: `architecturalSlidingWindow + affine` returns `AffineQuantizedKVCache(maxSize: slidingWindow, ...)` instead of `StandardKVCache`.
Verification
3 new unit tests pass:
End-to-end bench:
Cross-repo chain
Stacks on #214. Cross-repo: ekryski/mlx#31, ekryski/mlx-c#17, ekryski/mlx-swift#32.