Repository navigation
Report KV cache memory in KVCacheStatus - #639
Merged
Merged
Conversation
aleroot
force-pushed
the
alessio/kv-cache-status-bytes
branch
from
October 2, 2026 18:07
6828b88 to
c4f1e85
Compare
`KVCacheStatus` describes a cache's topology, strategy and progress, but not how much memory it holds, so an application cannot show what a conversation costs in unified memory. Two cache types count their own bytes (`TurboQuantKVCache.memoryBytes` and the internal `VarianceNormalizedKVCache.compactStorageByteCount`); the others leave callers to guess. Report it for every layer: - Add `KVCacheLayerStatus.memoryBytes`, the bytes allocated for the layer's arrays, and `KVCacheStatus.memoryBytes`, their total. Rows a cache reserves ahead of the tokens it holds are counted, since they are resident. - Count them from `innerState()`, the arrays `Evaluatable` already requires each cache to list. `nbytes` reads array metadata only, so building a status evaluates nothing and never waits on the GPU. - `TurboQuantKVCache` inherited `BaseKVCache`'s empty `innerState()`, so it reported no bytes and `asyncEval(cache)`, which chunked prefill runs after every chunk, skipped its buffers. List them, and count `memoryBytes` from the same list. - `VarianceNormalizedKVCache.innerState()` returned `state`, which slices a view of every tile on each call. Return the slabs, pending tiles and tail it stores instead: the same bytes, without work that grows with the context. Statuses are built when a turn starts, never in the token loop, and every built-in cache now lists only the arrays it stores, so the count stays cheap at any context length.
aleroot
force-pushed
the
alessio/kv-cache-status-bytes
branch
from
October 2, 2026 21:00
c4f1e85 to
82b762b
Compare
1 of 5 tasks
wballard
added a commit
to swissarmyhammer/mlx-swift-lm-old
that referenced
this pull request
Oct 7, 2026
Apply the upstream commits 55db721..ecd8e88 as a 3-way patch. CLAUDE.md is excluded. - 5e46681 Fix Jina reranker cosine scoring precision (ml-explore#651) (ml-explore#666) - c07010e Make reranker cancellation test deterministic (ml-explore#669) - 6d84ef6 Introduce component-aware checkpoint loading (ml-explore#679) - 282c2f5 Report KV cache memory in KVCacheStatus (ml-explore#639) - 0754e10 Fix Gemma tool calls losing nested object and array arguments to raw strings (ml-explore#626) - ecd8e88 Add generation observability (ml-explore#640) Conflict resolutions: - Evaluate.swift: keep discardGeneratedToken and stopTokenFedToCache of stable, and add the upstream lastLogProbabilities, evictedTokenCount, reasoningTokenCount and recordEmittedToken. handleGeneratedToken now records the emitted token and calls the upstream onToken with the log probabilities and emit. - KVCache.swift: CacheList keeps the offset and residentByteCount of stable and gets the upstream evictedTokenCount. - TurboQuantKVCache.swift: take the upstream innerState() override and memoryBytes. Remove the residentByteCount override of stable, because the base implementation now counts the same buffers through innerState(). - Load.swift: keep the async loadWeights of stable with the ModelWeightResidency raise and the dispatch to a global queue. installWeights now uses the upstream checkpoint API (loadModelCheckpoint and prepareCheckpoint) and quantizes from the per-layer plan of the checkpoint through quantizationParameters. Test changes for stable: - Gemma3nCheckpointTests and Qwen35MTPTests: loadWeights and convert are async on stable, thus the new upstream tests use await. - SpeculativeDecodingTests: the new upstream test expected a draft cache that trails by one token. On stable, finalizeGeneration() aligns the draft cache with the main cache, thus the test expects offset 3. No upstream commit in this range changes MiniMax code. Tests (xcrun xctest): MLXLMTests 1344 Swift Testing and 711 XCTest tests pass. MLXGuidedGenerationTests 70, MLXFoundationModelsTests 349, CXGrammarTests 7, MLXHuggingFaceMacrosTests 5 pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 tasks
This was referenced Oct 29, 2026
ximyro
pushed a commit
to ximyro/mlx-swift-lm
that referenced
this pull request
Nov 4, 2026
Merges upstream main (5 commits: generation observability ml-explore#640, Gemma nested tool-call arguments ml-explore#626, KV cache memory in KVCacheStatus ml-explore#639, component-aware checkpoint loading ml-explore#679, reranker test ml-explore#669). Conflicts resolved, keeping the fork behavior: - Qwen35CheckpointPolicy gains a retainMTP parameter so SwiftLM's --mtp (MTPConfig.retainMTPWeights) keeps the MTP head inside the target model. - Load.swift: lazy / expert-streaming weight loading, the MTP add-on file and per-layer quantization path normalization sit on top of upstream's ModelCheckpoint loading. - Evaluate.swift / TokenLoopHandler.swift: upstream's handler move, with the fork's Generation.chunk(tokenId:) carried over. - Tests: fork-only TokenIteratorProtocol requirements added to the new mocks. Also route ToolCallFormat.gemma4 to upstream's GemmaFunctionParser (ml-explore#626) and drop the fork's unused Gemma4FunctionParser, whose first-comma value split truncated nested objects. Co-Authored-By: Claude Sonnet 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
Expose how much memory each layer of the KV cache holds, and the total, through
KVCacheStatus. With this value an app can show what a conversation costs in unified memory while it grows, and compare the cache with the model weights and the GPU working set.Notes
Both new properties count allocated bytes:
KVCacheLayerStatus.memoryBytesKVCacheStatus.memoryBytesCaches allocate in steps (
KVCacheSimplereserves 256 rows at a time), so a three-token conversation reports a whole step: that memory is resident. A planned status reports zero: no built-in cache allocates before generation.ChatSession.cacheStatus()describes the main cache, so a speculative draft cache is not included.The count reads
innerState(), which exposed two problems:TurboQuantKVCachedid not overrideinnerState(), so it reported zero bytes andasyncEval(cache)in chunked prefill skipped its buffers.VarianceNormalizedKVCache.innerState()returnedstate, which slices one view per tile on every call. Cost per layer and call, with the same bytes before and after (M2, debug build, 8 KV heads, head dim 128, 128-token tiles):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.