Skip to content

Continuous batching (1/4): batched KV caches, factory, and cache plumbing (rebased on main) - #16

Closed
ronaldmannak wants to merge 14 commits into
mainfrom
claude/sweet-shannon-144odn
Closed

ronaldmannak wants to merge 14 commits into
mainfrom
claude/sweet-shannon-144odn

Conversation

@ronaldmannak

Copy link
Copy Markdown
Owner

Summary

This is PR #8 (continuous batching PR1 — the cache layer) rebased onto current main and reconciled with the changes main has landed in the meantime. It supersedes #8, which still points at the un-rebased claude/determined-fermat-cwpdS and conflicts with main.

Payload is unchanged from #8: the new Libraries/MLXLMCommon/Batching/ cache layer (no engine, no scheduler) plus minimal cache plumbing. No single-stream behavior changes.

New files (identical to #8):

  • Batching/BatchedCache.swift — BatchedCache protocol, BatchedCacheList composite, SSM (ArraysCache/MambaCache) conformance, and the makeBatchedCache factory.
  • Batching/BatchKVCache.swift / Batching/BatchRotatingKVCache.swift — full-attention and sliding-window batched caches (left-padding, ragged prefill, fromSingle, keep>0 rotation).
  • Tests/MLXLMTests/BatchCacheTests.swift.

Rebase / conflict reconciliation (the only difference vs #8)

Since #8 was opened, main independently grew an overlapping ArraysCache batching lifecycle through:

main's versions are upstream-aligned, authored by a core contributor, and carry regression tests, so they are treated as authoritative. The conflict in KVCache.swift was resolved by keeping main's implementation verbatim and adding back only the surface the new Batching/ files actually require but main lacks. The complete KVCache.swift delta vs main is just three additive changes (no regressions):

  1. BaseKVCache.ropeOffset declared as an open class member — the dynamic-dispatch fix from Continuous batching (1/4): batched KV caches, factory, and cache plumbing #8's own review (Codex P1), so a batched cache used as any KVCache returns its per-row .batch offset instead of the scalar extension default.
  2. createCausalMask(…, leftPadding:) — new optional parameter + per-row left-padding masking (used by BatchKVCache); defaults to nil, so single-stream callers are unaffected.
  3. ArraysCache.extract(_ idx:) — single-row extraction used by BatchedCache.extractBatched (with the optional-chaining form from Continuous batching (1/4): batched KV caches, factory, and cache plumbing #8's review).

.gitignore kept both sides (main's Python-tooling block + the .claude/worktrees/ ignore). All integration points (RoPEOffset.batch, BatchPositionedKVCache, attentionWithCacheUpdate, CacheList.children, MambaCache.init(leftPadding:), slotCount/currentLengths) were verified against main's symbols.

Caveat

As with #8, this was rebased in a Linux / no-Metal environment and could not be compiled or test-run locally — the macOS/Metal + CI lane is the compile and numerical-parity gate.

🤖 Generated with Claude Code


Generated by Claude Code

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces continuous-batching support for KV caches, adding BatchKVCache and BatchRotatingKVCache alongside a unified BatchedCache protocol, factory utilities, and comprehensive unit tests. Feedback on the changes highlights two severe issues: a critical out-of-bounds write and negative growth crash when extracting a sequence from a rotated BatchRotatingKVCache with left-padding, and a high-severity bug in BatchKVCache.filter(batchIndices:) where a negative index can corrupt the cache during chunked prefill.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +769 to +771
let seqEnd = maxCacheSize
extractedK = MLX.contiguous(extractedK[0..., 0..., padding ..< seqEnd, 0...])
extractedV = MLX.contiguous(extractedV[0..., 0..., padding ..< seqEnd, 0...])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

Critical Bug: Out-of-Bounds Write & Negative Growth Crash on Extracted Cache Update

When extracting a sequence from a rotated BatchRotatingKVCache where seqOffset >= maxCacheSize but leftPadding > 0 (which is common after batch extension), stripping the padding reduces the physical keys/values dimension below maxCacheSize (e.g., to maxCacheSize - padding).

This causes two severe issues when the extracted RotatingKVCache is subsequently updated:

  1. Negative Growth Crash: Since offset >= keys.dim(2) and keys.dim(2) < maxCacheSize, RotatingKVCache.updateInPlace tries to grow the cache to maxCacheSize. However, because offset >= maxCacheSize, maxCacheSize - offset is negative or zero, leading to a negative newSize and a crash in MLXArray.zeros().
  2. Out-of-Bounds Write: Even if it doesn't try to grow, cacheIdx (which becomes idx in metaState) is set to min(seqOffset, maxCacheSize, keys.dim(2)) = keys.dim(2). Writing at idx = keys.dim(2) on an array of size keys.dim(2) causes an out-of-bounds crash.

To fix this, we must keep the full maxCacheSize buffer when seqOffset >= maxCacheSize to ensure the physical buffer size remains maxCacheSize and the write pointer wraps correctly to keep.

                // Only strip padding if the sequence has not wrapped yet.
                // If seqOffset >= maxCacheSize, we must keep the full maxCacheSize buffer
                // to prevent out-of-bounds writes and negative growth crashes in RotatingKVCache.
                if seqOffset < maxCacheSize {
                    let seqEnd = maxCacheSize
                    extractedK = MLX.contiguous(extractedK[0..., 0..., padding ..< seqEnd, 0...])
                    extractedV = MLX.contiguous(extractedV[0..., 0..., padding ..< seqEnd, 0...])
                } else {
                    extractedK = MLX.contiguous(extractedK)
                    extractedV = MLX.contiguous(extractedV)
                }

Comment on lines +241 to +242
let minLeftPad = leftPadding.min().item(Int32.self)
if minLeftPad > 0, keys != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

High Severity Bug: Potential Negative Index & Cache Corruption during Chunked Prefill

In filter(batchIndices:), the cache shifts keys/values left by minLeftPad to discard padding. However, there is no guard ensuring that _idx (the number of physically written tokens) is at least minLeftPad.

During chunked prefill or when filtering is triggered before the full padded prompt is written, _idx can be less than minLeftPad. If this happens:

  1. _idx -= padInt will drive _idx negative.
  2. Slicing keys?[.ellipsis, padInt..., 0...] will slice beyond the logically written tokens, discarding valid tokens and keeping uninitialized garbage.

Adding _idx >= Int(minLeftPad) to the condition prevents this corruption.

Suggested change
let minLeftPad = leftPadding.min().item(Int32.self)
if minLeftPad > 0, keys != nil {
let minLeftPad = leftPadding.min().item(Int32.self)
if minLeftPad > 0, keys != nil, _idx >= Int(minLeftPad) {

@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: b54be71a89

ℹ️ 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".

/// stored slots are identical); the Mamba auto-upgrade path can refine this
/// to preserve the concrete subtype if needed.
public func extract(_ idx: Int) -> ArraysCache {
let extracted = ArraysCache(size: cache.count)

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 MambaCache type when extracting SSM rows

When callers extract a row from a batched MambaCache, this constructs a plain ArraysCache, so the returned single-request cache no longer satisfies the cache as? MambaCache downcasts used by hybrid/SSM model blocks (for example Libraries/MLXLLM/Models/LFM2.swift:303). In that extraction/continuation path the recurrent state is then ignored and not updated, producing incorrect generation for Mamba-backed layers; the extracted cache should preserve the concrete MambaCache subtype or extractBatched should special-case it.

Useful? React with 👍 / 👎.

// non-simple cache would silently contribute an all-zero row that the
// mask still exposes. Fail loudly instead.
precondition(
caches.allSatisfy { $0 is KVCacheSimple },

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 Reject ChunkedKVCache in simple-cache adapters

Because ChunkedKVCache subclasses KVCacheSimple, this precondition still lets it through even though the factory rejects chunked caches. When a chunked cache has trimmed its front, offset remains absolute while the inherited keys buffer only contains the retained chunk, so the merge loop later uses seqLen = c.offset and slices past the available KV data; use an exact-type check before copying the simple-cache layout.

Useful? React with 👍 / 👎.

Comment on lines +134 to +135
public func prepareBatched(leftPadding _: [Int]?, lengths: [Int]?, rightPadding _: [Int]?) {
prepare(lengths: lengths)

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 Honor SSM left padding during prepareBatched

When a ragged/cached prefill calls prepareBatched(leftPadding:...) on an ArraysCache/MambaCache, this drops the left-padding argument instead of updating ArraysCache.leftPadding. createSSMMask reads that field, so SSM rows prepared through this protocol can process padded tokens as real input while the attention caches in the same batched lifecycle correctly apply the padding.

Useful? React with 👍 / 👎.

/// [2, 6, 8, 9]
/// ```
/// With `leftPadding = [1, 3, 0]`.
public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache {

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 Register batched caches for prompt-cache round trips

This new public cache exposes state/metaState, but the prompt-cache serializer has no class-name/restore cases for BatchKVCache or BatchRotatingKVCache; cacheClassName therefore falls through to KVCache, and loadPromptCache reconstructs a KVCacheSimple from batched state, either fataling on the four-array state or misreading an empty batched cache as keys/values. Any saved continuous-batching cache snapshot will not round-trip until these cache types are registered or explicitly rejected.

Useful? React with 👍 / 👎.

claude added 8 commits June 23, 2026 17:14
…ng PR1)

First of a stacked series adding continuous/batched inference. This PR is the
cache layer only — no engine or scheduler — and must not change single-stream
behavior.

New (Libraries/MLXLMCommon/Batching/):
- BatchedCache: the continuous-batching cache protocol (filter/extend/prepare/
  finalize/extract/advance), the BatchedCacheList composite, the SSM conformance
  for ArraysCache/MambaCache, and the makeBatchedCache factory.
- BatchKVCache / BatchRotatingKVCache: full-attention and sliding-window batched
  caches with left-padding, ragged-prefill prepare/finalize, fromSingle, and
  (rotating) keep>0 rotation. Both conform to BatchedCache.

KVCache.swift:
- createCausalMask gains a per-sequence leftPadding argument.
- ArraysCache gains the ragged-prefill lifecycle (lengths/prepare/finalize/
  advance/extract) and the SSM mask-ordering fix; single-stream callers (which
  leave leftPadding/lengths nil) are unaffected.

The factory routes rotating caches with keep>0 to the keep-capable
BatchRotatingKVCache rather than rejecting them, and throws only for quantized
and chunked topologies.

Deferred (documented for later PRs in the series):
- KVCache: Updatable — pending verification of the protocol's requirements on a
  Metal/macOS build; not needed by the cache layer.
- SSM/composite fromSingle and Mamba-typed row extraction — implemented with
  PR4's auto-upgrade migration, where they can be validated end-to-end.

Tests: Tests/MLXLMTests/BatchCacheTests.swift (cache lifecycle, keep>0 overflow,
fromSingle, factory routing incl. keep>0, SSM/composite, left-padding masking).

https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
…cases

Codex / Gemini review fixes:
- ropeOffset (Codex P1): BaseKVCache now declares ropeOffset as an overridable
  class member, and BatchKVCache/BatchRotatingKVCache override it to return the
  per-row .batch offset. Previously, accessing a batched cache as KVCache
  dispatched to the scalar extension default, corrupting batched RoPE. Adds a
  regression test.
- extend on empty caches (Codex P2): concatenate row metadata when both caches
  are empty so admitted rows are not dropped before first prefill (both caches).
- filter([]) (Codex P2): reset rotated/_lengths/_rightPadding so a reused
  rotating cache starts unrotated.
- prepare (Gemini high): use rp.contains(where:) instead of rp.max()! to avoid a
  crash on an empty rightPadding array.
- dynamicRoll (Gemini medium): use % instead of remainder to avoid overload
  ambiguity with Foundation/Darwin remainder.
- ArraysCache filter/extract (Gemini medium): use optional-chaining subscripts.

Deferred:
- Rotating merge/extract tail for over-window prompts (Codex C4): noted in-code;
  validated in PR4 where merge is wired and testable.

https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
RotatingKVCache.keep is private to KVCache.swift, so BatchRotatingKVCache's
merge/fromSingle could not read cache.keep directly. Read it via the public
metaState[0] (= keep), matching the makeBatchedCache factory. Flagged by the
PR2 engine work as a stack-wide compile blocker.

https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
…rrides

- Remove `_rightPadding = nil` from BatchRotatingKVCache.filter([]) — that field
  only exists on BatchKVCache, so assigning it on the rotating cache was a
  compile error introduced in the prior fix round (Codex P1).
- Add copy() overrides to BatchKVCache and BatchRotatingKVCache so generic
  snapshot/copy paths (e.g. ChatSession's `cache.map { $0.copy() }`, and
  CacheList.copy() with batched children) deep-copy keys/values/offsets/padding/
  transient state instead of hitting BaseKVCache.copy()'s fatalError (Codex P2).

https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
…, enforce prefill-before-extend

- BatchRotatingKVCache.offset now reports the monotonic logical cache
  length (min(_scalarOffset, maxCacheSize)) instead of the ring write
  pointer _idx. _idx resets to `keep` on wrap, so generic callers that
  derive masks from cache.offset (e.g. the array-based
  createAttentionMask(h:cache:) used by Gemma2ModelInner) saw the
  position jump backward after the first rotation and built masks with
  too small an offset. This mirrors single-stream RotatingKVCache.offset,
  which reports a monotonic position rather than the ring index.

- Both extend() methods now precondition that a non-empty `other`
  (batchSize > 0) has been prefilled (keys != nil), making the
  prefill-before-extend admission contract explicit in code and closing
  the "append empty admitted rows" hole. The PR2 engine prefills each
  admitted sub-batch before calling extend, so this path is unreachable
  in the engine flow.

https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
… extract idx, preserve BatchedCacheList in copy

- BatchKVCache.filter: skip the left-padding buffer/index shift while
  keys == nil so a fresh/cancelled-before-prefill cache does not drive
  _idx negative or leave batchOffsets inconsistent, which would corrupt
  the next prefill's prev range.
- BatchRotatingKVCache.extract: restore the single RotatingKVCache idx
  from the row's logical write position (min(seqOffset, maxCacheSize)
  clamped to the extracted tensor length) instead of the padded tensor
  length, so a shorter/left-padded row in a globally-rotated batch does
  not lose its first post-extraction token.
- BatchedCacheList.copy: override CacheList.copy to return a
  BatchedCacheList of copied BatchedCache children so generic cache
  snapshots keep the continuous-batching wrapper (filter/extend/
  finalize/extract through the protocol).

https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp
… paths

- Factory: RotatingKVCache probes with keep > 0 now throw
  BatchedCacheError. The keep-prefix wrap roll moves a padded row's pads
  to the END of the buffer, which the prefix-only leftPadding mask cannot
  express, so zero-K/V slots would be attended until overwritten. All
  in-repo models use keep == 0; keep == 4 arises only via maxKVSize,
  which now falls back to single-stream.
- BatchKVCache.merge: precondition that all sources are KVCacheSimple
  (non-simple caches previously contributed silent all-zero rows).
- BatchRotatingKVCache.merge: precondition that no source exceeds
  maxSize — temporalState is oldest-first, so the head slice would keep
  the oldest tokens and drop the newest (Codex C4); fail loudly instead.
  Removed the stale 'exercised and tested in PR4' note (PR4's upgrade
  path uses fromSingle, not merge).
- BatchRotatingKVCache: class-doc warning documenting the keep>0 +
  left-padding limitation for direct users.

https://claude.ai/code/session_01JWyjaK32no59hZqNf4kCty
@ronaldmannak
ronaldmannak force-pushed the claude/sweet-shannon-144odn branch from b54be71 to 83fe975 Compare June 24, 2026 00:14
claude and others added 3 commits June 24, 2026 00:29
Adds a separate .github/workflows/swift.yml that builds the package (and
compiles the tests, without running them) on every pushed commit, on a
hosted Apple Silicon runner so the Metal toolchain is available.

Gated with `if: github.repository == 'PicoMLX/mlx-swift-lm'` so it runs
only on this fork and stays inert if it ever reaches upstream ml-explore,
mirroring how pull_request.yml gates its jobs to ml-explore. Kept as a
separate file from pull_request.yml so upstream syncs never conflict here.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b

@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: 000760d9e8

ℹ️ 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 +921 to +924
batchCache.keys = temporalData[0]
batchCache.values = temporalData[1]
let seqLen = min(cache.offset, ms)
batchCache._idx = seqLen

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 Keep the newest rotating window in fromSingle

When the source RotatingKVCache has offset > maxSize after a long prompt prefill, temporalState can be longer than the sliding window and is oldest-first. Copying it wholesale while setting _idx to min(offset, ms) makes state, toSingle(), and any later multi-token continuation use the first ms entries, keeping the oldest tokens instead of the newest window; this is the same over-window case that merge rejects below. Take the suffix window here or reject over-window sources before constructing the batched cache.

Useful? React with 👍 / 👎.

claude added 2 commits June 24, 2026 03:26
The first runs failed at package resolution: the macos-14 image ships
Xcode 15.4 / Swift 5.10, but Package.swift declares swift-tools-version 6.1
("using Swift tools version 6.1.0 but the installed version is 5.10.0",
exit 74). Switch to the macos-15 image and select the latest stable Xcode
(Swift 6.1+) so package resolution and the build can proceed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b
Addresses a high-severity review finding (PR #16). filter(batchIndices:)
left-shifts keys/values by minLeftPad to compact padding, but only guarded
on `keys != nil`. During chunked prefill the KV buffer can exist before the
write pointer (_idx) has advanced past the padding; shifting then drives
_idx negative and slices past the written region, keeping uninitialized
data. Require `_idx >= minLeftPad` so the shift is skipped until enough
tokens are written (state stays consistent, just un-compacted that round).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b

@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: 3b558f161a

ℹ️ 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 +231 to +234
keys = keys?[indices]
values = values?[indices]
batchOffsets = batchOffsets[indices]
leftPadding = leftPadding[indices]

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 Filter pending right-padding metadata with rows

If a request is cancelled/filtered after prepareBatched(... rightPadding:) stores _rightPadding but before finalizeBatched(), these per-row tensors are reduced while _rightPadding keeps the old batch shape and ordering. finalize() then rolls and subtracts using padding for rows that no longer exist, which can either fail shape checks or apply the wrong roll to the surviving rows; filter _rightPadding with the same indices here.

Useful? React with 👍 / 👎.

Comment on lines +643 to +646
keys = keys?[indices]
values = values?[indices]
batchOffsets = batchOffsets[indices]
leftPadding = leftPadding[indices]

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 Filter prepared rotating lengths with rows

When BatchRotatingKVCache is in a prepared right-padded prefill (_lengths is set) and rows are filtered before finalize(), _lengths remains at the original batch size/order while keys, batchOffsets, and leftPadding are indexed down. The next updateConcat/finalize computes rolls from mismatched row metadata, so surviving rows can be rolled by another row's padding or hit a shape error; _lengths should be indexed with indices here as well.

Useful? React with 👍 / 👎.

Addresses two P2 review findings (PR #16). filter(batchIndices:) reindexed
keys/values/batchOffsets/leftPadding but left the transient prepare->finalize
metadata at the pre-filter batch shape:
- BatchKVCache._rightPadding (set by prepareBatched, consumed by finalize)
- BatchRotatingKVCache._lengths (prepared right-padded prefill)

If a row is cancelled/filtered between prepareBatched(...) and finalize(),
finalize() then rolls/subtracts using padding for rows that no longer exist,
hitting a shape error or rolling surviving rows with the wrong per-row pad.
Filter both with the same indices; also clear BatchKVCache._rightPadding in
the empty-filter branch (BatchRotatingKVCache already clears _lengths there).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b

@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: 3636be44e0

ℹ️ 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 +236 to +237
if keys.dim(2) == 1 {
return updateInPlace(keys: keys, values: values)

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 Route prepared one-token prefills out of decode

When prepare(... rightPadding:) sets _lengths, a one-column update can still be a cached-prompt prefill, for example one request has one uncached token while another is fully cached and right-padded. This branch sends that valid prefill to updateInPlace, whose precondition requires _lengths == nil, so continuous batching crashes instead of finalizing the right padding; prepared one-token updates need to use the concat/finalize path rather than the decode-only path.

Useful? React with 👍 / 👎.

Comment on lines +263 to +264
if let lengths = _lengths {
let roll = MLX.maximum(MLXArray(Int32(0)), batchOffsets - lengths)

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 Account for pending padding before trimming

When a prepared cached-prompt prefill contains a fully cached row (length == 0) and another row has a multi-token suffix, _lengths is the row's real final offset, but this roll is computed before the new right-padded KV columns are appended, so batchOffsets - lengths is still zero for the fully cached row. If the rotating window is full, the following trim drops an old token even though that row added only padding; finalize() later subtracts the padding and leaves the request with one fewer valid cached token.

Useful? React with 👍 / 👎.

Comment on lines +244 to +245
lengths: MLXArray? = nil,
leftPadding: MLXArray? = nil

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 Thread batch padding through legacy masks

When Gemma2ModelInner uses the array overload createAttentionMask(h:cache: [KVCache]?), it bypasses BatchKVCache.makeMask and still calls createCausalMask with only offset, so left-padded prompt rows can attend to their pad KV slots. This new leftPadding support only fixes callers that pass the parameter or delegate through makeMask; the legacy helper needs to detect batch caches and pass their padding (or otherwise route through the batched mask path) before Gemma2/full-attention continuous batching is correct.

Useful? React with 👍 / 👎.

Comment on lines +524 to +526
if let k = keys, let v = values {
self.keys = dynamicRoll(k, shifts: padding[0..., .newAxis], axis: 2)
self.values = dynamicRoll(v, shifts: padding[0..., .newAxis], axis: 2)

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 Roll only the written KV window

For any right-padded cached-prompt prefill whose written length is smaller than the allocation step (the normal case, since update allocates 256 slots), finalize() rolls the entire backing buffer instead of just 0..<_idx. The roll moves valid KV entries past _idx, while later state, masks, and the next update still slice/write at _idx, so the request loses the tail of its cached prompt and may overwrite it on the next token; roll the populated slice or adjust _idx with the rolled buffer.

Useful? React with 👍 / 👎.

ronaldmannak pushed a commit that referenced this pull request Jun 28, 2026
Adopt PR #16's separate-file swift.yml pattern (push-triggered, hosted
macos-15, never touches the shared pull_request.yml) across all CB branches.
Park the cb-ci-enable (shared-file edit) approach as a fallback.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013zX4QEsmT3Svfo3o5fJBJK

Copy link
Copy Markdown
Owner Author

Superseded by #18 — the same cache-layer payload rebased cleanly onto current main as a fresh branch (claude/cb-1-caches), plus a separate fork-CI workflow (swift.yml). Closing this in favor of #18; keeping the branch around as a fallback. Open review threads here are carried over and tracked on #18.


Generated by Claude Code

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.

2 participants