From 60dcdcfa30e61bd0a313e9b21006f65b6af5fd5a Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Sat, 21 Mar 2026 01:09:28 -0600 Subject: [PATCH 1/7] restore TopKTopPSampler path for models with topK > 0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The upstream merge (bc3c20e) collapsed all sampler selection into TopPSampler, which runs argSort on the full vocabulary (131K+ for Qwen3.5). This caused a 4x speed regression: 3.1 tok/s vs ~13 tok/s. Restore the smarter selection from our pre-merge code: - topK > 0: TopKTopPSampler (sorts only topK candidates first) - topP only: TopPSampler (sorts full vocab, unavoidable) - neither: CategoricalSampler (no sorting) For Qwen3.5 4B 4-bit with topK=20: 3.1 → 13.7 tok/s (4.4x faster). --- Libraries/MLXLMCommon/Evaluate.swift | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index 226f52e76f..b2b77e29ea 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -146,8 +146,14 @@ public struct GenerateParameters: Sendable { if temperature == 0 { return ArgMaxSampler() - } else if usesTopP || usesTopK || usesMinP { - return TopPSampler(temperature: temperature, topP: topP, topK: topK, minP: minP) + } else if usesTopK { + // Top-K with optional top-P and min-P filtering. + // TopKTopPSampler first restricts to topK candidates before sorting, + // which is much faster than TopPSampler for large vocabularies (131K+). + return TopKTopPSampler( + temperature: temperature, topK: topK, topP: topP, minP: usesMinP ? minP : nil) + } else if usesTopP || usesMinP { + return TopPSampler(temperature: temperature, topP: topP, topK: 0, minP: minP) } else { return CategoricalSampler(temperature: temperature) } From eab709c1bc0316ceaf9c3a906cd22147bcbb4eee Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Tue, 24 Mar 2026 18:28:30 -0600 Subject: [PATCH 2/7] perf: eliminate CPU-GPU sync in penalty processors, optimize TopPSampler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace CPU-side [Int] token buffers with GPU-resident TokenRing struct that uses MLX.where mask operations for writes — no token.item(Int.self) calls that force CPU to wait for GPU results. TokenRing: shared ring buffer using MLXArray.arange() positions and MLX.where for GPU-only append. Bulk-loads prompt tokens efficiently. RepetitionContext, PresencePenaltyContext, FrequencyPenaltyContext: all rewritten to use TokenRing. FrequencyPenaltyContext now uses GPU histogram via .at[].add() instead of CPU dict counting. TopPSampler: rewritten to work in log-space with separate applyTopP, applyMinP, applyTopK filters matching Python mlx-lm ordering. Uses putAlong/takeAlong for scatter operations. Removes TopKTopPSampler (unified into TopPSampler). Based on approach from upstream PR #147. Preserves Sam-specific additionalProcessors and reasoningEffort fields. Expected: ~35% tok/s improvement with penalty processors active. --- Libraries/MLXLMCommon/Evaluate.swift | 158 +++++++++++---------------- 1 file changed, 64 insertions(+), 94 deletions(-) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index b2b77e29ea..5639ddc80b 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -146,14 +146,8 @@ public struct GenerateParameters: Sendable { if temperature == 0 { return ArgMaxSampler() - } else if usesTopK { - // Top-K with optional top-P and min-P filtering. - // TopKTopPSampler first restricts to topK candidates before sorting, - // which is much faster than TopPSampler for large vocabularies (131K+). - return TopKTopPSampler( - temperature: temperature, topK: topK, topP: topP, minP: usesMinP ? minP : nil) - } else if usesTopP || usesMinP { - return TopPSampler(temperature: temperature, topP: topP, topK: 0, minP: minP) + } else if usesTopP || usesTopK || usesMinP { + return TopPSampler(temperature: temperature, topP: topP, topK: topK, minP: minP) } else { return CategoricalSampler(temperature: temperature) } @@ -212,33 +206,54 @@ public struct ArgMaxSampler: LogitSampler { } /// Sampler that uses probability filters (`topP`, `topK`, `minP`) and `temperature` -/// to sample the logits. -/// -/// Filters are applied in the same order as Python mlx-lm: top_p → min_p → top_k. -/// Each filter operates on the full vocabulary in original token order, masking -/// rejected tokens with `-inf`. This matches the composable filter chain in -/// `mlx_lm.sample_utils.make_sampler`. +/// to sample the logits. Works in log-space to avoid numerical issues. public struct TopPSampler: LogitSampler { let temp: MLXArray - let topP: MLXArray? - let topK: Int? - let minP: MLXArray? - let negInf: MLXArray + let topP: Float + let topK: Int + let minP: Float let randomState: MLXRandom.RandomState + private static let negInf = Float(-1e9) + public init(temperature: Float, topP: Float = 1.0, topK: Int = 0, minP: Float = 0.0) { self.temp = MLXArray(temperature) - if topP > 0 && topP < 1 { - self.topP = MLXArray(topP) - } else { - self.topP = nil - } - self.topK = topK > 0 ? topK : nil - self.minP = minP > 0 ? MLXArray(minP) : nil - self.negInf = MLXArray(-Float.infinity) + self.topP = topP + self.topK = topK + self.minP = minP self.randomState = MLXRandom.RandomState() } + /// Apply top-p (nucleus) filtering in log-space. + private func applyTopP(_ logits: MLXArray, sortedIndices: MLXArray) -> MLXArray { + guard topP > 0 && topP < 1 else { return logits } + let sortedLogits = takeAlong(logits, sortedIndices, axis: -1) + let cumulativeProbs = cumsum(softmax(sortedLogits, axis: -1), axis: -1) + let mask = cumulativeProbs .> (1 - MLXArray(topP)) + let filteredLogits = MLX.where(mask, sortedLogits, MLXArray(Self.negInf)) + return putAlong(broadcast(MLXArray(Self.negInf), to: logits.shape), sortedIndices, values: filteredLogits, axis: -1) + } + + /// Apply min-p filtering: remove tokens below minP * max_probability. + private func applyMinP(_ logits: MLXArray) -> MLXArray { + guard minP > 0 else { return logits } + let probs = softmax(logits, axis: -1) + let maxProb = MLX.max(probs, axis: -1, keepDims: true) + let mask = probs .>= (maxProb * MLXArray(minP)) + return MLX.where(mask, logits, MLXArray(Self.negInf)) + } + + /// Apply top-k filtering: keep only the k highest-probability tokens. + private func applyTopK(_ logits: MLXArray) -> MLXArray { + guard topK > 0 else { return logits } + let vocabSize = logits.dim(-1) + guard topK < vocabSize else { return logits } + let kthValues = sorted(logits, axis: -1)[0..., vocabSize - topK] + let threshold = expandedDimensions(kthValues, axis: -1) + return MLX.where(logits .>= threshold, logits, MLXArray(Self.negInf)) + } + + public func sample(logits: MLXArray) -> MLXArray { var logits = logits if logits.dtype == .bfloat16 { @@ -246,55 +261,14 @@ public struct TopPSampler: LogitSampler { } return withRandomState(randomState) { - var logprobs = logSoftmax(logits) - - // Apply filters in Python mlx-lm order: top_p → min_p → top_k. - if let topP { - logprobs = applyTopP(logprobs, topP: topP) - } - if let minP { - logprobs = applyMinP(logprobs, minP: minP) - } - if let topK { - logprobs = applyTopK(logprobs, topK: topK) - } + let sortedIndices = argSort(logits, axis: -1) + logits = applyTopP(logits, sortedIndices: sortedIndices) + logits = applyMinP(logits) + logits = applyTopK(logits) - return categorical(logprobs * (1 / temp)) + return categorical(logits * (1 / temp)) } } - - /// Keep tokens whose cumulative probability exceeds `1 - topP` (nucleus sampling). - /// Matches `apply_top_p` from `mlx_lm/sample_utils.py`. - private func applyTopP(_ logprobs: MLXArray, topP: MLXArray) -> MLXArray { - let sortedIndices = argSort(logprobs, axis: -1) - let sortedLogprobs = takeAlong(logprobs, sortedIndices, axis: -1) - let sortedProbs = exp(sortedLogprobs) - let cumulativeProbs = cumsum(sortedProbs, axis: -1) - - // Mask low-probability tail in sorted order, scatter back to original vocab order. - let filtered = MLX.where(cumulativeProbs .> (1 - topP), sortedLogprobs, negInf) - return putAlong(logprobs, sortedIndices, values: filtered, axis: -1) - } - - /// Keep tokens with probability >= maxProb * minP. - /// Matches `apply_min_p` from `mlx_lm/sample_utils.py`. - private func applyMinP(_ logprobs: MLXArray, minP: MLXArray) -> MLXArray { - // threshold in log-space: log(maxProb * minP) = maxLogprob + log(minP) - let maxLogprob = logprobs.max(axis: -1, keepDims: true) - let threshold = maxLogprob + log(minP) - return MLX.where(logprobs .>= threshold, logprobs, negInf) - } - - /// Keep only the top-k highest-probability tokens. - /// Mirrors `apply_top_k` from `mlx_lm/sample_utils.py`. - private func applyTopK(_ logprobs: MLXArray, topK: Int) -> MLXArray { - let vocabularySize = logprobs.dim(-1) - guard topK < vocabularySize else { return logprobs } - // O(V) partition on negated logprobs so top-k land at [0, topK). - // Indices at [topK, V) are the tokens to mask out. - let maskIndices = argPartition(-logprobs, kth: topK - 1, axis: -1)[0..., topK...] - return putAlong(logprobs, maskIndices, values: negInf, axis: -1) - } } /// Sampler that uses `temperature` to sample the logits. @@ -315,10 +289,8 @@ public struct CategoricalSampler: LogitSampler { } /// GPU-resident ring buffer of recent token IDs. -/// -/// Shared by penalty processors to avoid duplicating ring buffer logic. -/// Uses `MLX.where` mask operations for GPU-only updates (no CPU←GPU sync), -/// preserving `asyncEval()` pipelining in `TokenIterator`. +/// Uses MLX.where mask operations for GPU-only updates (no CPU<-GPU sync), +/// preserving asyncEval() pipelining in TokenIterator. struct TokenRing { private(set) var buffer: MLXArray private(set) var count = 0 @@ -333,13 +305,11 @@ struct TokenRing { self.positions = MLXArray.arange(capacity) } - /// The valid portion of the ring (all of it once full), or `nil` if empty. var validTokens: MLXArray? { guard count > 0 else { return nil } return count < capacity ? buffer[.. 0) self.repetitionPenalty = repetitionPenalty self.ring = TokenRing(capacity: repetitionContextSize) } @@ -383,7 +355,8 @@ public struct RepetitionContext: LogitProcessor { } public func process(logits: MLXArray) -> MLXArray { - guard let indices = ring.validTokens?.asType(.uint32) else { return logits } + guard let validTokens = ring.validTokens else { return logits } + let indices = validTokens.asType(.uint32) var selectedLogits = logits[0..., indices] selectedLogits = MLX.where( @@ -400,14 +373,13 @@ public struct RepetitionContext: LogitProcessor { } /// Processor that applies an additive presence penalty to tokens in a recent context window. -/// -/// The penalty is applied once per unique token via scatter-write (writing the -/// same value to the same index multiple times is idempotent). public struct PresencePenaltyContext: LogitProcessor { - private var ring: TokenRing + var ring: TokenRing + let presencePenalty: Float public init(presencePenalty: Float, presenceContextSize: Int) { + precondition(presenceContextSize > 0) self.presencePenalty = presencePenalty self.ring = TokenRing(capacity: presenceContextSize) } @@ -417,7 +389,8 @@ public struct PresencePenaltyContext: LogitProcessor { } public func process(logits: MLXArray) -> MLXArray { - guard let indices = ring.validTokens?.asType(.uint32) else { return logits } + guard let validTokens = ring.validTokens else { return logits } + let indices = validTokens.asType(.uint32) logits[0..., indices] = logits[0..., indices] - presencePenalty return logits } @@ -428,14 +401,13 @@ public struct PresencePenaltyContext: LogitProcessor { } /// Processor that applies an additive frequency penalty to tokens in a recent context window. -/// -/// Frequency counting is performed on GPU via `scatter_add` to build a histogram -/// of token occurrences, avoiding CPU←GPU synchronization. public struct FrequencyPenaltyContext: LogitProcessor { - private var ring: TokenRing + var ring: TokenRing + let frequencyPenalty: Float public init(frequencyPenalty: Float, frequencyContextSize: Int) { + precondition(frequencyContextSize > 0) self.frequencyPenalty = frequencyPenalty self.ring = TokenRing(capacity: frequencyContextSize) } @@ -446,13 +418,11 @@ public struct FrequencyPenaltyContext: LogitProcessor { public func process(logits: MLXArray) -> MLXArray { guard let validTokens = ring.validTokens else { return logits } - let vocabSize = logits.dim(-1) let ones = MLXArray.ones([validTokens.dim(0)], type: Float32.self) let histogram = MLXArray.zeros([vocabSize], type: Float32.self) .at[validTokens.asType(.int32)].add(ones) - - return logits - (histogram * frequencyPenalty).reshaped(1, -1) + return logits - histogram * frequencyPenalty } mutating public func didSample(token: MLXArray) { From 9be4810216dcdf248c7f1811956e5877434170e0 Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Tue, 24 Mar 2026 19:13:56 -0600 Subject: [PATCH 3/7] fix TokenRing crash: flatten prompt before measuring length loadPrompt received multi-dimensional prompt tokens (e.g. [1, 1454]) but used dim(0) which returned the batch dimension (1), not the sequence length. This caused the buffer to be allocated with the wrong size, leading to shape mismatch in append() when positions array couldn't broadcast with the oversized buffer. Fix: reshape(-1) first, then measure dim(0) on the flattened array. --- Libraries/MLXLMCommon/Evaluate.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index 5639ddc80b..ed4a4fe3a0 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -311,8 +311,8 @@ struct TokenRing { } mutating func loadPrompt(_ prompt: MLXArray) { - let n = prompt.dim(0) - let promptTokens = prompt.asType(.int32) + let promptTokens = prompt.reshaped(-1).asType(.int32) + let n = promptTokens.dim(0) if n <= capacity { if n < capacity { let padding = MLXArray.zeros([capacity - n], type: Int32.self) From 499ae7b3bcda2ff791db4758e63121a4963e209b Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Tue, 24 Mar 2026 22:14:29 -0600 Subject: [PATCH 4/7] optimize sampler: logSoftmax, argPartition, proper -inf masking Port key optimizations from upstream PR #147: - Work in log-space throughout (single logSoftmax vs multiple softmax) - Use argPartition for top-k (O(V) vs O(V log V) full sort) - Use -Float.infinity instead of -1e9 for proper categorical masking - Pre-compute filter threshold arrays only when filters are active - Cleaner code structure matching Python mlx-lm sample_utils.py --- Libraries/MLXLMCommon/Evaluate.swift | 117 +++++++++++++++++---------- 1 file changed, 74 insertions(+), 43 deletions(-) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index ed4a4fe3a0..1d7882a5aa 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -207,53 +207,40 @@ public struct ArgMaxSampler: LogitSampler { /// Sampler that uses probability filters (`topP`, `topK`, `minP`) and `temperature` /// to sample the logits. Works in log-space to avoid numerical issues. +/// Sampler that uses probability filters (`topP`, `topK`, `minP`) and `temperature` +/// to sample the logits. +/// +/// Filters are applied in the same order as Python mlx-lm: top_p → min_p → top_k. +/// Each filter operates on the full vocabulary in original token order, masking +/// rejected tokens with `-inf`. This matches the composable filter chain in +/// `mlx_lm.sample_utils.make_sampler`. +/// +/// Performance optimizations (matching PR #147): +/// - Log-space throughout (`logSoftmax`) — avoids redundant softmax calls +/// - `argPartition` for top-k — O(V) partial sort vs O(V log V) full sort +/// - `-Float.infinity` for proper masking in categorical sampler public struct TopPSampler: LogitSampler { let temp: MLXArray - let topP: Float - let topK: Int - let minP: Float + let topP: MLXArray? + let topK: Int? + let minP: MLXArray? + let negInf: MLXArray let randomState: MLXRandom.RandomState - private static let negInf = Float(-1e9) - public init(temperature: Float, topP: Float = 1.0, topK: Int = 0, minP: Float = 0.0) { self.temp = MLXArray(temperature) - self.topP = topP - self.topK = topK - self.minP = minP + // Only create threshold arrays when the filter is active + if topP > 0 && topP < 1 { + self.topP = MLXArray(topP) + } else { + self.topP = nil + } + self.topK = topK > 0 ? topK : nil + self.minP = minP > 0 ? MLXArray(minP) : nil + self.negInf = MLXArray(-Float.infinity) self.randomState = MLXRandom.RandomState() } - /// Apply top-p (nucleus) filtering in log-space. - private func applyTopP(_ logits: MLXArray, sortedIndices: MLXArray) -> MLXArray { - guard topP > 0 && topP < 1 else { return logits } - let sortedLogits = takeAlong(logits, sortedIndices, axis: -1) - let cumulativeProbs = cumsum(softmax(sortedLogits, axis: -1), axis: -1) - let mask = cumulativeProbs .> (1 - MLXArray(topP)) - let filteredLogits = MLX.where(mask, sortedLogits, MLXArray(Self.negInf)) - return putAlong(broadcast(MLXArray(Self.negInf), to: logits.shape), sortedIndices, values: filteredLogits, axis: -1) - } - - /// Apply min-p filtering: remove tokens below minP * max_probability. - private func applyMinP(_ logits: MLXArray) -> MLXArray { - guard minP > 0 else { return logits } - let probs = softmax(logits, axis: -1) - let maxProb = MLX.max(probs, axis: -1, keepDims: true) - let mask = probs .>= (maxProb * MLXArray(minP)) - return MLX.where(mask, logits, MLXArray(Self.negInf)) - } - - /// Apply top-k filtering: keep only the k highest-probability tokens. - private func applyTopK(_ logits: MLXArray) -> MLXArray { - guard topK > 0 else { return logits } - let vocabSize = logits.dim(-1) - guard topK < vocabSize else { return logits } - let kthValues = sorted(logits, axis: -1)[0..., vocabSize - topK] - let threshold = expandedDimensions(kthValues, axis: -1) - return MLX.where(logits .>= threshold, logits, MLXArray(Self.negInf)) - } - - public func sample(logits: MLXArray) -> MLXArray { var logits = logits if logits.dtype == .bfloat16 { @@ -261,14 +248,58 @@ public struct TopPSampler: LogitSampler { } return withRandomState(randomState) { - let sortedIndices = argSort(logits, axis: -1) - logits = applyTopP(logits, sortedIndices: sortedIndices) - logits = applyMinP(logits) - logits = applyTopK(logits) + // Work in log-space throughout — single logSoftmax instead of + // multiple softmax calls per filter. + var logprobs = logSoftmax(logits) - return categorical(logits * (1 / temp)) + // Apply filters in Python mlx-lm order: top_p → min_p → top_k. + if let topP { + logprobs = applyTopP(logprobs, topP: topP) + } + if let minP { + logprobs = applyMinP(logprobs, minP: minP) + } + if let topK { + logprobs = applyTopK(logprobs, topK: topK) + } + + return categorical(logprobs * (1 / temp)) } } + + /// Keep tokens whose cumulative probability exceeds `1 - topP` (nucleus sampling). + /// Matches `apply_top_p` from `mlx_lm/sample_utils.py`. + private func applyTopP(_ logprobs: MLXArray, topP: MLXArray) -> MLXArray { + let sortedIndices = argSort(logprobs, axis: -1) + let sortedLogprobs = takeAlong(logprobs, sortedIndices, axis: -1) + let sortedProbs = exp(sortedLogprobs) + let cumulativeProbs = cumsum(sortedProbs, axis: -1) + + // Mask low-probability tail in sorted order, scatter back to original vocab order. + let filtered = MLX.where(cumulativeProbs .> (1 - topP), sortedLogprobs, negInf) + return putAlong(logprobs, sortedIndices, values: filtered, axis: -1) + } + + /// Keep tokens with probability >= maxProb * minP. + /// Matches `apply_min_p` from `mlx_lm/sample_utils.py`. + /// Works in log-space: threshold = maxLogprob + log(minP). + private func applyMinP(_ logprobs: MLXArray, minP: MLXArray) -> MLXArray { + let maxLogprob = logprobs.max(axis: -1, keepDims: true) + let threshold = maxLogprob + log(minP) + return MLX.where(logprobs .>= threshold, logprobs, negInf) + } + + /// Keep only the top-k highest-probability tokens. + /// Uses `argPartition` for O(V) partial sort instead of O(V log V) full sort. + /// Mirrors `apply_top_k` from `mlx_lm/sample_utils.py`. + private func applyTopK(_ logprobs: MLXArray, topK: Int) -> MLXArray { + let vocabularySize = logprobs.dim(-1) + guard topK < vocabularySize else { return logprobs } + // O(V) partition on negated logprobs so top-k land at [0, topK). + // Indices at [topK, V) are the tokens to mask out. + let maskIndices = argPartition(-logprobs, kth: topK - 1, axis: -1)[0..., topK...] + return putAlong(logprobs, maskIndices, values: negInf, axis: -1) + } } /// Sampler that uses `temperature` to sample the logits. From 5870c02545aef067a440e995e50f67394b671307 Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Tue, 24 Mar 2026 22:50:25 -0600 Subject: [PATCH 5/7] add periodic GPU cache clear every 256 tokens Matches Python mlx-lm behavior of calling mx.clear_cache() during long generation runs to prevent memory fragmentation. Without this, GPU memory allocations accumulate and can cause pressure on memory-constrained systems. --- Libraries/MLXLMCommon/Evaluate.swift | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index 1d7882a5aa..e29b07b40b 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -702,6 +702,12 @@ public struct TokenIterator: Sequence, IteratorProtocol { tokenCount += 1 + // Periodically clear GPU memory cache to prevent fragmentation + // during long generations, matching Python mlx-lm behavior. + if tokenCount % 256 == 0 { + MLX.Memory.clearCache() + } + return previousY.tokens.item(Int.self) } } From cb8e2af559da9f6b9b0eb868dbc55ca8688852dc Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Tue, 24 Mar 2026 23:28:05 -0600 Subject: [PATCH 6/7] periodic GPU cache clear, revert compiled sampler (deadlocks) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add MLX.Memory.clearCache() every 256 tokens during generation, matching Python mlx-lm behavior to prevent memory fragmentation. Attempted mx.compile() for sampler functions but reverted — the Swift compile() implementation uses evalLock which deadlocks with asyncEval() in the TokenIterator generation loop. This is an upstream mlx-swift issue where CompiledFunction.innerCall holds evalLock while mlx_closure_apply triggers evaluation that also needs the eval pipeline. --- Libraries/MLXLMCommon/Evaluate.swift | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index e29b07b40b..e6cdef069b 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -229,7 +229,6 @@ public struct TopPSampler: LogitSampler { public init(temperature: Float, topP: Float = 1.0, topK: Int = 0, minP: Float = 0.0) { self.temp = MLXArray(temperature) - // Only create threshold arrays when the filter is active if topP > 0 && topP < 1 { self.topP = MLXArray(topP) } else { @@ -248,11 +247,8 @@ public struct TopPSampler: LogitSampler { } return withRandomState(randomState) { - // Work in log-space throughout — single logSoftmax instead of - // multiple softmax calls per filter. var logprobs = logSoftmax(logits) - // Apply filters in Python mlx-lm order: top_p → min_p → top_k. if let topP { logprobs = applyTopP(logprobs, topP: topP) } @@ -268,35 +264,26 @@ public struct TopPSampler: LogitSampler { } /// Keep tokens whose cumulative probability exceeds `1 - topP` (nucleus sampling). - /// Matches `apply_top_p` from `mlx_lm/sample_utils.py`. private func applyTopP(_ logprobs: MLXArray, topP: MLXArray) -> MLXArray { let sortedIndices = argSort(logprobs, axis: -1) let sortedLogprobs = takeAlong(logprobs, sortedIndices, axis: -1) let sortedProbs = exp(sortedLogprobs) let cumulativeProbs = cumsum(sortedProbs, axis: -1) - - // Mask low-probability tail in sorted order, scatter back to original vocab order. let filtered = MLX.where(cumulativeProbs .> (1 - topP), sortedLogprobs, negInf) return putAlong(logprobs, sortedIndices, values: filtered, axis: -1) } - /// Keep tokens with probability >= maxProb * minP. - /// Matches `apply_min_p` from `mlx_lm/sample_utils.py`. - /// Works in log-space: threshold = maxLogprob + log(minP). + /// Keep tokens with probability >= maxProb * minP (log-space). private func applyMinP(_ logprobs: MLXArray, minP: MLXArray) -> MLXArray { let maxLogprob = logprobs.max(axis: -1, keepDims: true) let threshold = maxLogprob + log(minP) return MLX.where(logprobs .>= threshold, logprobs, negInf) } - /// Keep only the top-k highest-probability tokens. - /// Uses `argPartition` for O(V) partial sort instead of O(V log V) full sort. - /// Mirrors `apply_top_k` from `mlx_lm/sample_utils.py`. + /// Keep only the top-k highest-probability tokens (O(V) argPartition). private func applyTopK(_ logprobs: MLXArray, topK: Int) -> MLXArray { let vocabularySize = logprobs.dim(-1) guard topK < vocabularySize else { return logprobs } - // O(V) partition on negated logprobs so top-k land at [0, topK). - // Indices at [topK, V) are the tokens to mask out. let maskIndices = argPartition(-logprobs, kth: topK - 1, axis: -1)[0..., topK...] return putAlong(logprobs, maskIndices, values: negInf, axis: -1) } From 5a6879d979da4676a566039e38d3ebaf26af06fe Mon Sep 17 00:00:00 2001 From: Eric Kryski Date: Wed, 25 Mar 2026 00:46:27 -0600 Subject: [PATCH 7/7] add speculative decoding infrastructure for draft-verify generation --- .../MLXLMCommon/SpeculativeDecoder.swift | 431 ++++++++++++++++++ 1 file changed, 431 insertions(+) create mode 100644 Libraries/MLXLMCommon/SpeculativeDecoder.swift diff --git a/Libraries/MLXLMCommon/SpeculativeDecoder.swift b/Libraries/MLXLMCommon/SpeculativeDecoder.swift new file mode 100644 index 0000000000..9da3733736 --- /dev/null +++ b/Libraries/MLXLMCommon/SpeculativeDecoder.swift @@ -0,0 +1,431 @@ +// Copyright 2026 Eric Kryski. All rights reserved. + +import Foundation +import MLX +import MLXNN +import Tokenizers + +/// Token iterator that implements speculative decoding for faster inference. +/// +/// Speculative decoding uses a small "draft" model to generate K candidate tokens +/// autoregressively, then the larger "target" model verifies all K+1 tokens in a +/// single forward pass. Matching tokens are accepted; on first mismatch, the +/// target model's token is used instead. This gives near-draft-model speed with +/// target-model quality. +/// +/// Both models must share the same tokenizer and have trimmable KV caches. +/// +/// Usage: +/// ```swift +/// let iterator = try SpeculativeTokenIterator( +/// input: lmInput, +/// targetModel: targetModel, +/// draftModel: draftModel, +/// targetCache: nil, +/// draftCache: nil, +/// parameters: generateParameters, +/// numDraftTokens: 4 +/// ) +/// +/// for token in iterator { +/// // token is an Int (token ID) +/// } +/// ``` +/// +/// Reference: Python mlx-lm `speculative_generate_step()` in generate.py +public struct SpeculativeTokenIterator: Sequence, IteratorProtocol { + + let targetModel: any LanguageModel + let draftModel: any LanguageModel + + var targetCache: [KVCache] + var draftCache: [KVCache] + + var processor: LogitProcessor? + let sampler: LogitSampler + + /// Number of draft tokens to generate per speculation round. + let numDraftTokens: Int + + var tokenCount = 0 + let maxTokens: Int? + + // Cache quantization parameters + let kvBits: Int? + let kvGroupSize: Int + let quantizedKVStart: Int + + // Internal metrics + var promptPrefillTime: TimeInterval = 0.0 + + /// Tokens accepted from draft model (for acceptance rate tracking). + public private(set) var draftAcceptedCount = 0 + + /// Total draft tokens proposed (for acceptance rate tracking). + public private(set) var draftProposedCount = 0 + + /// Buffer of accepted tokens waiting to be yielded. + /// Speculative decoding can accept multiple tokens per round, + /// but IteratorProtocol yields one at a time. + private var pendingTokens: [Int] = [] + + /// The next token to feed into the draft model for the next round. + /// After verification, this is the target model's sampled token at + /// the rejection point (or the token after the last accepted draft token). + private var nextY: LMInput.Text + + /// When all draft tokens are accepted, the last draft token hasn't been + /// processed by the draft model's cache yet, so we must prepend it + /// to the next draft input. + private var draftNeedsExtraToken: Bool = false + private var lastDraftToken: MLXArray? + + /// Initialize a speculative token iterator. + /// + /// - Parameters: + /// - input: language model input (prompt) + /// - targetModel: the large target model for verification + /// - draftModel: the small draft model for candidate generation + /// - targetCache: optional pre-created KV cache for target model + /// - draftCache: optional pre-created KV cache for draft model + /// - parameters: generation parameters (shared between both models) + /// - numDraftTokens: number of draft tokens per speculation round (default: 4) + public init( + input: LMInput, + targetModel: any LanguageModel, + draftModel: any LanguageModel, + targetCache: [KVCache]? = nil, + draftCache: [KVCache]? = nil, + parameters: GenerateParameters, + numDraftTokens: Int = 4 + ) throws { + self.targetModel = targetModel + self.draftModel = draftModel + self.targetCache = targetCache ?? targetModel.newCache(parameters: parameters) + self.draftCache = draftCache ?? draftModel.newCache(parameters: parameters) + self.numDraftTokens = numDraftTokens + + self.processor = parameters.processor() + self.sampler = parameters.sampler() + self.maxTokens = parameters.maxTokens + + self.kvBits = parameters.kvBits + self.kvGroupSize = parameters.kvGroupSize + self.quantizedKVStart = parameters.quantizedKVStart + + // Temporary placeholder; will be set during prepare() + self.nextY = input.text + + // Validate that both caches are trimmable + Self.validateCachesAreTrimmable(self.targetCache, label: "target") + Self.validateCachesAreTrimmable(self.draftCache, label: "draft") + + self.promptPrefillTime = try speculativeMeasure { + try prepareBothModels( + input: input, windowSize: parameters.prefillStepSize + ) + } + } + + // MARK: - Prefill + + /// Prefill both models with the prompt. + /// + /// Both models must process the same prompt to align their caches. + /// After prefill, the first token is sampled from the target model. + private mutating func prepareBothModels( + input: LMInput, windowSize: Int? + ) throws { + processor?.prompt(input.text.tokens) + + // Prefill draft model + switch try draftModel.prepare(input, cache: draftCache, windowSize: windowSize) { + case .tokens(let tokens): + // Run the remaining tokens through the draft model to prime its cache + let _ = draftModel( + tokens[text: .newAxis], cache: draftCache.isEmpty ? nil : draftCache, state: nil + ) + case .logits: + // Draft model already processed everything during prepare + break + } + + // Prefill target model and get first token + switch try targetModel.prepare(input, cache: targetCache, windowSize: windowSize) { + case .tokens(let tokens): + let result = targetModel( + tokens[text: .newAxis], + cache: targetCache.isEmpty ? nil : targetCache, + state: nil + ) + let token = convertToToken(logits: result.logits) + nextY = .init(tokens: token) + asyncEval(nextY.tokens) + + case .logits(let result): + let token = convertToToken(logits: result.logits) + nextY = .init(tokens: token) + asyncEval(nextY.tokens) + } + } + + // MARK: - Core Speculative Loop + + /// Run one speculation round: draft K tokens, verify with target, accept/reject. + /// + /// Returns an array of accepted token IDs (may include the corrected token). + private mutating func speculateRound() -> [Int] { + let effectiveDraftCount: Int + if let maxTokens { + effectiveDraftCount = Swift.min(maxTokens - tokenCount, numDraftTokens) + } else { + effectiveDraftCount = numDraftTokens + } + + // Step 1: Generate K draft tokens autoregressively + let draftTokens = generateDraftTokens(count: effectiveDraftCount) + + // Step 2: Build the verification input: [nextY, draft_0, draft_1, ..., draft_{K-1}] + let verificationInput: MLXArray + if draftTokens.size == 0 { + verificationInput = nextY.tokens.reshaped(-1) + } else { + verificationInput = concatenated( + [nextY.tokens.reshaped(-1), draftTokens], + axis: 0 + ) + } + + // Step 3: Run target model on all K+1 tokens in a single forward pass + let targetResult = targetModel( + LMInput.Text(tokens: verificationInput)[text: .newAxis], + cache: targetCache.isEmpty ? nil : targetCache, + state: nil + ) + + // Apply cache quantization to target + maybeQuantizeKVCache( + cache: &targetCache, + kvBits: kvBits, + kvGroupSize: kvGroupSize, + quantizedKVStart: quantizedKVStart + ) + + // Step 4: Sample from each position's logits + // targetResult.logits shape: [1, K+1, vocab_size] + // Position i gives logits for what should follow token i in the input + let allLogits = targetResult.logits.squeezed(axis: 0) // [K+1, vocab_size] + + var targetTokens: [Int] = [] + for i in 0 ..< (effectiveDraftCount + 1) { + var logits = allLogits[i] + logits = processor?.process(logits: logits) ?? logits + let sampled = sampler.sample(logits: logits) + processor?.didSample(token: sampled) + targetTokens.append(sampled.item(Int.self)) + } + + // Step 5: Compare draft tokens with target tokens + // targetTokens[i] is what the target thinks should follow the i-th input token + // draftTokens[i] is what the draft proposed as the (i+1)-th token + let draftTokenList: [Int] + if draftTokens.size > 0 { + eval(draftTokens) + draftTokenList = (0 ..< draftTokens.dim(0)).map { draftTokens[$0].item(Int.self) } + } else { + draftTokenList = [] + } + + var acceptedCount = 0 + var accepted: [Int] = [] + + for i in 0 ..< effectiveDraftCount { + if targetTokens[i] == draftTokenList[i] { + acceptedCount += 1 + accepted.append(targetTokens[i]) + } else { + break + } + } + + // The target model's token at the rejection point (or after all accepted) + accepted.append(targetTokens[acceptedCount]) + + // Update metrics + draftAcceptedCount += acceptedCount + draftProposedCount += effectiveDraftCount + + // Step 6: Rewind caches to the correct position + // Target cache consumed K+1 tokens but we only accepted `acceptedCount + 1` + // So we need to trim (K - acceptedCount) tokens from target cache + let targetTrim = effectiveDraftCount - acceptedCount + if targetTrim > 0 { + trimCache(targetCache, count: targetTrim) + } + + // Draft cache consumed K tokens but we only accepted `acceptedCount` + // Draft needs to be trimmed back to match. + // Python: cache.trim_prompt_cache(draft_cache, max(num_draft - num_accept - 1, 0)) + let draftTrim = Swift.max(effectiveDraftCount - acceptedCount - 1, 0) + if draftTrim > 0 { + trimCache(draftCache, count: draftTrim) + } + + // Set up for next round + let correctedToken = MLXArray(Int32(targetTokens[acceptedCount])) + nextY = .init(tokens: correctedToken) + + if acceptedCount == effectiveDraftCount && !draftTokenList.isEmpty { + // All draft tokens accepted: the last draft token hasn't been + // processed by the draft cache yet, so prepend it next round + draftNeedsExtraToken = true + lastDraftToken = MLXArray(Int32(draftTokenList.last!)) + } else { + draftNeedsExtraToken = false + lastDraftToken = nil + } + + return accepted + } + + /// Generate K draft tokens autoregressively using the draft model. + private mutating func generateDraftTokens(count: Int) -> MLXArray { + guard count > 0 else { + return MLXArray.zeros([0], type: Int32.self) + } + + var draftInput: LMInput.Text + if draftNeedsExtraToken, let extraToken = lastDraftToken { + // Feed [lastDraftToken, nextY] to draft model + let combined = concatenated( + [extraToken.reshaped(1), nextY.tokens.reshaped(1)], + axis: 0 + ) + draftInput = .init(tokens: combined) + draftNeedsExtraToken = false + lastDraftToken = nil + } else { + draftInput = nextY + } + + var draftTokens: [MLXArray] = [] + + for _ in 0 ..< count { + let result = draftModel( + draftInput[text: .newAxis], + cache: draftCache.isEmpty ? nil : draftCache, + state: nil + ) + + // Apply cache quantization to draft + maybeQuantizeKVCache( + cache: &draftCache, + kvBits: kvBits, + kvGroupSize: kvGroupSize, + quantizedKVStart: quantizedKVStart + ) + + // Sample from draft model (greedy for simplicity) + var logits = result.logits[0..., -1, 0...] + logits = processor?.process(logits: logits) ?? logits + let y = sampler.sample(logits: logits) + asyncEval(y) + + draftTokens.append(y) + draftInput = .init(tokens: y) + } + + if draftTokens.isEmpty { + return MLXArray.zeros([0], type: Int32.self) + } + + return concatenated(draftTokens, axis: 0) + } + + // MARK: - IteratorProtocol + + mutating public func next() -> Int? { + if let maxTokens, tokenCount >= maxTokens { + return nil + } + + // Yield from pending buffer first + if !pendingTokens.isEmpty { + let token = pendingTokens.removeFirst() + tokenCount += 1 + + // Periodically clear GPU memory cache + if tokenCount % 256 == 0 { + MLX.Memory.clearCache() + } + + return token + } + + // Run a new speculation round + let accepted = speculateRound() + + guard !accepted.isEmpty else { + return nil + } + + // Put all but the first into the pending buffer + if accepted.count > 1 { + pendingTokens = Array(accepted.dropFirst()) + } + + tokenCount += 1 + + // Periodically clear GPU memory cache + if tokenCount % 256 == 0 { + MLX.Memory.clearCache() + } + + return accepted[0] + } + + // MARK: - Helpers + + /// Convert logits to a sampled token, applying processor and sampler. + private mutating func convertToToken(logits: MLXArray) -> MLXArray { + var logits = logits[0..., -1, 0...] + logits = processor?.process(logits: logits) ?? logits + let y = sampler.sample(logits: logits) + processor?.didSample(token: y) + return y + } + + /// Trim all caches in an array by the given count. + private func trimCache(_ cache: [KVCache], count: Int) { + for c in cache { + c.trim(count) + } + } + + /// Validate that all caches in the array are trimmable. + private static func validateCachesAreTrimmable(_ cache: [KVCache], label: String) { + for (i, c) in cache.enumerated() { + if !c.isTrimmable { + print( + "Warning: \(label) cache layer \(i) is not trimmable. " + + "Speculative decoding requires trimmable caches." + ) + } + } + } + + /// The acceptance rate of draft tokens (0.0 to 1.0). + public var acceptanceRate: Double { + guard draftProposedCount > 0 else { return 0 } + return Double(draftAcceptedCount) / Double(draftProposedCount) + } +} + +// MARK: - Time measurement (private to this file) + +private func speculativeMeasure(_ closure: () throws -> Void) rethrows -> TimeInterval { + let start = Date.timeIntervalSinceReferenceDate + try closure() + let end = Date.timeIntervalSinceReferenceDate + return end - start +}