Skip to content

Estimate what generation will need from a model's configuration - #852

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/estimate-from-configuration
Dec 1, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:alessio/estimate-from-configuration

Conversation

@aleroot

@aleroot aleroot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

Follow-up to #748.

estimator(parameters:) reads the caches of a loaded model, so an app can plan a conversation only after the weights are downloaded and loaded. To choose a model in the first place, for example to say whether it fits a Mac before a multi-GB download, an app needs the estimate first. Deriving the cache geometry from config.json by hand repeats per architecture what the library already knows: sliding windows, recurrent state, shared KV, latent attention.

The library can build a model from its configuration alone. The probe pass that estimator(parameters:) traces is never evaluated, so the weights don't need to exist.

Design

  • ModelTypeRegistry.estimator(configuration:parameters:), for registries of language models, so LLMTypeRegistry.shared and VLMTypeRegistry.shared both estimate from a config.json. It builds the model through the registry and traces it as LanguageModel.estimator(parameters:) traces a loaded model, so both give the same estimate. Nothing is evaluated, so the weights are never allocated.
  • It is nonisolated. The registry only creates the model; the trace runs off the actor, so an app estimating a page of search results does not hold up model loads.
  • A model built without weights holds float32 placeholders, and the caches take the precision of the activations, so every cache would double. The configuration is parsed once into the model type and the precision of its weights: torch_dtype or dtype, at the top level, then in text_config, else bfloat16. The placeholders take that precision. A precision the caches cannot take is rejected when the configuration is parsed, with a DecodingError.
  • The input is the configuration Data; how it is fetched is the app's concern.
  • The KV cache article and the skill reference show the call.

Measured on an M5 Max with 14 configurations of 12 model types, from 0.6B to 80B: Qwen3, Qwen3.5, Qwen3 MoE, Qwen3-Next, Llama (3.2 3B and 3.3 70B), Mistral, Gemma 3 text and vision-language, GPT-OSS, LFM2, Qwen2.5-VL, and one out-of-tree vision-language model.

  • No MLX memory allocated, and 12-90 ms each, of which building the model is 4-35 ms.
  • For the three models whose weights were on disk, the estimate equals the loaded model's, in full precision and in affine 4-bit.
  • For the other eleven, bytes per token equal attention layers × KV heads × head dimension × 2 × 2 bytes.
  • Without the precision step, every cache doubled.

Costs and limits

  • The precision comes from the configuration. A repository whose weights are stored in a precision other than the one its configuration declares is estimated in the declared one. An app can cross-check it against the stored precision the Hub reports for the safetensors files.
  • Like estimator(parameters:), the estimate covers the caches, not the activations of a prefill step, and not media tokens.

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:

`estimator(parameters:)` reads the caches of a loaded model, so an app can
plan a conversation only after the weights are downloaded and loaded. To
choose a model, an app needs the estimate first, and deriving the cache
geometry from `config.json` by hand repeats per architecture what the
library already knows.

Follow the model's own caches, without its weights:

- Add `ModelTypeRegistry.estimator(configuration:parameters:)` for registries
  of language models, so `LLMTypeRegistry.shared` and `VLMTypeRegistry.shared`
  estimate from a `config.json`. It builds the model through the registry and
  traces it as `LanguageModel.estimator(parameters:)` traces a loaded model.
  Nothing is evaluated, so the weights are never allocated.
- A model built without weights holds float32 placeholders, which would
  double the cache. The configuration is parsed once for its model type and
  the precision of its weights, `torch_dtype` or `dtype`, at its top level or
  in `text_config`, else `bfloat16`, and the placeholders take it. A precision
  the caches cannot take is rejected when the configuration is parsed.
- The KV cache article and the skill reference show the call.

