Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Libraries/MLXLMCommon/Documentation.docc/kv-cache-quantization.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,24 @@ let peak = estimator.cache.peakBytes(tokens: 32_768, promptTokens: 4_096)
The estimate covers the cache, not the activations of a prefill step, which grow
with ``PrefillParameters/stepSize``.

To choose a model before its weights are downloaded, estimate it from its
`config.json`.
``ModelTypeRegistry/estimator(configuration:precision:parameters:)`` builds the
model without weights and traces it as a loaded model is traced, so both give the
same estimate. Nothing is evaluated, so the weights are never allocated:

```swift
let estimator = try await LLMTypeRegistry.shared.estimator(configuration: configData)
let maxTokens = estimator.cache.maxTokens(fittingIn: budgetBytes)
```

The caches hold keys and values in the precision of the weights, which the
configuration declares as `torch_dtype` or `dtype`, at its top level or in its
`text_config`. A configuration that declares none is taken as `bfloat16`. For
quantized weights it is the precision of their scales. Some repositories store
another precision than they declare; pass the stored one as `precision`. Use
`VLMTypeRegistry.shared` for a vision-language model.

``KVCacheStatus/memoryBytes`` is the measured counterpart: the bytes a cache
holds now. Each ``GenerationEstimator/Cache/Layer`` has its bytes per token,
fixed bytes, and capacity. Combine layers from several models, such as a target
Expand Down
90 changes: 90 additions & 0 deletions Libraries/MLXLMCommon/Registries/ModelTypeRegistry.swift
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> {

Expand Down Expand Up @@ -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)
Comment on lines +118 to +119

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.

// 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

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?

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.")
}
}
}
170 changes: 131 additions & 39 deletions Tests/MLXLMTests/GenerationEstimatorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import Foundation
import MLX
import MLXLLM
import MLXNN
import Testing

@testable import MLXLMCommon
Expand All @@ -16,17 +17,21 @@ import Testing

/// Six full-attention layers, so TurboQuant protects two layers at each end.
private func qwen3() throws -> Qwen3Model {
Qwen3Model(
try decode(
Qwen3Configuration.self,
"""
{
"hidden_size": 64, "num_hidden_layers": 6, "intermediate_size": 64,
"num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 64,
"rms_norm_eps": 1e-6, "vocab_size": 32, "rope_theta": 10000.0,
"tie_word_embeddings": true
}
"""))
Qwen3Model(try decode(Qwen3Configuration.self, qwen3Configuration()))
}

/// The `config.json` of ``qwen3()``, with `fields` added at its top level.
private func qwen3Configuration(_ fields: String = "") -> String {
"""
{
\(fields)
"model_type": "qwen3",
"hidden_size": 64, "num_hidden_layers": 6, "intermediate_size": 64,
"num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 64,
"rms_norm_eps": 1e-6, "vocab_size": 32, "rope_theta": 10000.0,
"tie_word_embeddings": true
}
"""
}

/// Sliding-window and full-attention layers.
Expand Down Expand Up @@ -117,35 +122,38 @@ import Testing

