Skip to content

Report KV cache memory in KVCacheStatus - #639

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/kv-cache-status-bytes
Oct 5, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/kv-cache-status-bytes

Conversation

@aleroot

@aleroot aleroot commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

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:

Property Meaning
KVCacheLayerStatus.memoryBytes bytes allocated for one layer's arrays
KVCacheStatus.memoryBytes the total across all layers

Caches allocate in steps (KVCacheSimple reserves 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:

  • TurboQuantKVCache did not override innerState(), so it reported zero bytes and asyncEval(cache) in chunked prefill skipped its buffers.
  • VarianceNormalizedKVCache.innerState() returned state, 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):
Context Before After
2K 1.85 ms 6.7 µs
8K 7.38 ms 4.3 µs
32K 29.5 ms 2.8 µs

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:

`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.

@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 good, thank you!

@davidkoski
davidkoski merged commit 282c2f5 into ml-explore:main Oct 5, 2026
5 checks passed
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>
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>
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