Skip to content

KV cache quantization: live GQA/sink correctness fixes - #43

Merged
Gajesh2007 merged 13 commits into
mainfrom
darkbloom/kvquant
Jun 20, 2026
Merged

Gajesh2007 merged 13 commits into
mainfrom
darkbloom/kvquant

Conversation

@Gajesh2007

Copy link
Copy Markdown
Member

Summary

  • Add sink-aware softmax support to quantizedScaledDotProductAttention.
  • Fix B>1 GQA mask handling by applying mask/sink/softmax in canonical 4D [B, nQHeads, L, kL] space, then reshaping back for quantized value matmul.
  • Keep fully masked no-sink rows finite by returning zero attention weights instead of propagating NaNs.
  • Thread GPT-OSS sinks through the quantized kernel path when that cache is explicitly selected.

Before / After

Area Before After
GPT-OSS sinks Quantized path fataled on non-zero sinks Sink logits are folded into the softmax denominator
B>1 GQA masks 4D masks could not broadcast onto 5D GQA score tensors; concurrent batching could crash Mask/sink/softmax happen in canonical 4D, works for B>1 GQA
Fully masked rows No-sink softmax could produce NaNs Fully masked no-sink rows produce finite zero attention
Correctness proof Mostly B=1/g64 coverage in downstream gate Downstream selftest now covers live Gemma g128 and GPT-OSS g64 dequant paths

Validation

Run from the parent d-inference worktree:

  • swift build --product kv-attn-selftest
  • ./.build/debug/kv-attn-selftest
  • swift test --filter KVQuant

Key downstream results:

  • Gemma k8v8:g128 B=4 GQA bool/additive masks: kernel_relL2=0.00000, quant_loss_relL2≈0.0072
  • GPT-OSS k8v8:g64:dequant B=4 GQA+sinks: cache/impl relL2=0.000000, quant_loss_relL2=0.00681

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5a9f9e9d01

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

public let cacheKind: KVQuantCacheKind

