Repository navigation
Fix ChunkedKVCache dropping valid tokens during decode (llama4) - #1673
Merged
Merged
Conversation
maybe_trim_front compared self.keys.shape[2] against chunk_size, but that is the padded buffer size (allocated in blocks of step=256), not the number of valid cached tokens. Valid tokens are front-filled at [0:offset-start_position], so once the padded buffer reached chunk_size the trim discarded live tokens and kept unfilled padding, corrupting start_position. Every llama4 decode step after the buffer crossed chunk_size then diverged from a full forward pass. Trim on the valid token count instead, keeping the most recent chunk_size valid tokens. Adds a regression test asserting incremental decode matches a single forward pass for a multi-chunk sequence.
zcbenz
force-pushed
the
fix-chunked-kv-cache-decode
branch
from
August 22, 2026 03:28
953972b to
35f851d
Compare
zcbenz
approved these changes
Aug 22, 2026
Contributor
Author
|
Thanks @zcbenz |
azamamirza
added a commit
to azamamirza/mlx-lm
that referenced
this pull request
Aug 22, 2026
Rebuilt on upstream/main d78bf58 (mlx-lm 0.32.0 line, MLX 0.32.1) rather than patched in place, per this document's own rule. DROPPED the ChunkedKVCache trim fix: upstream landed the same fix as ml-explore#1673 on 2026-08-21 with the same reasoning (trim on valid length, not buffer length) and additionally bounds the slice end. Carrying ours would leave a duplicate patch in the fleet's dependency path, which PR-LEDGER explicitly forbids. Remaining contents are the two Qwen3 MoE commits, both still absent upstream and both re-verified against d78bf58 today: model_parallel_tests 2 passed + 5 subtests, test_models -k qwen3 3 passed.
azamamirza
added a commit
to azamamirza/mlx-lm
that referenced
this pull request
Aug 27, 2026
Rebased onto upstream/main 74e7cf9 (adds ml-explore#1673 ChunkedKVCache valid-length trim — which supersedes and retires our own fix — plus ml-explore#1772 GenerationBatch filter, ml-explore#1775 decode-loop thread-safety, and new model support). Our two qwen3_moe patches (tensor-parallel ml-explore#1774 submitted, pipeline staged) ride on top unchanged and rebased clean.
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
ChunkedKVCache.maybe_trim_front(used only by Llama 4) decides how much of theKV cache to trim by comparing
self.keys.shape[2]— the padded buffer size,which is over-allocated in blocks of
step(256) — againstchunk_size. Butvalid tokens are front-filled at
[0 : offset - start_position], so once thepadded buffer reaches
chunk_sizethe trim slices off the live tokens and keepsthe unfilled padding, and
start_positionis advanced by the wrong amount.After the padded buffer crosses
chunk_size, every Llama 4 decode step thenattends over corrupted keys, so incremental generation diverges from a single
full forward pass. The generic model test only checks output shapes, so it does
not catch this. The repo's own Llama 4 test config (
attention_chunk_size=8,cache
step=256) triggers it on the first decode step; a real Llama 4(
attention_chunk_size=8192) triggers it on long contexts once the padded bufferreaches 8192.
Reproduction
With random weights, comparing a single forward pass to token-by-token decode
over a 12-token (multi-chunk) sequence,
max |Δlogit|:attention_chunk_size=4attention_chunk_size=8Position 0 (prefill) was already correct; every decoded position was wrong. A
dense control model matches to ~1e-6 both before and after, confirming the
invariant and the harness. Verified across
batch > 1, longer sequences, andseveral chunk sizes (multiple chunk-boundary crossings).
Fix
Trim on the number of valid tokens (
offset - start_position) and keep themost recent
chunk_sizevalid tokens. Those always contain the current chunk(its start is
>= offset - chunk_size), and the existing block-position maskexcludes any older tokens still in the window.
Test
Adds
test_llama4_chunked_kv_cache: builds Llama 4 with a smallattention_chunk_sizeand asserts that incremental decode matches a singleforward pass over a multi-chunk sequence. It fails on
mainand passes with thefix.
tests/test_models.pyandtests/test_prompt_cache.pyremain green.