Repository navigation
Settle the KV cache state every 256 decode steps, not every step - #851
Merged
davidkoski merged 1 commit intoDec 1, 2026
Merged
Conversation
davidkoski
approved these changes
Dec 1, 2026
davidkoski
left a comment
Member
There was a problem hiding this comment.
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!
3 of 5 tasks
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>
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.
Proposed changes
TokenIterator.next()evaluates the whole KV cache state with every decoded token: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)ingenerate.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 == 0drives both the state evaluation and the existingclearCache().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:
MLX active memory after decode, gemma-4-26b-a4b-it-4bit (2,040 steps, not a settle step):
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
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.