Repository navigation
Estimate what generation will need from a model's configuration - #852
Conversation
`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.
| // A model built without weights holds float32 placeholders. | ||
| model.update( | ||
| parameters: model.parameters().mapValues { | ||
| $0.dtype.isFloatingPoint ? $0.asType(declaration.precision) : $0 | ||
| }) |
There was a problem hiding this comment.
Should this use the quantization code as well?
| let model = try await createModel( | ||
| configuration: configuration, modelType: declaration.modelType) |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
Thanks! The real gap is a repo whose stored precision differs from what its config declares. 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 ( |
|
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
left a comment
There was a problem hiding this comment.
Very cool idea, thank you!
* 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>
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 fromconfig.jsonby 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, soLLMTypeRegistry.sharedandVLMTypeRegistry.sharedboth estimate from aconfig.json. It builds the model through the registry and traces it asLanguageModel.estimator(parameters:)traces a loaded model, so both give the same estimate. Nothing is evaluated, so the weights are never allocated.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.torch_dtypeordtype, at the top level, then intext_config, elsebfloat16. The placeholders take that precision. A precision the caches cannot take is rejected when the configuration is parsed, with aDecodingError.Data; how it is fetched is the app's concern.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.
Costs and limits
estimator(parameters:), the estimate covers the caches, not the activations of a prefill step, and not media tokens.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.