Skip to content
Open
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
64 changes: 47 additions & 17 deletions Libraries/MLXLMCommon/Documentation.docc/kv-cache-quantization.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,32 @@ The standalone legacy ``maybeQuantizeKVCache(cache:kvBits:kvGroupSize:quantizedK
hook leaves custom schemes unchanged; generation APIs reject them.

When the model starts its caches compressed (``KVCacheStart/compressed(headDim:)``)
and the strategy compresses from token 0, the cache starts compressed and
encodes every prefill chunk as it lands, so the full-precision cache never
exists. This moves compression earlier, not only allocation: each prefill chunk
after the first attends over already-compressed history, where the dynamic path
ran the whole first prompt at full precision before converting. Expect small
logit differences between the two, growing with chunk count and shrinking with
more bits. Models that start ``KVCacheStart/deferred``, deferred compression starts, and
TurboQuant keep the dynamic path: raw fp16 during prompt processing, one
conversion on the first decode step, then incremental encoding. Compressed
caches round-trip through prompt-cache save/restore either way.
and an affine or variance-normalized strategy compresses from token 0, the cache
starts compressed and encodes every prefill chunk as it lands, so the
full-precision cache never exists. This moves compression earlier, not only
allocation: each prefill chunk after the first attends over already-compressed
history, where the dynamic path ran the whole first prompt at full precision
before converting. Expect small logit differences between the two, growing with
chunk count and shrinking with more bits.

Otherwise the cache starts in full precision and converts dynamically. An affine
cache then compresses while it prefills, like mlx-lm: the prefill stops right
after the compression start, converts the cache, and writes the rest of the
prompt into it. A long prompt is never held in full precision past the start. On
Qwen3-Reranker-0.6B-4bit with a 32,768-token prompt (M5 Max), the prefill peaked
at 2.4 GB above the weights instead of 4.2 GB, at the same speed.
Each chunk attends to a dequantized copy of the cache, except for head
dimensions the fused kernel does not cover, such as 256, which attend through
quantized matmuls and hold the attention scores. On Qwen3.8-27B-4bit with an
8,192-token prompt that peaked 190 MB higher and ran 10% slower.
Set ``PrefillParameters/cacheCompression`` to
``PrefillParameters/CacheCompression/afterPrefill`` to write the whole prompt
in full precision first and compress it afterwards. Dynamic TurboQuant and
variance-normalized caches always do that: their attention over a compressed
cache is much slower for a prompt chunk and does not use less memory.
TurboQuant compresses on the first decode step and encodes each new token
incrementally afterwards. Compressed caches round-trip through prompt-cache
save/restore either way.

## Capacity and compatibility

Expand Down Expand Up @@ -107,15 +123,17 @@ let maxTokens = estimator.cache.maxTokens(fittingIn: budgetBytes)
```

A compressed cache stays in full precision until it holds more than its
compression start, and generation compresses it only after a prefill or a decode
step. A prompt that crosses the start is written in full precision first, and
while the cache converts it holds both copies. ``GenerationEstimator/Cache/bytes(tokens:)``
compression start. Generation compresses it after the prefill or decode step
that crosses the start, or, for an affine cache that compresses while it
prefills, right after the start. It converts one layer at a time, and the
converting layer holds both copies. ``GenerationEstimator/Cache/bytes(tokens:)``
is what the cache holds once it has compressed, and
``GenerationEstimator/Cache/peakBytes(tokens:promptTokens:)`` includes the
conversion, but not the working memory of the conversion itself: variance
conversion, but not the working memory of converting one layer: variance
normalization computes in float32 and needs more while it converts.
`maxTokens(fittingIn:)` uses the peak. Pass `promptTokens` when
prompts are shorter than the whole context, for example in a chat:
`maxTokens(fittingIn:)` uses the peak. Pass `promptTokens` when the cache
compresses after the prefill and prompts are shorter than the whole context,
for example in a chat, or when a prompt with media cannot stop at the start:

```swift
let peak = estimator.cache.peakBytes(tokens: 32_768, promptTokens: 4_096)
Expand All @@ -142,10 +160,22 @@ 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.

A ``ChatSession`` also keeps prompt checkpoints, so a later prompt that rewrites
what followed resumes from one instead of from the start. A checkpoint copies the
layers that cannot trim back to it: sliding windows, recurrent state, a requested
capacity once it evicts, and the incomplete tile of a variance-normalized cache.
``GenerationEstimator/Cache/checkpointBytes(tokens:)`` estimates one checkpoint. A
session keeps up to three, each at a shorter context than the conversation:

```swift
let session = estimator.cache.peakBytes(tokens: 32_768, promptTokens: 4_096)
+ 3 * estimator.cache.checkpointBytes(tokens: 32_768)
```

``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
and its drafter, with ``GenerationEstimator/Cache/init(layers:)``.
and its drafter, with ``GenerationEstimator/Cache/init(layers:prefillCompression:)``.

Its ``GenerationEstimator/decode`` reports what one decoded token reads: the
model's weights and the cache it attends to. The weights belong to the model, so
Expand Down
2 changes: 2 additions & 0 deletions Libraries/MLXLMCommon/Documentation.docc/wired-memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ state, and cache quantization instead of a hand-written formula.
let estimator = try await container.estimator(parameters: parameters)
// The peak includes the full-precision copy a compressed cache holds while it converts.
let kvBytes = estimator.cache.peakBytes(tokens: contextLength)
// A ChatSession keeps up to three prompt checkpoints beside the cache.
let checkpointBytes = 3 * estimator.cache.checkpointBytes(tokens: contextLength)
```

Dense, hybrid, and mixture-of-experts models need different sums per layer, which is what the
Expand Down
49 changes: 42 additions & 7 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1318,9 +1318,13 @@ public struct TokenIterator: TokenIteratorProtocol {
prefill.prefix?(cacheStorage.processedTokenCount)
var input = input
var prefill = prefill
if !checkpointPositions.isEmpty, prefill.chunking == .balanced {
let compressionSplit = kvCachePlan.compressionSplit(
of: input, after: cacheStorage.processedTokenCount, cache: cacheStorage.cache,
prefill: prefill)
if prefill.chunking == .balanced, !checkpointPositions.isEmpty || compressionSplit != nil {
(input, prefill) = try prefillToCheckpoints(
input, at: checkpointPositions, prefill: prefill)
input, at: checkpointPositions, compressingAt: compressionSplit,
prefill: prefill)
}
let inputLength = input.text.cacheSequenceLength

Expand Down Expand Up @@ -1358,9 +1362,10 @@ public struct TokenIterator: TokenIteratorProtocol {

/// Prefills `input` up to each of `positions`, records ``prefillCheckpoints`` there, and
/// returns the rest of the input with the parameters to prefill it as the remainder of one
/// prefill.
/// prefill. At `compression`, the cache compresses before the prefill goes on.
private mutating func prefillToCheckpoints(
_ input: LMInput, at positions: [Int], prefill: PrefillParameters
_ input: LMInput, at positions: [Int], compressingAt compression: Int?,
prefill: PrefillParameters
) throws -> (LMInput, PrefillParameters) {
precondition(
input.image == nil && input.video == nil && input.audio == nil
Expand All @@ -1375,16 +1380,16 @@ public struct TokenIterator: TokenIteratorProtocol {
"prefill checkpoints are ascending")

var start = 0
for position in positions {
for position in Set(positions + [compression].compactMap { $0 }).sorted() {
if position > start {
state = try model.prefill(
LMInput(text: input.text[.ellipsis, start ..< position]), into: cacheStorage,
state: state, parameters: prefill.pass(after: start, of: total))
}
if kvCachePlan.requiresRealizedCheckpoint {
if position == compression || kvCachePlan.requiresRealizedCheckpoint {
try kvCachePlan.applyAndValidate(to: cacheStorage)
}
if let checkpoint = cacheStorage.checkpoint() {
if positions.contains(position), let checkpoint = cacheStorage.checkpoint() {
prefillCheckpoints.append(PrefillCheckpoint(cache: checkpoint, state: state))
}
start = position
Expand Down Expand Up @@ -1712,6 +1717,14 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
mutating func prepare(input: LMInput, prefill: PrefillParameters = .init()) throws {
processor?.prompt(input.text.tokens)
prefill.prefix?(mainCacheStorage.processedTokenCount)
var input = input
var prefill = prefill
if let split = kvCachePlan.compressionSplit(
of: input, after: mainCacheStorage.processedTokenCount,
cache: mainCacheStorage.cache + draftCacheStorage.cache, prefill: prefill)
{
(input, prefill) = try prefillAndCompress(input, at: split, prefill: prefill)
}
let inputLength = input.text.cacheSequenceLength

// Prefill main model
Expand Down Expand Up @@ -1771,6 +1784,28 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
try kvCachePlan.applyAndValidate(to: draftCacheStorage)
}

/// Prefills both models up to `split`, compresses their caches, and returns the rest of the
/// input with the parameters to prefill it as the remainder of one prefill.
private mutating func prefillAndCompress(
_ input: LMInput, at split: Int, prefill: PrefillParameters
) throws -> (LMInput, PrefillParameters) {
let total = input.text.cacheSequenceLength
let head = LMInput(text: input.text[.ellipsis, ..<split])
let pass = prefill.pass(after: 0, of: total)
state = try mainModel.prefill(
head, into: mainCacheStorage, state: state, parameters: pass)
var draftPass = pass
draftPass.progress = nil
_ = try draftModel.prefill(
head, into: draftCacheStorage, state: nil, parameters: draftPass)
try kvCachePlan.applyAndValidate(to: mainCacheStorage)
try kvCachePlan.applyAndValidate(to: draftCacheStorage)
return (
LMInput(text: input.text[.ellipsis, split...]),
prefill.pass(after: split, of: total)
)
}

/// Run one round of speculative decoding: draft, verify, accept/reject
mutating func speculateRound() {
let remaining = maxTokens.map { $0 - tokenCount } ?? numDraftTokens
Expand Down
Loading
Loading