public init(
groupSize: Int = 128,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Default to a supported KV group size

QuantizedBatchKVCacheBase.updateQuantized rejects any layer whose key/value head dimension is not divisible by the configured group size. With this default, simply enabling SchedulerConfig(kvQuantization: .init()) crashes on supported 64-dim attention models such as GPT-OSS before decoding starts; use the existing QuantizedKVCache default of 64 or validate/derive the group size per model.

Useful? React with 👍 / 👎.

Comment on lines +915 to +916
if let quantConfig {
return .quantized(config: quantConfig)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Fix warm-cache merging under KV quantization

From this branch onward cold full-attention layers use the new quantized batched cache, but the warm prefix-cache and restored-checkpoint paths still seed full layers with BatchKVCache.merge(...). I checked GenerationBatch.extend: it merges by calling each layer's extendBatched, whose implementations precondition on the same concrete cache class, so a scheduler configured with kvQuantization plus a prefix-cache/checkpoint hit will crash when that warm row is merged with an existing cold quantized batch, or vice versa.

Useful? React with 👍 / 👎.

Comment on lines +193 to +194
let qk = quantized(keys, groupSize: groupSize, bits: bits)
let qv = quantized(values, groupSize: groupSize, bits: bits)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass the selected quantization mode when encoding K/V

When callers choose KVQuantizationConfig(mode: .symmetric), these calls still encode the incoming keys and values with quantized's default mode, while the cache later dequantizes and runs quantizedMM using self.mode. That mismatch corrupts attention for non-affine KV quantization; pass mode: mode here (and for initialized padding) so the stored tuples match how they are consumed.

Useful? React with 👍 / 👎.

Comment on lines +915 to +916
if let quantConfig {
return .quantized(config: quantConfig)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid kernel caches for MiMo sink layers

When kvQuantization is enabled this branch selects QuantizedBatchKVCache for every non-rotating full-attention layer. I checked MiMoV2Flash: its full layers come from KVCacheSimple, pass attention_sink_bias into attentionWithCacheUpdateAndSinks, and that helper's quantized branch still preconditions sinks == nil, so MiMo configs with full-attention sink bias will abort as soon as one of these layers runs; either route those layers to .dequant/fp16 or thread sinks through that helper too.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ab45ac112c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

public override func makeMask(
n: Int, windowSize: Int?, returnArray _: Bool
) -> MLXFast.ScaledDotProductAttentionMaskMode {
let mask = createCausalMask(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the no-mask decode fast path

When kvQuantization is enabled with cacheKind: .dequant, these caches use the regular MLXFast.scaledDotProductAttention path, but this method always materializes an explicit boolean mask. During normal single-token decode with no left padding, that mask is all true; BatchKVCache.makeMask deliberately returns .none in this exact case to avoid the documented MLX #3384 path where all-true masks on quantized Gemma 4 change top-1 output and can cause repetition. Mirroring that fast path here keeps dequant KV quantization from regressing unpadded decode accuracy/performance.

Useful? React with 👍 / 👎.

Comment on lines +915 to +916
if let quantConfig {
return .quantized(config: quantConfig)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Leave composite caches unquantized

When kvQuantization is enabled, this fall-through also classifies composite CacheList layers as a single quantized KV cache. I checked the repo for CacheList models: BaichuanM1 and FalconH1 build CacheList(MambaCache(), KVCacheSimple()), and their forward paths downcast each layer cache back to CacheList before updating the convolution and KV subcaches; replacing that object with QuantizedBatchKVCache makes the downcast fail and decode proceeds without the required recurrent/cache state. Only quantize plain full-attention caches, or recurse into the CacheList instead of replacing it.

Useful? React with 👍 / 👎.

Comment on lines +915 to +916
if let quantConfig {
return .quantized(config: quantConfig)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid kernel caches when value head dims differ

With the default .kernel kind, this also selects QuantizedBatchKVCache for full-attention layers whose value head dimension is not the query/key head dimension. I checked MiMoV2FlashAttention: it has separate headDim and vHeadDim and sizes wo for numAttentionHeads * vHeadDim; in the quantized GQA path, quantizedScaledDotProductAttention still reshapes the value matmul output with the query D, so enabling KV quantization for a no-sink MiMo full layer where vHeadDim != headDim will shape-fail or feed the projection the wrong width. Use the dequant path for those layers or make the quantized kernel preserve the value head dimension.

Useful? React with 👍 / 👎.

Gajesh2007 added a commit that referenced this pull request Jun 17, 2026
…omposite-cache guard

- DequantBatchKVCache.makeMask: return .none for single-token decode with no
  left padding (mirror BatchKVCache) so the dequant path takes SDPA's unmasked
  fast path. An explicit all-true mask routes through the divergent MLX #3384
  branch that flips top-1 logprobs on quantized Gemma 4 and traps continuous-
  batched decode in repetition loops. The kernel base class is left unchanged
  (its always-masked behavior is what the Gemma 4 g128 scheme was validated on).
- cacheFactoryKind: never replace a composite CacheList layer (e.g. BaichuanM1 /
  FalconH1 = MambaCache + KVCacheSimple) with a quantized KV cache; those models
  downcast the per-layer cache back to CacheList in forward(). Only plain
  full-attention layers are eligible for KV-quant.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f884dfc5fd

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

let newValues = (qv.wq, qv.scales, qv.biases)

_idx += stepCount
batchOffset = batchOffset + Int32(stepCount)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detach per-step offset updates

When this cache is used for single-token decode in models that capture one per-row RoPE offset for the whole batch (for example Gemma 4's shared-offset path), most layers never consume their own batchOffset; unlike BatchKVCache.update, this line keeps chaining lazy scalar additions every step. Long quantized continuous-batch generations can therefore recreate the IOGPU resource leak that the fp16 cache avoids with asyncEval(batchOffset), so mirror that decode-only detach after the increment.

Useful? React with 👍 / 👎.

return {
switch config.cacheKind {
case .kernel:
QuantizedBatchKVCache(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid advertising kernel caches for update-only models

When kvQuantization.cacheKind == .kernel is used with Gemma4Text, this factory returns QuantizedBatchKVCache, but Gemma4Attention never checks QuantizedKVCacheProtocol and only calls cache.update(keys:values:), which dequantizes the full stored cache before regular MLXFast attention. That means kernel mode silently runs the dequant path for this model and pays full-cache dequantization every decode token; either add the quantized branch for these layers or select the dequant cache explicitly for models that only use update.

Useful? React with 👍 / 👎.

Gajesh2007 added a commit that referenced this pull request Jun 18, 2026
… leak (#43)

QuantizedBatchKVCacheBase.updateQuantized chained lazy scalar additions to
batchOffset every decode step without detaching, unlike BatchKVCache.update.
For models that share one RoPE offset across layers (Gemma 4) most caches never
consume their own batchOffset, leaking a scalar buffer per step until the iogpu
numResources ceiling aborts the process. Mirror BatchKVCache's decode-only
asyncEval(batchOffset) detach — same DAR-325 class of leak, now fixed for the
quantized cache (covers both kernel and dequant paths via the shared
updateQuantized chokepoint).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 54743e5db1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// in their forward pass. Only plain full-attention layers are eligible
// for KV-quant; leave everything else on the existing fp16 path.
if layer is CacheList {
return .fp16

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve CacheList layers in the factory

When the model cache layer is a CacheList (for example BaichuanM1/FalconH1), this branch still maps it to .fp16, whose factory below constructs a plain BatchKVCache rather than a batched CacheList. Fresh evidence versus the earlier composite-cache finding is that the new CacheList guard avoids QuantizedBatchKVCache but still replaces the composite object, so those models' forward paths that downcast to CacheList lose their Mamba/KV child caches; recurse into the children or provide a batched CacheList instead.

Useful? React with 👍 / 👎.

Masked positions used +Float.leastNormalMagnitude (~0) instead of a large
negative, leaking attention to future/padded tokens. Use -greatestFiniteMagnitude.
Local Darkbloom patch (DAR-313) to be upstreamed.
…he (DAR-314)

Quantized counterpart to BatchKVCache: BatchedCache + BatchPositionedKVCache +
QuantizedKVCacheProtocol. Incremental-append quantization (O(step)); update()
returns dequant fp16 fallback, updateQuantized() returns quantized tuples for the
kernel path; per-row left-padding + allocationStep growth. Numerically verified
(kernel_relL2=0 at 8-bit vs dequant-same-data) incl finalize/extend/filter.
SchedulerConfig.kvQuantization (nil = off, byte-identical). When set, full-attention
layers build QuantizedBatchKVCache; sliding/recurrent stay fp16. cacheFactoryKind
test seam added. Off-path preserves exact Mamba->Arrays->Rotating->default order.
Refactor QuantizedBatchKVCache into a shared base + kernel subclass
(QuantizedKVCacheProtocol, Gemma) + DequantBatchKVCache (NOT conforming, so
GPT-OSS attention takes the sink-safe regular path on dequantized fp16 while
storage stays quantized). KVQuantCacheKind selects the cache in cacheFactories.
Gemma kernel path unchanged (bit-exact).
…omposite-cache guard

- DequantBatchKVCache.makeMask: return .none for single-token decode with no
  left padding (mirror BatchKVCache) so the dequant path takes SDPA's unmasked
  fast path. An explicit all-true mask routes through the divergent MLX #3384
  branch that flips top-1 logprobs on quantized Gemma 4 and traps continuous-
  batched decode in repetition loops. The kernel base class is left unchanged
  (its always-masked behavior is what the Gemma 4 g128 scheme was validated on).
- cacheFactoryKind: never replace a composite CacheList layer (e.g. BaichuanM1 /
  FalconH1 = MambaCache + KVCacheSimple) with a quantized KV cache; those models
  downcast the per-layer cache back to CacheList in forward(). Only plain
  full-attention layers are eligible for KV-quant.
… leak (#43)

QuantizedBatchKVCacheBase.updateQuantized chained lazy scalar additions to
batchOffset every decode step without detaching, unlike BatchKVCache.update.
For models that share one RoPE offset across layers (Gemma 4) most caches never
consume their own batchOffset, leaking a scalar buffer per step until the iogpu
numResources ceiling aborts the process. Mirror BatchKVCache's decode-only
asyncEval(batchOffset) detach — same DAR-325 class of leak, now fixed for the
quantized cache (covers both kernel and dequant paths via the shared
updateQuantized chokepoint).
…ath under quant

- cacheFactoryKind only quantizes plain full-attention KVCacheSimple layers;
  ChunkedKVCache and non-KVCacheSimple custom caches (e.g. DeepseekV4LayerCache)
  stay fp16 so model-side downcasts/semantics are preserved.
- admitWaiting forces the cold path when SchedulerConfig.kvQuantization is set so
  fp16 warm/restore rows never merge into a live quantized batch (extendBatched
  class-mismatch). Defense in depth; provider already disables prefix under quant.
- add non-Metal CBCacheFactorySelectionTests covering the selection matrix.
…wins

Host-overhead reductions on the memory-bandwidth-bound autoregressive
decode path. No model output changes.

CHANGE #5 — penalty sampler runs on-device (highest value):
- makeRepetitionSampler now applies repetition/presence/frequency
  penalties with MLX gather (take) → elementwise transform (which) →
  scatter (indexed assignment), all on-device. Removes the per-token
  hard GPU sync (eval + asArray) and full-vocab GPU↔host round trip.
  Logits are upcast to float32 first so the math is bit-for-bit the
  original CPU formula (v>0 ? v/rp : v*rp; then -presence; then
  -frequency*count). The scatter is functional, so the input logits
  array is never mutated.
- TokenHistoryHolder maintains token counts incrementally on append()
  instead of rescanning the full history each step (was O(n) per token
  → O(n^2) per generation; now O(unique tokens) per call). Both history
  append sites route through the new append().

CHANGE #4 — cheap per-token wins:
- GenerationBatch.step() skips the full-vocab logSumExp normalization
  when no active row needs it (gated by skipLogprobNormalization, set by
  the Scheduler from the rows' sampling params, combined with AND on
  extend). Only top-p and the penalty sampler need normalized logprobs;
  temperature/top-k/min-p/categorical/argMax are shift-invariant, so
  results are unchanged. Defaults to false (normalize) for safety.
- step() reads the single sampled token via item() for B==1 instead of
  materializing a 1-element array; multi-row path unchanged.
- outputTokenIds streaming delta change left UNCHANGED: OutputCollector
  merge propagates new.outputTokenIds as the cumulative value and the
  field is a public documented "cumulative" contract, so emitting only a
  delta risks an external streaming regression. (See report.)

CHANGE #3 — resource debug off the hot path:
- DARKBLOOM_MLX_RESOURCE_DEBUG now defaults OFF (opt-in). The Memory.*
  resource/byte reads in the step loop are already gated behind the flag,
  so they no longer run per step by default. Capability preserved; enable
  with =1/true/yes/on.

Tests: CBRepetitionPenaltyDeviceTests asserts the on-device sampler
equals the original CPU formula within 1e-4 (incl. presence/frequency-
only and the empty / out-of-range guards) and that incremental counts
match a full rescan. Existing CBRepetitionPenaltyTests and
CBGenerationBatchShapeTests stay green.
Two decode-throughput levers for the hand-rolled quantized scaled-dot-product attention, aimed at fp16 decode parity (KV-quant is a memory-capacity feature, not a speedup).

Lever A: fuse the quantized-SDPA softmax (max/sub/exp/where/sum/div) via compile(shapeless:). It is the largest cluster of small elementwise kernels on the decode path; fusing cuts per-step launch overhead. shapeless: true handles the growing-context shape churn — the score tensor's kL axis grows every token, but a shapeless graph only recompiles on rank/dtype changes, not shape changes, so it compiles once and is reused. The cores are pure axis:-1 reductions/broadcasts (no batch/head/kL constants); the quantizedMM matmuls and GQA reshape stay outside (one large kernel each, and the reshape depends on the batch axis which shapeless would bake in stale). Both no-sink and sink variants are compiled. Numerics unchanged.

Lever B: skip the all-true causal mask for single-query decode in QuantizedBatchKVCacheBase.makeMask — for n==1 with no left padding and no sliding window the mask is a no-op, so return .none and skip the per-step createCausalMask build + where. Bit-identical to the old always-masked path; n>1 and windowed/left-padded cases unchanged. Mirrors BatchKVCache.makeMask.

Tests: Tests/MLXLMTests/QuantizedSDPATests.swift — GQA parity vs an independent dequantized reference for n==1 and n>1 (max|delta| ~2-4e-7), sink-softmax parity (~1e-7), n==1 .none-vs-all-true-mask parity (delta=0), and makeMask fast-path conditions.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0f46814c07

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +358 to +360
let kDQ = dequantized(
kTuple.0, scales: kTuple.1, biases: kTuple.2,
groupSize: groupSize, bits: bits, mode: mode)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid dequantizing quantized rows on finish

When kvQuantization is enabled, GenerationBatch.next() still calls extractBatched for every finished row before the scheduler knows whether a prefix cache will be stored. This implementation dequantizes the entire quantized K/V history into a KVCacheSimple; for long contexts that creates an fp16 copy at completion time and can also pass the scheduler's rawCache.allSatisfy({ $0 is KVCacheSimple }) store guard even though admission skips prefix hits while KV quantization is active. Avoid dequantizing unless prefix caching is actually usable for the quantized run, or return a quantized single-row cache instead.

Useful? React with 👍 / 👎.

…(DAR-319 v2)

Checkpoint restore now rebuilds full-attention rows as QUANTIZED batched
caches (re-quantizing the captured fp16 prefix via the cold cache factory,
restoredFullAttentionCache) instead of fp16 BatchKVCache.merge, so a restored
row stays concrete-class-compatible with quantized cold rows under
extendBatched. Admission no longer forces the cold path under KV-quant for the
checkpoint-restore branch (engine-tier warm prefix stays fp16/cold).

Tests: restored-vs-cold parity under KV-quant + concurrent cold+restored
(the extendBatched type-compat regression) in CBCheckpointRestoreTests; all
92 CB tests + Quantized SDPA green.
…ache

GenerationBatch only extracts (dequant + copy) a finished row's prompt cache
when a prefix cache will consume it (capturePromptCacheOnFinish, set by the
scheduler from prefixCache != nil). Avoids a per-finish fp16 copy of the KV
history on runs without prefix caching (e.g. KV-quant hybrids whose prefix
tier isn't the in-GPU block cache). Also removes internal tracker refs from
comments for readability. 92 CB tests green.
@Gajesh2007
Gajesh2007 merged commit a9e0ee1 into main Jun 20, 2026
3 checks passed
@Gajesh2007
Gajesh2007 deleted the darkbloom/kvquant branch June 20, 2026 02:56
Gajesh2007 added a commit that referenced this pull request Jun 20, 2026
Integrate the rotating quant cache onto merged main (#43 + perf/composition):
- makeMask conflict resolved: combine the windowed (rotating) mask path with the
  full-attention non-windowed n==1 fast path (both preserved for their cases).
- Add quantizedRotatingFromSingleRow + restoredSlidingCache (rotating analog of
  restoredFullAttentionCache): re-quantize a restored fp16 sliding window into
  the matching quantized rotating class, preserving the absolute RoPE offset, so
  checkpoint restore composes with KV-quant on sliding layers (fixes the
  extendBatched concrete-class mismatch).
- Update CBCacheFactorySelectionTests for the new sliding-layer behavior.

Green: 92 CB + 6 checkpoint-restore + 7 rotating + 5 SDPA.
Gajesh2007 added a commit that referenced this pull request Jun 20, 2026
…KVCache) (#46)

* feat(kvcache): quantize sliding-window layers (QuantizedBatchRotatingKVCache)

KV quantization previously covered only full-attention layers
(QuantizedBatchKVCache); sliding-window layers stayed fp16 BatchRotatingKVCache,
so on the production models — Gemma-4 (mostly sliding-window=1024) and GPT-OSS
(12/24 sliding-window=128) — only ~15–30% of the KV cache was actually
quantized. This extends quantization to the sliding-window layers so the
capacity win covers the whole cache.

Approach: add an optional `windowSize` to QuantizedBatchKVCacheBase. When set,
`updateQuantized` front-trims (drops the oldest tokens off the time axis) to cap
the retained length at the window, mirroring BatchRotatingKVCache.update exactly
(multi-token prefill trims before append; single-token decode trims after). The
front-trim is group-safe: quantization groups run along the head-dim axis
(groupSize divides head_dim), never the time axis, so dropping whole leading
tokens can never split a group — it is a plain slice of the (wq, scales, biases)
tuples. Two thin subclasses: QuantizedBatchRotatingKVCache (native-kernel path)
and DequantBatchRotatingKVCache (sink models, e.g. GPT-OSS). makeMask mirrors the
reference including the single-token `.none` fast path — important because the
dequant subclass runs the regular SDPA, so always emitting an explicit array
mask would route sliding-window decode back through the mlx#3384 divergence.
extractBatched restores a windowed RotatingKVCache (metaState field-for-field
matching BatchRotatingKVCache.extract). The Scheduler factory routes
sliding-window layers to the quantized variants when kvQuantization is set;
with it nil the behavior is unchanged (still BatchRotatingKVCache).

Tests: QuantizedBatchRotatingKVCacheTests — window-length parity vs fp16 at B=4,
dequantized-window relL2 < 0.02 over a window-exceeding decode, mask fast-path
parity (the mlx#3384 guard), extract→RotatingKVCache, maxSize/isTrimmable, and
the non-windowed base unaffected. 7/7 new + 15/15 existing batch-cache tests
pass. Dual-review (Codex xhigh + independent) passed; the one finding (missing
mask fast path) is fixed here.

* feat(kvcache): compose quantized sliding-window prefix-cache restore

Integrate the rotating quant cache onto merged main (#43 + perf/composition):
- makeMask conflict resolved: combine the windowed (rotating) mask path with the
  full-attention non-windowed n==1 fast path (both preserved for their cases).
- Add quantizedRotatingFromSingleRow + restoredSlidingCache (rotating analog of
  restoredFullAttentionCache): re-quantize a restored fp16 sliding window into
  the matching quantized rotating class, preserving the absolute RoPE offset, so
  checkpoint restore composes with KV-quant on sliding layers (fixes the
  extendBatched concrete-class mismatch).
- Update CBCacheFactorySelectionTests for the new sliding-layer behavior.

Green: 92 CB + 6 checkpoint-restore + 7 rotating + 5 SDPA.

---------

Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
davidtai added a commit that referenced this pull request Oct 24, 2026
The Layr-Labs/mlx-swift revision moves from 8d927e6d to eedca444, the
new mlx-swift#63 head. It pins mlx ff4bb35b (Layr-Labs/mlx#43, a freed
compiled closure is erased from every thread compile cache, on top of
main with #40) and mlx-c 004c735f.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
davidtai added a commit that referenced this pull request Oct 24, 2026
Pin mlx-swift eedca444 (mlx ff4bb35b: #40, #43)
jonathan308 added a commit that referenced this pull request Oct 24, 2026
SDK main gained #358: Package.swift pins Layr-Labs/mlx-swift eedca444
(was 6c31f9f1), which pins mlx ff4bb35b (Layr-Labs/mlx #43: a freed
compiled closure is erased from every thread compile cache; #40: float16
and bfloat16 floor divide in float32) and mlx-c 004c735f. Clean merge.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant