Skip to content

Estimate what generation will need before it runs - #748

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/kv-cache-memory-estimate
Nov 30, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/kv-cache-memory-estimate

Conversation

@aleroot

@aleroot aleroot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

An application can read what a conversation's KV cache holds now (KVCacheStatus.memoryBytes, #639) and what the model holds (memory(), #746), but not what a conversation will need before it starts. Choosing a context length against a memory budget means deriving the cache geometry from the model configuration, which every application repeats, and gets wrong for sliding windows, recurrent state, and compressed caches. #737 made the Qwen 3.5 geometry readable for that reason, one architecture at a time.

Estimate the cache from the model's own caches instead:

  • LanguageModel.estimator(parameters:) and ModelContainer.estimator(parameters:) return a GenerationEstimator. The default implementation traces one forward pass without evaluating it and reads the shapes of the caches from newCache(parameters:), so the estimate follows the model rather than a configuration. Two tokens take the prefill path, so a compiled decode stays untouched. Compressed layers are measured on synthetic keys and values written into a throwaway cache.
  • GenerationEstimator.cache is what the cache will hold as the context grows: bytes(tokens:) for a context length, maxTokens(fittingIn:) for the longest context that fits a budget, and layers for the breakdown, one entry per cache layer, with its bytes per token, fixed bytes, and capacity.
  • GenerationEstimator.decode is what one decoded token reads: the cache it attends to, plus the weights. The weight bytes come from the caller, because a mixture-of-experts model reads only the experts it routes to, and a vision tower is not read while decoding text.
let estimator = try await container.estimator(parameters: parameters)
let weights = try await container.memory().total          // #746
let available = gpuBudget - weights
let contextLength = estimator.cache.maxTokens(fittingIn: available) ?? modelContextLength
let perToken = estimator.decode.bytes(tokens: contextLength, weightBytes: weights)

Together with KVCacheStatus.memoryBytes and memory(), an app can now assess what a conversation will cost before it starts, and project a decode speed from the memory bandwidth of the machine.

The layers of a target model and its drafter combine into one estimate:

let combined = GenerationEstimator(cache: .init(layers: target.cache.layers + drafter.cache.layers))

Notes

The estimate is checked against a generated cache, layer by layer, for dense, sliding-window, recurrent, latent-attention, shared-KV, and vision-language models. It matches exactly for full precision. Affine caches grow by one step on their first decode write, so they may hold up to 256 tokens more than the estimate.

