Repository navigation
Estimate what generation will need from a model's configuration #852
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
davidkoski
merged 2 commits into
ml-explore:main
from
aleroot:alessio/estimate-from-configuration
Dec 1, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,8 @@ | ||
| // Copyright © 2024 Apple Inc. | ||
|
|
||
| import Foundation | ||
| import MLX | ||
| import MLXNN | ||
|
|
||
| public actor ModelTypeRegistry<T> { | ||
|
|
||
|
|
@@ -68,3 +70,91 @@ public actor ModelTypeRegistry<T> { | |
| } | ||
|
|
||
| } | ||
|
|
||
| extension ModelTypeRegistry where T == any LanguageModel { | ||
| /// Estimate what generation will need with the model a `config.json` describes, | ||
| /// before its weights are downloaded. | ||
| /// | ||
| /// The estimate covers the caches. The weights are the caller's to count, as in | ||
| /// ``GenerationEstimator/Decode/bytes(tokens:weightBytes:)``. | ||
| /// | ||
| /// The model is built from `configuration` without weights and traced as | ||
| /// ``LanguageModel/estimator(parameters:)`` traces a loaded model, so both give the | ||
| /// same estimate. Nothing is evaluated, so the weights are never allocated. | ||
| /// | ||
| /// The caches hold keys and values in the precision of the weights, or of their | ||
| /// scales when they are quantized. The configuration declares it as `torch_dtype` | ||
| /// or `dtype`, at its top level or in its `text_config`. A configuration that | ||
| /// declares none is taken as `bfloat16`. Some repositories store another precision | ||
| /// than they declare: pass the stored one as `precision`. | ||
| /// | ||
| /// ```swift | ||
| /// // A config.json from a model repository, a few kilobytes. | ||
| /// let (configuration, _) = try await URLSession.shared.data(from: configurationURL) | ||
| /// let estimator = try await LLMTypeRegistry.shared.estimator(configuration: configuration) | ||
| /// let maxTokens = estimator.cache.maxTokens(fittingIn: budgetBytes) | ||
| /// ``` | ||
| /// | ||
| /// - Parameters: | ||
| /// - configuration: The contents of a `config.json`. | ||
| /// - precision: The precision the weights are stored in, when it differs from the | ||
| /// one the configuration declares. | ||
| /// - parameters: The parameters generation will use. | ||
| /// - Throws: `DecodingError` when the configuration has no `model_type` or declares | ||
| /// a precision other than `float16`, `bfloat16`, or `float32`, | ||
| /// ``ModelFactoryError/invalidConfiguration(_:)`` when `precision` is not one of | ||
| /// them, and ``ModelFactoryError/unsupportedModelType(_:)`` when no creator | ||
| /// accepts the configuration. | ||
| public nonisolated func estimator( | ||
| configuration: Data, precision: DType? = nil, parameters: GenerateParameters? = nil | ||
| ) async throws -> GenerationEstimator { | ||
| let declaration = try JSONDecoder.json5().decode( | ||
| ModelDeclaration.self, from: configuration) | ||
| let precision = precision ?? declaration.precision | ||
| guard [.float16, .bfloat16, .float32].contains(precision) else { | ||
| throw ModelFactoryError.invalidConfiguration( | ||
| "A model in \(precision) cannot be estimated.") | ||
| } | ||
| let model = try await createModel( | ||
| configuration: configuration, modelType: declaration.modelType) | ||
| // A model built without weights holds float32 placeholders. | ||
| model.update( | ||
| parameters: model.parameters().mapValues { | ||
| $0.dtype.isFloatingPoint ? $0.asType(precision) : $0 | ||
| }) | ||
|
Comment on lines
+120
to
+124
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this use the quantization code as well? |
||
| return try model.estimator(parameters: parameters) | ||
| } | ||
| } | ||
|
|
||
| /// What a `config.json` declares about its model: the architecture, and the precision | ||
| /// of the weights. | ||
| private struct ModelDeclaration: Decodable { | ||
| let modelType: String | ||
| let precision: DType | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case modelType = "model_type" | ||
| case torchDType = "torch_dtype" | ||
| case dtype | ||
| case textConfig = "text_config" | ||
| } | ||
|
|
||
| init(from decoder: any Decoder) throws { | ||
| let container = try decoder.container(keyedBy: CodingKeys.self) | ||
| let text = try? container.nestedContainer(keyedBy: CodingKeys.self, forKey: .textConfig) | ||
| func declared(in container: KeyedDecodingContainer<CodingKeys>?) throws -> String? { | ||
| try container?.decodeIfPresent(String.self, forKey: .torchDType) | ||
| ?? container?.decodeIfPresent(String.self, forKey: .dtype) | ||
| } | ||
| modelType = try container.decode(String.self, forKey: .modelType) | ||
| switch try declared(in: container) ?? declared(in: text) ?? "bfloat16" { | ||
| case "bfloat16": precision = .bfloat16 | ||
| case "float16": precision = .float16 | ||
| case "float32": precision = .float32 | ||
| case let name: | ||
| throw DecodingError.dataCorruptedError( | ||
| forKey: .torchDType, in: container, | ||
| debugDescription: "A model in \(name) cannot be estimated.") | ||
| } | ||
| } | ||
| } | ||
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
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
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.