Skip to content

Settle the KV cache state every 256 decode steps, not every step - #851

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/settle-cache-periodically
Dec 1, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/settle-cache-periodically

Conversation

@aleroot

@aleroot aleroot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

TokenIterator.next() evaluates the whole KV cache state with every decoded token:

asyncEval([token] + cache.flatMap { $0.state })

A step's cache update already feeds the next token, so evaluating the token settles it. mlx-lm evaluates only the token and its log probabilities while decoding (mx.async_eval(next_y, next_logprobs) in generate.py); it evaluates [c.state for c in prompt_cache] only during prefill. Evaluating every cache array on each step costs 0.3–0.5 ms per token.

This change evaluates the cache state with the token every 256 tokens, on the step where the loop already calls Memory.clearCache():

  • settles = tokenCount % 256 == 0 drives both the state evaluation and the existing clearCache().
  • Other steps evaluate the token and, when requested, the deferred log probabilities.
  • The comment no longer says that mlx-lm settles cache state on every decode step.

Why settle at all

None of the caches I measured needs it: evaluating only the token, as mlx-lm does, holds the same memory as evaluating the state on every step (table below). The periodic settle is a bound for a cache whose state is written during decode but not read by the next token. Such state is never evaluated by the token's graph, so without a settle its update chain would grow for the whole reply. Settling on the step that already calls clearCache() keeps that bound at no measurable cost.

Measured results

Release, M6 32 GB, greedy decoding, 2K-token prompt. Generated tokens are identical in every run.

Decode time, ms per token:

Model Context Cache Every step Every 256 steps
gemma-4-26b-a4b-it-4bit 2K full precision 19.75 19.38
affine 8-bit 21.17 20.71
TurboQuant 8/3 19.86 19.50
variance-normalized 4/2 25.03 24.61
LFM3-1.7B-MLX-bf16 8K full precision 24.47 23.98
affine 8-bit 24.21 23.92
TurboQuant 8/3 27.18 27.04
variance-normalized 4/2 29.85 29.00
Ternary-Bonsai-2.5-27B-mlx-2bit 2K full precision 56.60 56.36

MLX active memory after decode, gemma-4-26b-a4b-it-4bit (2,040 steps, not a settle step):

Cache Every step Token only Every 256 steps
full precision 14,915 MB 14,915 MB 14,915 MB
TurboQuant 8/3 14,955 MB 14,955 MB 14,955 MB
variance-normalized 4/2 14,894 MB 14,894 MB 14,894 MB

Memory is read after a later evaluation has run. MLX returns a step's temporary buffers only after that step's command buffer completes, so a reading taken right after the last token includes them and can differ by tens of MB between runs.

Building the state list is not the cost: it takes 1–70 µs per step. The cost is evaluating the extra arrays.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure:

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks like an interesting change. I wonder if there is any use for caller control over this? maybe via GenerateParameters? I guess if the case comes up it is easy enough to add.

Thanks!

@davidkoski
davidkoski merged commit f38d0d6 into ml-explore:main Dec 1, 2026
3 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm that referenced this pull request Dec 6, 2026
Apply the upstream commits 264d1e3..d8d2de2 (the 38 after 026d599) as
cherry-picks. Where upstream and the fork disagree, the fork's code is kept.
CLAUDE.md is untouched. 25 commits are taken (some in part), 13 are skipped.