The estimate describes one sequence, not a batch. The weights are not included: memory() (#746) measures those.

The KV cache article and the wired-memory article now point at the estimator instead of a hand-written formula, and the skill reference shows how to read the layers.

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:

An application can read how much memory a conversation's KV cache holds
(`KVCacheStatus.memoryBytes`), but not what a conversation will need before
it starts. Choosing a context length against a memory budget means deriving
the cache geometry from the model configuration, which every application
repeats and gets wrong for sliding windows, recurrent state, and compressed
caches.

Follow the model's own caches instead:

- Add `GenerationEstimator`, with a `cache` and a `decode` result.
  `cache.bytes(tokens:)` is what the cache will hold at a context length,
  `cache.maxTokens(fittingIn:)` the longest context that fits a budget, and
  `decode.bytes(tokens:weightBytes:)` what one decoded token reads.
- Add `LanguageModel.estimator(parameters:)` and
  `ModelContainer.estimator(parameters:)`. The default implementation traces
  one forward pass without evaluating it and reads the shapes of the caches
  from `newCache(parameters:)`. Compressed layers are measured on synthetic
  keys and values.
- The weight bytes come from the caller: a mixture-of-experts model reads
  only the experts it routes to, and a vision tower is not read while
  decoding text.
- The cache traffic of a decode step leaves out a rotating layer's rewind
  reserve, which is stored but not attended.
- The KV cache article and the wired-memory article now point at the
  estimator instead of a hand-written formula.
Comment on lines +291 to +292
applyKVCacheConfigurationFast(
cache: &cache, configuration: configuration, compressionStart: 0)

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.

I think there is a gap between this and real configurations. It might just be a documentation issue rather than a code change.

  • as written, this assume that compression starts from the first token

    • mlx-lm uses 5000 as a default
    • on Llama 3.1 8b this undercounts by ~450M up to that point (something like that, i had claude estimate it)
    • and briefly both the uncompressed and compressed will exist as the latter is being built
  • prefill costs might be significantly higher as the compression is not applied

    • does the estimate need to consider this? it seems like a different estimate at the very least, but perhaps just document that it doesn't cover it
    • I wonder if we need more configuration around prefill so applications can tune for performance or memory? (a separate issue, just something this PR makes me thing about)
    • over the last week I was playing with local genAI coding agents and the prefill turned out to be a big deal -- if it wasn't configured correctly it happened too often (like every turn) and was very large (I had up to 128k token contexts)

See what you think

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You're right, and it was more than a docs gap. The estimate charged compressed bytes from the first token, but generation only compresses after a prefill or decode step. So even with start 0, a long first prompt lands in full precision first. I measured the conversion on 268 MB of fp16 cache: affine peaks at exactly full precision + compressed (344 MB), and TurboQuant, which compresses on its first decode write, at 374 MB. I kind of fixed it. Two things it doesn't cover: prefill activations, and the working memory of the conversion itself. Variance normalization uses float32 temporaries and peaked around 748 MB in the same test. Converting layer by layer in the runtime would bound both transients. I'd do that, and the prefill tuning you mentioned, in a separate issue if possible

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.

Sounds good!

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

Please take a look at my comment -- I think the code here looks good and is ready to merge. Maybe we need to think about this in followups or adjust the docs? Let me know how you want to proceed.

Thanks!

The estimate charged compressed bytes from the first token. Generation keeps
a layer in full precision until it holds more than its compression start,
and compresses only after a prefill or decode step, so a prompt that crosses
the start lands in full precision and both copies coexist while it converts.

Layers now carry their compression start and full-precision rate, and
bytes(tokens:) follows the runtime. peakBytes(tokens:promptTokens:) adds the
conversion, counting every layer a prompt may still be converting, and
maxTokens(fittingIn:promptTokens:) searches the peak, which grows
monotonically where the held bytes drop at the start. The working memory of
the conversion itself is not included; variance normalization needs float32
temporaries on top.
@davidkoski
davidkoski merged commit cc1fcf8 into ml-explore:main Nov 30, 2026
4 checks passed
aleroot added a commit to aleroot/mlx-swift-lm that referenced this pull request Dec 2, 2026
…ling

Follow-up to ml-explore#748. A compressed cache converted every layer in one graph,
and the runtime kept the full-precision leaves until it returned, so the
whole cache existed twice while it converted. A long first prompt also
landed in full precision whole, because generation compressed only after
the prefill. The estimate described that, but the runtime could do better.

Design

- Each converted layer is evaluated before the next converts, and
  applyKVCacheConfigurationValidated and maybeTurboQuantizeKVCache no
  longer hold the old leaves, so one layer holds both copies at a time.
- PrefillParameters.cacheCompression chooses when an affine cache
  compresses a prompt that crosses its start. .whilePrefilling, the
  default, stops the prefill right after the start, compresses, and writes
  the rest of the prompt compressed, like mlx-lm. It reuses the prefill
  split of prompt checkpoints, in TokenIterator and
  SpeculativeTokenIterator. .afterPrefill keeps the previous behaviour.
  Prompts with media, non-balanced chunking, and the MTP and block
  diffusion iterators compress after the prefill.
- GenerationEstimator follows both: peakBytes converts layers in order,
  and Cache.prefillCompression says when a prompt compresses.
- Layer.checkpoint and checkpointBytes(tokens:) estimate what a
  ChatSession prompt checkpoint copies: sliding windows, recurrent state,
  a requested capacity once it evicts, and an incomplete
  variance-normalized tile. An app sizing a session against memory missed
  them before.

Measured on an M5 Max, release build:

- Converting a 32k cache on Qwen3-Reranker-0.6B-4bit, peak: affine
  5.16 -> 4.39 GB, TurboQuant 5.51 -> 4.42 GB. Variance normalization is
  unchanged at 5.87 GB: its peak is the float32 working memory of one
  layer, which the estimate still leaves out.
- 32k affine prefill on the same model: peak 4.2 -> 2.4 GB above the
  weights, same speed.

Costs and limits

- On head dim 256 (Qwen3.8-27B-4bit, 8k prompt) the prompt past the start
  attends through quantized matmuls: +190 MB peak and 10% slower prefill.
  .afterPrefill turns it off.
- TurboQuant and variance normalization always compress after the
  prefill. Compressing them while prefilling was 13-18x slower and peaked
  higher.

Tests check that the split matches two generations that end at the start,
that both speculative caches compress, that a layer is freed before the
next converts, and that checkpointBytes matches real checkpoints for
sliding windows, recurrent state, a requested capacity and variance
normalization.

AI usage: Filo, an AI coding assistant, wrote the code, tests and this
message, and ran the unit tests, the DocC check and the measurements.
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