/// A vision-language model with gated-delta layers and compiled decode.
private func qwen35VLM() throws -> Qwen35 {
Qwen35(
try decode(
Qwen35Configuration.self,
"""
{
"model_type": "qwen3_5_vl", "image_token_id": 500, "video_token_id": 501,
"vision_start_token_id": 502, "vision_end_token_id": 503,
"vocab_size": 512,
"text_config": {
"model_type": "qwen3_5", "hidden_size": 64, "num_hidden_layers": 4,
"intermediate_size": 128, "num_attention_heads": 4,
"num_key_value_heads": 2, "head_dim": 32, "vocab_size": 512,
"full_attention_interval": 2, "linear_num_value_heads": 4,
"linear_num_key_heads": 2, "linear_key_head_dim": 32,
"linear_value_head_dim": 32, "linear_conv_kernel_dim": 4,
"max_position_embeddings": 4096,
"rope_parameters": {
"type": "default", "mrope_section": [8, 4, 4],
"rope_theta": 100000.0, "partial_rotary_factor": 1.0
}
},
"vision_config": {
"model_type": "qwen3_vl", "depth": 2, "hidden_size": 32,
"intermediate_size": 64, "out_hidden_size": 64, "num_heads": 2,
"patch_size": 16, "spatial_merge_size": 2, "temporal_patch_size": 2,
"num_position_embeddings": 64
}
Qwen35(try decode(Qwen35Configuration.self, qwen35VLMConfiguration()))
}

/// The `config.json` of ``qwen35VLM()``, with `fields` added to its `text_config`.
private func qwen35VLMConfiguration(textFields fields: String = "") -> String {
"""
{
"model_type": "qwen3_5", "image_token_id": 500, "video_token_id": 501,
"vision_start_token_id": 502, "vision_end_token_id": 503,
"vocab_size": 512,
"text_config": {
\(fields)
"model_type": "qwen3_5", "hidden_size": 64, "num_hidden_layers": 4,
"intermediate_size": 128, "num_attention_heads": 4,
"num_key_value_heads": 2, "head_dim": 32, "vocab_size": 512,
"full_attention_interval": 2, "linear_num_value_heads": 4,
"linear_num_key_heads": 2, "linear_key_head_dim": 32,
"linear_value_head_dim": 32, "linear_conv_kernel_dim": 4,
"max_position_embeddings": 4096,
"rope_parameters": {
"type": "default", "mrope_section": [8, 4, 4],
"rope_theta": 100000.0, "partial_rotary_factor": 1.0
}
"""))
},
"vision_config": {
"model_type": "qwen3_vl", "depth": 2, "hidden_size": 32,
"intermediate_size": 64, "out_hidden_size": 64, "num_heads": 2,
"patch_size": 16, "spatial_merge_size": 2, "temporal_patch_size": 2,
"num_position_embeddings": 64
}
}
"""
}

/// The cache after a real prefill and one decode step, `tokens` positions in total.
Expand Down Expand Up @@ -425,4 +433,88 @@ import Testing
combined.decode.bytes(tokens: 512, weightBytes: 0) == 2
* target.cache.bytes(tokens: 512))
}

// MARK: - Estimating from a configuration

/// `model` with its weights in `precision`, evaluated as a loaded model's are.
private func loaded<M: LanguageModel>(
_ model: M, in precision: DType, quantizedAs mode: QuantizationMode? = nil
) -> M {
model.update(parameters: model.parameters().mapValues { $0.asType(precision) })
if let mode {
MLXNN.quantize(model: model) { _, module in
module is Linear || module is Embedding ? (32, 4, mode) : nil
}
}
eval(model)
return model
}

@Test func configurationMatchesTheLoadedModel() async throws {
let configuration = Data(qwen3Configuration(#""torch_dtype": "bfloat16","#).utf8)

let estimate = try await LLMTypeRegistry.shared.estimator(configuration: configuration)
let generated = try expectEstimateMatchesGeneration(
loaded(qwen3(), in: .bfloat16), parameters: .init())

#expect(estimate.cache == generated)
}

@Test func configurationOfAHybridVisionModelMatchesTheLoadedModel() async throws {
let configuration = Data(qwen35VLMConfiguration(textFields: #""dtype": "float16","#).utf8)
let affine = GenerateParameters(
kvCache: KVCacheConfiguration(strategy: .affine(try .init(bits: 4, groupSize: 32))))

let estimate = try await VLMTypeRegistry.shared.estimator(
configuration: configuration, parameters: affine)
let generated = try expectEstimateMatchesGeneration(
loaded(qwen35VLM(), in: .float16), parameters: affine, allowingStepSlack: true)

#expect(estimate.cache == generated)
}

@Test func configurationMatchesAQuantizedModelInItsStoredPrecision() async throws {
// Declared in float32, stored in float16, as some converted repositories are.
let configuration = Data(qwen3Configuration(#""torch_dtype": "float32","#).utf8)

let declared = try await LLMTypeRegistry.shared.estimator(configuration: configuration)
let stored = try await LLMTypeRegistry.shared.estimator(
configuration: configuration, precision: .float16)
let generated = try expectEstimateMatchesGeneration(
loaded(qwen3(), in: .float16, quantizedAs: .affine), parameters: .init())

#expect(stored.cache == generated)
#expect(declared.cache.bytesPerToken == 2 * generated.bytesPerToken)
}

@Test(arguments: [
(#""torch_dtype": "float32","#, 4),
(#""torch_dtype": "float16","#, 2),
(#""dtype": "bfloat16","#, 2),
("", 2),
])
func configurationDeclaresThePrecisionOfTheCache(field: String, bytes: Int) async throws {
let configuration = Data(qwen3Configuration(field).utf8)

let estimate = try await LLMTypeRegistry.shared.estimator(configuration: configuration)

// One KV head of 64 values for keys and values.
#expect(estimate.cache.layers.allSatisfy { $0.bytesPerToken == 2 * 64 * bytes })
}

@Test func configurationThatCannotBeEstimatedThrows() async throws {
let unknownPrecision = Data(qwen3Configuration(#""torch_dtype": "int8","#).utf8)
let unknownType = Data(#"{"model_type": "not_a_model"}"#.utf8)

await #expect(throws: DecodingError.self) {
try await LLMTypeRegistry.shared.estimator(configuration: unknownPrecision)
}
await #expect(throws: ModelFactoryError.self) {
try await LLMTypeRegistry.shared.estimator(configuration: unknownType)
}
await #expect(throws: ModelFactoryError.self) {
try await LLMTypeRegistry.shared.estimator(
configuration: Data(qwen3Configuration().utf8), precision: .int8)
}
}
}
14 changes: 14 additions & 0 deletions skills/mlx-swift-lm/references/kv-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,20 @@ for layer in estimator.cache.layers {
}
```

Before the weights are downloaded, estimate from the `config.json` alone. The
model is built without weights and nothing is evaluated. The cache takes the
precision the configuration declares (`torch_dtype` or `dtype`, else `bfloat16`).
For quantized weights that is the precision of their scales. Pass `precision:`
when a repository stores another precision than it declares.

```swift
let estimator = try await LLMTypeRegistry.shared.estimator(configuration: configData)
// Weights stored in float16 under a config that declares float32.
let stored = try await LLMTypeRegistry.shared.estimator(
configuration: configData, precision: .float16)
// A vision-language model: VLMTypeRegistry.shared.estimator(configuration:)
```

Its `decode` reports what one decoded token reads. The weights are the
model's, so pass the bytes they contribute to a token.

Expand Down
Loading