Taken:
- 264d1e3 Report unparsable Onyx tool frames as rejected tool calls (ml-explore#842)
- 876ae8f Report whether a reranker reads the request instruction (ml-explore#838)
- 0a4facd Add Ricursive (Ripple-65B) text model (ml-explore#789)
- 1ca761b Retire CompositeLogitProcessor in favor of ChainedLogitProcessor (ml-explore#844)
- cc1fcf8 Estimate what generation will need before it runs (ml-explore#748)
- 127bd1c use MaterializedArray for Sendable conformance - part 1 (ml-explore#810)
- 8a87065 Add Inkling 2 Mini and Small (ml-explore#821), general parts only
- 5fe817b Qwen2-VL, Qwen2.5-VL: fused RoPE for M-RoPE decode (ml-explore#839)
- c0f3a9f Fix StreamingDetokenizer U+FFFD hold check after Prepend scalars (ml-explore#832)
- d06a727 Implement reranker protocols for Qwen3-based rerankers (ml-explore#676)
- 072116f Estimate what generation will need from a model's configuration (ml-explore#852)
- 7bfcd7a Accept rope_type "proportional" in LFM3 configs (ml-explore#847)
- 1703b34 Mark LFM2.5-24B-A2B as reasoning and skip LFM2.5 Base checkpoints (ml-explore#846)
- d8b2841 Start quantized KV caches at token 0 when the model declares its head dim (ml-explore#704)
- f6b6bfe Add LiquidAI LFM3-VL image and video input support (ml-explore#781)
- 11169ed Make the KV cache start explicit with KVCacheStart (ml-explore#858)
- d5d4b3f Llama and Qwen3 MLP: run SwiGLU as one compiled kernel (ml-explore#854)
- 4ead844 Prefill over a compressed TurboQuant cache through the fused SDPA kernel (ml-explore#717)
- 47c4dcf Use compiled swiGLU across remaining LLM and VLM MLPs (ml-explore#863)
- 500e07c switch integration tests to greedy logit sampling (ml-explore#853)
- 0570424 use different audio load path that does not engage the mixer (ml-explore#867)
- 96eb212 Add reversible component and session cache eviction (ml-explore#713)
- ebc444c Keep GPT-OSS attention sinks with a quantized KV cache (ml-explore#794)
- 18713a4 MLXVLM: add Qwen3-VL text and image embeddings (ml-explore#665)
- 1a1c979 Recovery: an unclosed reasoning span that opens on a tool call dispatches it (ml-explore#707)

Conflict resolutions:
- ml-explore#821: the fork keeps its own Inkling 2 (tensor parallel, cluster, OMLX
  layout). Taken: CheckpointNameMapping.replaceMatches and the numParameters
  fix. Not taken: upstream's Inkling files, DirectAttentionKVCache,
  ConvolutionStatesCache, RotatingKVCacheLayout, CacheList round staging and
  the MTP speculative-sampling changes.
- ml-explore#748: the fork's remote-cache quantization stays; compressionStart is
  threaded into the local application. The estimator treats a RemoteKVCache
  leaf as not estimated here.
- ml-explore#704/ml-explore#858: Qwen 3.5/3.8 declares kvCacheStart .compressed, as upstream
  does, so a strategy that compresses from token 0 starts compressed. The
  fork-only conformers (DeepSeek-V4, Flint, Qwen4Exp, Inkling 2, MiniMax-M3,
  test fakes) declare .deferred, which keeps their behavior. The quantized
  prefill test goes into KVCacheQuantizationTests.
- ml-explore#863: the fork's Qwen 3.5, Qwen3-Next and Qwen4Exp MLPs keep their own form.
- ml-explore#676: the weight-file listing resolves symbolic links, but an absent
  directory still lists as empty (the fork's contract); upstream's
  listing-error test is not taken.
- ml-explore#713: ChatSession.evict() and ChatSessionError.noHistoryAvailable are
  ported onto the fork's session. Six of upstream's evict tests run; the
  seven that need upstream-only fixtures are not taken.
- ml-explore#789: RicursiveCheckpointTests (IntegrationTesting) builds against the
  fork's async loadWeights.
- ml-explore#665, ml-explore#713, ml-explore#789, ml-explore#781: tests that call the fork's async loadWeights are
  async.
- ml-explore#854: float32 SwiGLU fusion matches within a few ULP; the fork's MLX
  fuses the sigmoid differently in float32. Half precision stays bit-equal.

Skipped:
- 3db6705 ml-explore#845, 3d8891a ml-explore#848, f88d37e ml-explore#834: built on upstream's ChatSession
  checkpoints; the fork's checkpoints already cover the instructions segment.
- bd3c2ba ml-explore#840: the fork already compiles the Qwen 3.5 MTP verify step.
- a390d50 ml-explore#818: the fork has its own qwen4_exp. Upstream's right-padded GDN
  conv-state fix for batched rows is not taken.
- f38d0d6 ml-explore#851: the fork's TokenIterator settles the cache each step through
  evaluationState, which adds no op.
- 0e4e170 ml-explore#825: the fork's MTP iterator already accepts sampled drafts with
  the probability ratio at any temperature. LFM2 DSpark stays greedy.
- dec056a ml-explore#837, 5be3fec ml-explore#868: the fork keeps registerDrafter; drafters still
  register explicitly.
- 4ca1bf6 ml-explore#861: for upstream's Inkling 2.
- Port candidates: 4ad95e8 ml-explore#864 (log probabilities before the processors),
  f718469 ml-explore#827 (cache reuse on text turns after an image turn), d8d2de2 ml-explore#843
  (tool calls while the step generates). Each lives in upstream's
  ChatSession or TokenIterator code, which the fork rewrote.

After-merge steps: no merged model adds advance( with a manual offset +=.
LFM3-VL (lfm3_vl, ArraysCache through LFM3) is added to
HybridRecurrentCacheOffsetTests. No merged test is gated on the environment.

Tests: all five bundles pass under xctest (MLXLMTests 1409 XCTest + 3298
Swift Testing, MLXGuidedGenerationTests 97, MLXFoundationModelsTests 779,
CXGrammarTests 7, MLXHuggingFaceMacrosTests 11). The IntegrationTesting
suites Qwen35SessionPromptCacheTests (7), Qwen35AgenticPromptCacheAssessmentTests
(3) and PromptCacheSpoolCostAssessmentTests (5) pass, each run alone; run
together, the suites share TestModelManager and one unloads a model another
uses. RicursiveCheckpointTests keeps its environment gate: its only checkpoint
is the 65B ricursiveAI/Ripple-65B-Preview.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants