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
70 changes: 35 additions & 35 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,20 @@ 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: MLXArray?
Expand Down Expand Up @@ -242,7 +249,6 @@ 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)
}
Expand All @@ -258,34 +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`.
/// Keep tokens with probability >= maxProb * minP (log-space).
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`.
/// 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)
}
Expand All @@ -309,10 +307,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
Expand All @@ -327,16 +323,14 @@ 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[..<count] : buffer
}

/// Bulk-load from a prompt. Keeps the last `capacity` tokens.
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)
Expand All @@ -353,7 +347,6 @@ struct TokenRing {
}
}

/// Append a single token using GPU-only mask write (no CPU←GPU sync).
mutating func append(_ token: MLXArray) {
let mask = positions .== Int32(writeIndex)
buffer = MLX.where(mask, token.asType(.int32), buffer)
Expand All @@ -362,12 +355,15 @@ struct TokenRing {
}
}

/// Processor that implements a `repetitionPenalty`.
/// Processor that implements a `repetitionPenalty`
public struct RepetitionContext: LogitProcessor {
private var ring: TokenRing
var ring: TokenRing

/// penalty factor for repeating tokens
let repetitionPenalty: Float

public init(repetitionPenalty: Float, repetitionContextSize: Int) {
precondition(repetitionContextSize > 0)
self.repetitionPenalty = repetitionPenalty
self.ring = TokenRing(capacity: repetitionContextSize)
}
Expand All @@ -377,7 +373,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(
Expand All @@ -394,14 +391,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)
}
Expand All @@ -411,7 +407,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
}
Expand All @@ -422,14 +419,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)
}
Expand All @@ -440,13 +436,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) {
Expand Down Expand Up @@ -695,6 +689,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)
}
}
Expand Down
Loading