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
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,25 @@ for try await event in session.observe(to: "Explain gravity.", using: .logProbab
parameters. This applies to the entire request, including automatic tool restarts,
without changing `generateParameters`, later calls, or forks.

## Model or processed log probabilities

By default the values normalize the logits after the logit processors and before
temperature and sampler filters, as Python MLX-LM does. A repetition or presence
penalty therefore changes them: a token the reply already used looks less likely
than the model thinks it is. Set `source` to ``LogProbabilitySource/model`` to
report the model's logits before any processor:

```swift
let stream = session.observe(
to: "When was the Eiffel Tower built?",
using: .logProbabilities(topCount: 5, source: .model))
```

The sampled tokens stay the same. Use ``LogProbabilitySource/model`` to measure
the model's confidence, and ``LogProbabilitySource/processed`` to see the
distribution the sampler draws from before temperature. Without a processor the
two are identical.

## Custom transformers

A transformer's ``GenerationTransformer/configure(_:)`` enables the computation
Expand Down Expand Up @@ -66,7 +85,8 @@ observations, wrap a ``TextToolTokenLoopHandler`` or ``RawTokenLoopHandler`` in
Enable computation with ``GenerateParameters/logProbabilities`` when constructing
a token iterator: ``TokenIterator``, ``SpeculativeTokenIterator``, or
``MTPSpeculativeTokenIterator``. `nil` disables reporting, `0` reports the selected token,
and a positive value also reports that many top candidates. The ordinary
and a positive value also reports that many top candidates.
``GenerateParameters/logProbabilitySource`` selects the logits they describe. The ordinary
`generate` and `generateTokens` streams do not emit probability events.

```swift
Expand Down
72 changes: 52 additions & 20 deletions Libraries/MLXLMCommon/Evaluate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ public struct GenerateTokenLogProbability: Sendable, Equatable {
/// The vocabulary token ID.
public let token: Int

/// The token's log probability after logit processing and before sampling.
/// The token's log probability before temperature and sampler filters, from the
/// logits that ``GenerateParameters/logProbabilitySource`` selects.
public let logProbability: Float

public init(token: Int, logProbability: Float) {
Expand All @@ -124,9 +125,9 @@ public struct GenerateTokenLogProbability: Sendable, Equatable {

/// Log-probability details for one generated token.
///
/// These values match Python MLX-LM's `GenerationResponse.logprobs`: they
/// normalize the post-processor logits before temperature or sampler filters
/// are applied.
/// These values normalize the logits that ``GenerateParameters/logProbabilitySource``
/// selects, before temperature or sampler filters are applied. The default,
/// ``LogProbabilitySource/processed``, matches Python MLX-LM's `GenerationResponse.logprobs`.
public struct GenerateTokenLogProbabilities: Sendable, Equatable {
/// The token selected by the sampler and its log probability.
public let chosen: GenerateTokenLogProbability
Expand Down Expand Up @@ -155,6 +156,21 @@ public struct GenerateTokenLogProbabilities: Sendable, Equatable {
}
}

/// The logits that reported log probabilities normalize.
public enum LogProbabilitySource: Sendable, Hashable {
/// The logits after the logit processors, such as penalties and suppressed tokens.
case processed

/// The model's logits, before any logit processor. Penalties change what is
/// sampled, not what is reported, so the values show the model's own confidence.
case model

/// The logits to report, of the logits before and after the processors.
func logits<Logits>(model: Logits, processed: Logits) -> Logits {
self == .model ? model : processed
}
}

/// Parameters for text generation, see ``TokenIterator``.
///
/// This produces:
Expand Down Expand Up @@ -253,6 +269,9 @@ public struct GenerateParameters: Sendable {
/// Speculative iterators report the verifier's values for each emitted token.
public var logProbabilities: Int?

/// The logits that ``logProbabilities`` reports. See ``LogProbabilitySource``.
public var logProbabilitySource: LogProbabilitySource = .processed

/// Optional seed for reproducible sampling. When set, the sampler's RNG
/// (`TopPSampler` / `CategoricalSampler`) is seeded deterministically, so
/// the same `(seed, prompt, parameters)` produces the same sampled
Expand Down Expand Up @@ -298,6 +317,7 @@ public struct GenerateParameters: Sendable {
topK: Int = 0,
minP: Float = 0.0,
logProbabilities: Int? = nil,
logProbabilitySource: LogProbabilitySource = .processed,
repetitionPenalty: Float? = nil,
repetitionContextSize: Int = 20,
presencePenalty: Float? = nil,
Expand All @@ -320,6 +340,7 @@ public struct GenerateParameters: Sendable {
self.topK = topK
self.minP = minP
self.logProbabilities = logProbabilities
self.logProbabilitySource = logProbabilitySource
self.repetitionPenalty = repetitionPenalty
self.repetitionContextSize = repetitionContextSize
self.presencePenalty = presencePenalty
Expand Down Expand Up @@ -1010,18 +1031,18 @@ public struct DeferredTokenLogProbabilities {
return -terms.sum(axis: -1)
}

/// Records the log probabilities of tokens sampled from the rows of processed logits.
/// Records the log probabilities of tokens, one row of logits per token.
///
/// One batch serves every row and evaluates in the background, so a speculative round
/// pays one normalization for the tokens it emits, outside its accept loop.
///
/// - Parameters:
/// - tokens: The sampled tokens, in emission order, one or more per array.
/// - logits: The processed logits each token was sampled from, one row per token.
/// - logits: The logits to report for each token, one row per token.
/// - topK: The candidates to report per token; `nil` records nothing.
/// - Returns: One value per token, or none when `topK` is `nil`.
static func recording(
_ tokens: [MLXArray], sampledFrom logits: [MLXArray], topK: Int?
_ tokens: [MLXArray], from logits: [MLXArray], topK: Int?
) -> [DeferredTokenLogProbabilities] {
guard let topK, !tokens.isEmpty else { return [] }
let tokens = concatenated(tokens.map { $0.flattened() })
Expand Down Expand Up @@ -1149,6 +1170,7 @@ public struct TokenIterator: TokenIteratorProtocol {
var processor: LogitProcessor?
let sampler: LogitSampler
let logProbabilityTopK: Int?
let logProbabilitySource: LogProbabilitySource
private var deferredLogProbabilities: DeferredTokenLogProbabilities?

/// Log probabilities for the token returned by the most recent ``next()`` call.
Expand Down Expand Up @@ -1243,6 +1265,7 @@ public struct TokenIterator: TokenIteratorProtocol {
self.processor = components.logitProcessor(parameters: parameters, model: model)
self.sampler = parameters.sampler()
self.logProbabilityTopK = parameters.logProbabilities.map { Swift.max($0, 0) }
self.logProbabilitySource = parameters.logProbabilitySource
self.maxTokens = parameters.maxTokens

self.promptPrefillTime = try measure {
Expand Down Expand Up @@ -1279,6 +1302,7 @@ public struct TokenIterator: TokenIteratorProtocol {
self.processor = processor
self.sampler = sampler
self.logProbabilityTopK = nil
self.logProbabilitySource = .processed
self.maxTokens = maxTokens

self.promptPrefillTime = try measure {
Expand Down Expand Up @@ -1393,8 +1417,8 @@ public struct TokenIterator: TokenIteratorProtocol {

mutating func convertToToken(logits: MLXArray) -> MLXArray {
// process the logits (one hot array of possible tokens)
var logits = logits[0..., -1, 0...]
logits = processor?.process(logits: logits) ?? logits
let modelLogits = logits[0..., -1, 0...]
let logits = processor?.process(logits: modelLogits) ?? modelLogits

// Filtered sampling already normalizes logits, so reuse that distribution.
let y: MLXArray
Expand All @@ -1405,7 +1429,10 @@ public struct TokenIterator: TokenIteratorProtocol {
} else {
y = sampler.sample(logits: logits)
}
self.deferredLogProbabilities = distribution.recording(
let reported =
processor == nil || logProbabilitySource == .processed
? distribution : LogProbabilityDistribution(logits: modelLogits)
self.deferredLogProbabilities = reported.recording(
token: y, topK: logProbabilityTopK)
} else {
self.deferredLogProbabilities = nil
Expand Down Expand Up @@ -1550,6 +1577,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
var processor: LogitProcessor?
let sampler: LogitSampler
let logProbabilityTopK: Int?
let logProbabilitySource: LogProbabilitySource

/// Log probabilities for the token returned by the most recent ``next()`` call.
public private(set) var lastLogProbabilities: DeferredTokenLogProbabilities?
Expand Down Expand Up @@ -1693,6 +1721,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {

self.sampler = parameters.sampler()
self.logProbabilityTopK = parameters.logProbabilities.map { Swift.max($0, 0) }
self.logProbabilitySource = parameters.logProbabilitySource
try components.validate(parameters: parameters)
self.processor = components.logitProcessor(parameters: parameters, model: mainModel)

Expand Down Expand Up @@ -1727,8 +1756,8 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
prefill.progress?(total, total)
case .logits(let result):
mainCacheStorage.commitProcessedTokens(inputLength)
var logits = result.logits[0..., -1, 0...]
logits = processor?.process(logits: logits) ?? logits
let modelLogits = result.logits[0..., -1, 0...]
let logits = processor?.process(logits: modelLogits) ?? modelLogits
let token = sampler.sample(logits: logits)
processor?.didSample(token: token)
y = .init(tokens: token)
Expand All @@ -1737,7 +1766,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
// prefill-sampled token must be queued here or the stream would
// silently start at the second generated token.
pendingTokens.append(token.item(Int.self))
recordLogProbabilities(of: [token], sampledFrom: [logits])
recordLogProbabilities(of: [token], model: [modelLogits], processed: [logits])
}

// Prefill draft model, don't call didSample here -- processor tracks main model's accepted sequence only
Expand Down Expand Up @@ -1829,6 +1858,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
mainCacheStorage.commitProcessedTokens(verifyInput.cacheSequenceLength)
}
let mainLogits = mainResult.logits
let modelLogits = mainLogits[0..., verifyStart..., 0...].squeezed(axis: 0)
state = mainResult.state

let mainTokens: MLXArray
Expand All @@ -1849,7 +1879,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
verifyLogits = concatenated(processed)
} else {
// Batch-sample all verify tokens from main model in one operation
verifyLogits = mainLogits[0..., verifyStart..., 0...].squeezed(axis: 0)
verifyLogits = modelLogits
mainTokens = sampler.sample(logits: verifyLogits)
}

Expand All @@ -1874,7 +1904,8 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
processor?.didSample(token: finalToken)
pendingTokens.append(mainTokensList[accepted])
recordLogProbabilities(
of: [mainTokens[0 ... accepted]], sampledFrom: [verifyLogits[0 ... accepted]])
of: [mainTokens[0 ... accepted]], model: [modelLogits[0 ... accepted]],
processed: [verifyLogits[0 ... accepted]])
mainCommittedPendingTokenCount = accepted
// When every draft is accepted the draft cache still trails the main
// cache by one accepted token; `draftY` carries that token into the
Expand Down Expand Up @@ -1932,13 +1963,13 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {
let result = mainModel(y[text: .newAxis], cache: mainCache, state: state)
mainCacheStorage.commitProcessedTokens(y.cacheSequenceLength)
state = result.state
var logits = result.logits[0..., -1, 0...]
logits = processor?.process(logits: logits) ?? logits
let modelLogits = result.logits[0..., -1, 0...]
let logits = processor?.process(logits: modelLogits) ?? modelLogits
let token = sampler.sample(logits: logits)
processor?.didSample(token: token)
eval(token)
pendingTokens.append(token.item(Int.self))
recordLogProbabilities(of: [token], sampledFrom: [logits])
recordLogProbabilities(of: [token], model: [modelLogits], processed: [logits])
mainCommittedPendingTokenCount = 0
draftCommittedPendingTokenCount = 0
y = .init(tokens: token)
Expand All @@ -1947,10 +1978,11 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol {

/// Records the verifier's log probabilities for tokens just queued in `pendingTokens`.
private mutating func recordLogProbabilities(
of tokens: [MLXArray], sampledFrom logits: [MLXArray]
of tokens: [MLXArray], model: [MLXArray], processed: [MLXArray]
) {
pendingLogProbabilities += DeferredTokenLogProbabilities.recording(
tokens, sampledFrom: logits, topK: logProbabilityTopK)
tokens, from: logProbabilitySource.logits(model: model, processed: processed),
topK: logProbabilityTopK)
}

/// Returns the next queued token and makes its log probabilities current.
Expand Down
13 changes: 10 additions & 3 deletions Libraries/MLXLMCommon/GenerationTransformer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,17 @@ public struct LogProbabilityGenerationTransformer: GenerationTransformer {
/// Number of top candidates. Values at or below zero report only the chosen token.
public var topCount: Int

public init(topCount: Int = 0) {
/// The logits the values describe. See ``LogProbabilitySource``.
public var source: LogProbabilitySource

public init(topCount: Int = 0, source: LogProbabilitySource = .processed) {
self.topCount = topCount
self.source = source
}

public func configure(_ parameters: inout GenerateParameters) {
parameters.logProbabilities = topCount
parameters.logProbabilitySource = source
}

public func makeHandler(wrapping base: TextToolTokenLoopHandler)
Expand All @@ -84,8 +89,10 @@ public struct LogProbabilityGenerationTransformer: GenerationTransformer {

extension GenerationTransformer where Self == LogProbabilityGenerationTransformer {
/// Observe chosen-token log probabilities and, optionally, the top candidates.
public static func logProbabilities(topCount: Int = 0) -> Self {
.init(topCount: topCount)
public static func logProbabilities(
topCount: Int = 0, source: LogProbabilitySource = .processed
) -> Self {
.init(topCount: topCount, source: source)
}
}

Expand Down
Loading
Loading