Measured on an M5 Max with 14 configurations of 12 model types, from 0.6B to
80B (dense, mixture of experts, sliding window, gated delta, convolution, and
vision-language): no MLX memory allocated and 12-90 ms each. For the three
models whose weights were on disk, the estimate equals the loaded model's in
full precision and affine 4-bit; for the other eleven, bytes per token equal
layers x KV heads x head dimension x 2 x 2 bytes. Without the precision step
every cache doubled.
Comment on lines +103 to +107
// A model built without weights holds float32 placeholders.
model.update(
parameters: model.parameters().mapValues {
$0.dtype.isFloatingPoint ? $0.asType(declaration.precision) : $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.

Should this use the quantization code as well?

Comment on lines +101 to +102
let model = try await createModel(
configuration: configuration, modelType: declaration.modelType)

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.

Just a thought: what about the onDemandComponents? Maybe out of scope for this, but that does make a difference.

Also #708 could make a big difference in the footprint. Actually, it isn't merged yet, but I bet the estimator counts the file backed storage as it is -- it can't tell the difference between an mmap file and real memory.

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

This is an amazing idea! I think it is good to merge as-is, but see my question on quantization: that may have a big effect on the counts.

The other one about mmap and onDemandComponents is maybe future work.

A quantized model's caches take the precision of its scales, so the
estimate from a configuration matches the quantized loaded model when the
configuration declares the precision the weights are stored in. Some
repositories store another one, such as float16 scales under a declared
float32, and the estimate doubles.

- Add `precision:` to `ModelTypeRegistry.estimator(configuration:)`, so
  an app can pass the stored precision the Hub reports.
- Say in the documentation that the estimate covers the caches, not the
  weights, and that quantized weights give the precision of their scales.
- Test that the estimate matches a model with affine 4-bit weights stored
  in float16 under a configuration that declares float32.
@aleroot

aleroot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

This is an amazing idea! I think it is good to merge as-is, but see my question on quantization: that may have a big effect on the counts.

The other one about mmap and onDemandComponents is maybe future work.

Thanks!
On quantization: the estimator only covers the KV cache. Weight bytes are left to the caller (decode.bytes(tokens:weightBytes:)), so weight quantization matters only through the cache dtype, and a quantized model's cache takes the dtype of its scales. I checked Qwen3 and Qwen3.5-VL with affine 4-bit, affine 8-bit and mxfp4 weights in bfloat16: the estimate from the config matches the loaded model exactly. (One exception: mxfp4 weights in a float16 model dequantize to bfloat16, so the cache ends up float32, which a config can't show.) This logic about the weights probably belongs to the app logic, but I can think about if bringing it to the library can make sense.

The real gap is a repo whose stored precision differs from what its config declares. mlx-community/bge-m3-mlx-8bit, for example, declares float32 but stores float16 scales. For such a model the estimate comes out 2x too high. I added a commit with an optional precision: on estimator(configuration:), so an app can pass the stored precision the Hugging Face Hub reports.

On onDemandComponents and #708: both change how much memory the weights take, not the cache, and the estimate's two-token text pass never touches the vision towers. So I agree they're future work. They fit better with measuring a loaded model's weights (ModelMemory, #746). At the moment I handle that in my app, eventually I can add it in a follow-up.

@davidkoski

Copy link
Copy Markdown
Member

Ahhh, that makes sense -- for some reason I conflated the weights and the KVCache. Actually, given my recent local genai adventures the KVCache is a very hard one to estimate.

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

Very cool idea, thank you!

@davidkoski
davidkoski merged commit 072116f into ml-explore:main Dec 1, 2026
4 checks passed
@davidkoski davidkoski mentioned this pull request Dec 2, 2026
4 of 5 tasks
davidkoski added a commit that referenced this pull request Dec 2, 2026
- cnflict between #676 and #704
- conflic between #852 and #704
- NAX tolerance issues (not seen in CI but seen locally when testing)
davidkoski added a commit that referenced this pull request Dec 2, 2026
* fix CI tests on main

- cnflict between #676 and #704
- conflic between #852 and #704
- NAX tolerance issues (not seen in CI but seen locally when testing)

* Require an explicit KVCacheStart when building attention caches

#704 added `headDim: Int? = nil` to makeAttentionKVCache and a
`kvHeadDim { nil }` default on KVCacheDimensionProvider. #676's new
makeHybridAttentionKVCache call compiled without it, so dense Qwen3
silently stayed on the convert-after-prefill path.

Replace the optional with a required choice:

    public enum KVCacheStart { case compressed(headDim: Int), deferred }

- makeAttentionKVCache(parameters:start:) and
  makeHybridAttentionKVCache(parameters:slidingWindow:usesSlidingWindow:start:)
  take it with no default. The released signatures without `start:`
  remain as deprecated overloads that pass `.deferred`.
- KVCacheDimensionProvider.kvCacheStart replaces kvHeadDim. Its default,
  `.deferred`, is deprecated, so a conformer that relies on it gets a
  warning.
- Every in-repo call site and conformer states its choice. The models
  that start compressed are the ones that did before: Llama, Qwen2,
  Qwen3, Qwen3-MoE, Qwen3.5, GLM4, Gemma 3 and Falcon-H1.

`headDim:` and `kvHeadDim` were never in a release (3.33.0 predates
#704), so they are replaced rather than deprecated.

* Show kvCacheStart in the model templates and test the deprecated path

The porting guides and the skill's model template conformed to
KVCacheDimensionProvider without kvCacheStart, so a model copied from them
would warn. They now declare it: the skill template attends through
attentionWithCacheUpdate and starts compressed, the others start deferred.

deprecatedCacheFactoriesStartDeferred checks that the released signatures
and the protocol default still build full-precision caches under kvBits 4.

---------

Co-authored-by: David Koski <dkoski@apple.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