Repository navigation
evaluate: populate per-token data for PPL and KLD (opt-in, ~zero overhead) - #48
Merged
Merged
Conversation
…head)
GenerateCompletionInfo declared thinkingPerplexity / generationPerplexity /
perTokenLogProbs / perTokenIds / perTokenPhases, and GenerateParameters
exposed trackPerplexity / collectPerTokenData, but nothing in the
generation loop populated any of them. Downstream consumers
(benchmark harness PPL columns, KLD forced-decode at
InferenceBenchmark.swift:854, anywhere that branches on completionInfo.
perTokenIds != nil) silently read nil and did nothing.
This change wires the capture without touching the inference path when
the flags are off.
New types (Libraries/MLXLMCommon/Evaluate.swift, near TokenIteratorProtocol):
- PerTokenData — the flushed, phase-labeled, per-token result with
precomputed thinkingPerplexity / generationPerplexity.
- PerTokenDataCapture — reference-type box holding lazy MLXArray handles
during the loop. Class (not struct) is required because TokenIterator
is a struct and `for token in iterator` copies it; the class lets
appends from the for-in's copy be visible to the outer iterator.
- GenerateParameters.needsPerTokenCapture — single source of truth for
whether capture is on (trackPerplexity || collectPerTokenData).
TokenIteratorProtocol gets finalizePerTokenData() with a default nil
implementation so SpeculativeTokenIterator opts out automatically.
PPL/KLD with speculative decoding is a separate workstream.
TokenIterator changes:
- Three new stored fields: thinkStartTokenId / thinkEndTokenId /
thinkingPhasePrefilled (carried from GenerateParameters so the
finalizer can label phases without an API change to the outer
generateLoopTask), plus the optional perTokenCapture box.
- All three init overloads wired: the two `parameters:` inits enable
capture when either flag is set; the manual processor/sampler init
always disables (that entry point doesn't carry thinking config).
- convertToToken(logits:) gets a single `if let capture = perTokenCapture`
block emitting the lean kernel chain:
let lse = logSumExp(logits, axes: [-1]) // 1 reduction
let yLogit = takeAlong(logits, y.expandedDimensions(axis:-1),
axis: -1) // scalar gather
let selected = yLogit - lse
asyncEval(selected)
Scalar output. Does NOT materialise a full-vocab logSoftmax buffer
(V can be 250k+ tokens → 1MB per step on decode). asyncEval detaches
the subgraph so it runs concurrently with the next forward pass rather
than blocking it.
- New non-mutating finalizePerTokenData(): concatenates all captured
1-element tensors into one [N] tensor, does a SINGLE GPU→CPU transfer
for the whole generation, labels phases in pure Swift based on stored
think-start/end ids + thinkingPhasePrefilled, computes exp(-mean(lp))
per phase.
Generation-loop wiring (two call sites):
- Async path (generateLoopTask): moved Stream().synchronize() ahead of
the info-event emit (it was already at the end of the function — we
just need it before the finalize), called iterator.finalizePerTokenData(),
and plumbed the 5 fields into GenerateCompletionInfo.
- Sync path (deprecated generate(input:context:iterator:didGenerate:)
returning GenerateCompletionInfo): same finalize call after
runSynchronousGenerationLoop (which already synchronizes).
Performance validation (M1 Max, Qwen3.5-0.8B 4bit, 1024 ctx, 5 runs each):
Flags OFF Flags ON Delta
Prefill 236.4 ± 2.2 239.6 ± 2.2 +1.4% (within noise)
Decode 159.5 ± 7.9 161.1 ± 4.4 +1.0% (within noise)
The first-pass implementation used logSoftmax(logits) materialising a
[1, V] buffer and showed ~8% decode regression. Switching to the
scalar-output logSumExp + takeAlong chain got overhead into the noise
floor on this workload.
Correctness validation (same config, --ppl --kld --think):
4bit / no-quant: Think PPL 2.31, Gen PPL 1.07, Think KLD 0.27, Gen KLD 0.31
4bit / turbo4v2: Think PPL 3.39, Gen PPL 1.98, Think KLD 0.32, Gen KLD 0.41
KLD is directionally correct: turbo4v2 (more aggressive KV compression)
diverges more from the bf16 baseline. The benchmark harness's KLD
forced-decode path at InferenceBenchmark.swift:854 — previously dead
because perTokenIds was always nil — now fires.
xcodebuild test -scheme mlx-swift-lm-Package -only-testing MLXLMTests:
54 tests in 4 suites passed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Extends PPL/KLD support to harmony-format models (GPT-OSS 20B) whose
reasoning is delimited by channel transitions rather than a bracketed
start/end token pair. Previously `supportsThinking: false` in the
registry — accurate for what the harness could DO, misleading for what
the model actually emits — so harmony reasoning tokens were silently
lumped into the "gen" phase.
What's in this commit
GenerateParameters (Libraries/MLXLMCommon/Evaluate.swift):
- New optional fields, additive — no existing call sites need changes:
harmonyChannelMarkerTokenId: Int32? // e.g. 200005 = <|channel|>
harmonyThinkingChannelTokenIds: [Int32] // e.g. [35644] = analysis
harmonyGenerationChannelTokenIds: [Int32] // e.g. [17196] = final
TokenIterator:
- Stores the three harmony fields alongside existing thinkStart/End.
- labelPhases(_:) dispatches: harmony state machine if markerId set,
bracket-pair state machine if thinkStart/End set, otherwise every
token labelled "gen". The harmony SM is ~20 lines: on each token,
check if it is the marker; if so, flag awaitingChannelName and keep
the current phase for this token; on the next token, consult the
thinking/generation sets to flip phase. Unknown channel names leave
phase unchanged.
- No inference-path changes — phase labeling runs once in the
finalizer after Stream().synchronize().
Phase string alignment:
- Changed finalizer output from "thinking"/"generation" to "think"/"gen"
to match the long-standing BaselineTokenData.phases convention at
InferenceBenchmark.swift:288 and the checks at :1592. The earlier
PPL/KLD commit left these mismatched; KLD worked only because of a
bracket-based fallback detector at :1584 that is harmony-blind.
With the strings aligned, the primary phase-string check fires for
both bracket and harmony models.
ModelRegistry (Tests/Benchmarks/Utils/ModelRegistry.swift):
- ThinkingConfig.style is now an enum:
.bracket(start: String, end: String)
.harmonyChannel(marker: String,
thinkingChannels: [String],
generationChannels: [String])
- `.qwen` and `.gemma4` statics migrate to .bracket; new `.harmony`
static describes GPT-OSS's channels (analysis → thinking;
final, commentary → generation).
- gpt-oss-20b entry flipped to supportsThinking: true,
thinkingConfig: .harmony.
InferenceBenchmark token resolution:
- The token-ID resolution block at line 634 rewrote to dispatch on
ThinkingConfig.Style. Bracket models resolve startId + endId as
before; harmony models resolve markerId + channel-name IDs and
populate the new GenerateParameters harmony fields. Startup log
gains a "[BENCH] Harmony channel marker=… thinking=… generation=…"
line when the harmony path is taken.
--reasoning flag (scripts/benchmark.sh + BenchEnv):
- New CLI flag with default "medium". Accepts low/medium/high (warns
rather than errors on other values — future model vocabularies pass
through). Plumbed through MLX_BENCH_REASONING env var to
BenchEnv.reasoningEffort, which overrides family.reasoningEffort at
the GenerateParameters construction site. Harness prints
"Think: yes (reasoning=…)" when --think is active. A new
"[INFO] PPL: yes" line is also emitted for parity with --kld /
--think logging.
Docs (benchmarks/README.md):
- --reasoning added to the CLI flags table.
- MLX_BENCH_REASONING added to the environment variables table.
- Quick Start gains a GPT-OSS + --reasoning + --think + --ppl example.
Validation (M1 Max, GPT-OSS 20B 4bit / turbo4v2, --think --kld --ppl)
Harness log confirms harmony resolution:
Harmony channel marker=200005, thinking=[35644], generation=[17196]
Forced decode output for three configurations:
ctx / reasoning Think/Gen tokens Think PPL Think KLD
ctx=1024 / reasoning=medium 199 / 1 2.47 0.39
ctx=1024 / reasoning=low 199 / 1 3.03 0.64
ctx=128 / reasoning=low 199 / 1 2.34 0.62
All 199 reasoning tokens attributed to "think" phase. The single
"gen" token is the initial <|channel|> marker itself (labeled with
the pre-transition phase by design — Gen PPL ~ 1.00 confirms the
model was virtually certain <|channel|> was the first token).
Previous GPT-OSS runs showed think=0 / gen=400 because the harness
lacked any way to detect the channel transition; now think-phase
tokens are attributed correctly and Think KLD reflects reasoning-
phase divergence from the bf16 baseline.
Qwen3.5 and Gemma4 bracket models are unaffected — same token
resolution path, same labeling semantics, just on the renamed
"think"/"gen" strings.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
5 tasks done
Two issues surfaced once harmony phase detection shipped: GPT-OSS continued to spend all of its --think token budget reasoning and never emitted a final-channel answer, and the KLD forced-decode loop re-applied the bracket-only effectiveMaxTokens cap so it stopped processing at 200 tokens regardless of how many the target generated. Both are fixed here; together they let --ppl --kld --think produce meaningful numbers for both reasoning and visible answer on GPT-OSS. Budget parity (effectiveMaxTokens) Previously `effectiveMaxTokens = thinkStartId != nil ? budget + max : max`, which gated the `+ budget` addition on bracket-only thinking. Harmony models (harmonyMarkerId set, thinkStartId nil) fell through to the short branch and got HALF the token budget. Switched to a `hasThinkingBudget = thinkStartId != nil || harmonyMarkerId != nil` check — both paths now reserve the same `thinkingBudget` reasoning tokens on top of the `maxTokens` answer budget. Same-shaped bug in forcedDecodeKLD capped the forced-decode loop at `min(tokenIds.count, effectiveMaxTokens)` — bracket-only. Replaced with `tokenIds.count`; the captured target sequence is already bounded by the generation loop's own budget, so recapping here only dropped data (200 captured tokens instead of all 400 target tokens were being fed through the baseline model). HarmonyThinkingBudgetProcessor Analogue of ThinkingBudgetProcessor for channel-transition models. State machine: 1. Watch for <|channel|> marker, then the following channel-name token. On `analysis` set inThinking=true and reset thinkingTokenCount. On `final`/`commentary` set inThinking=false. 2. While inThinking, count tokens and suppress EOS so the model cannot quit mid-reasoning. 3. When thinkingTokenCount reaches maxThinkingTokens, arm forceIndex=0. 4. Next N process() calls pin the sampler to `forcedTransitionSequence[forceIndex]` — for GPT-OSS this is <|end|> <|start|> assistant <|channel|> final <|message|> (6 tokens). Token pinning uses the same large-finite logit trick (100.0) as ThinkingBudgetProcessor — softmax(+inf) would produce NaN which the sampler misroutes. 5. After the transition completes, suppress entry back into the analysis channel so the model can't oscillate into reasoning during the final answer. Extended ThinkingConfig.harmonyChannel with a `transitionSequence` associated value that lists the token strings to force; the harness resolves them to IDs at startup and hands the Int32 array to the processor at construction. GPT-OSS's `.harmony` config gets the full 6-token sequence. A nil/missing entry in the resolution table silently disables the processor (no force) rather than panic — the generation still runs, it just isn't budget-enforced. The bracketBudgetProcessor and harmonyBudgetProcessor are mutually exclusive — exactly one keys off the active thinking style. Both are appended to additionalProcessors when present so CompositeLogitProcessor sees them; only one ever fires for a given run. Caveat: the 6 forced tokens land in GenerateCompletionInfo.perTokenLogProbs with logprob ~= 0 (we pinned the sampler). They very slightly bias per-phase PPL toward 1.0 — bounded contribution (6 tokens out of hundreds) and not material to the signal we care about (reasoning- phase PPL / KLD comparisons across KV configs). Left as-is; documented in the processor's doc comment. scripts/benchmark.sh adds `[HARMONY]` to the log-filter pattern so future harmony-side diagnostics flow through to the terminal when added (none ship in this commit). Validation (M1 Max, GPT-OSS 20B 4bit/turbo4v2, --ppl --kld --think --reasoning medium) Before: Generation 400 tokens, Think/Gen = 199/1, Gen PPL = 1.00 (degenerate), Gen KLD = 0.00 (degenerate). Model ran out of tokens mid-reasoning. After: Generation 300 tokens, Think/Gen = 205/97, Gen PPL = 1.82, Gen KLD = 0.47. Model emits a real final-channel answer; Gen KLD reflects the 4-bit turbo4v2 model's answer-distribution divergence from the bf16 baseline. The 205 think count is 200 reasoning content + 5 transition tokens that labelPhases attributes to "think" (everything up to and including <|channel|> in the transition sequence). The 97 gen count is the `final` name token, `<|message|>`, and ~95 actual answer tokens. Qwen3.5 and Gemma 4 bracket paths are unchanged: Qwen3.5 0.8B 4bit turbo4v2 ctx 128 still produces Think/Gen = 201/200 with Think PPL 2.34 / Gen PPL 1.13 / Think KLD 0.58 / Gen KLD 0.24. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…arams
Two related Parameters-table cleanups.
Parse max_ops_per_buffer from device.cpp
The hardware-default switch in BenchmarkWriter mirrored the one in
mlx/backend/metal/device.cpp by hand. Committed truth drifted:
device.cpp had 100 for Max/Ultra while the Swift table returned 200,
so the Parameters block reported the wrong default in every run
that didn't set MLX_MAX_OPS_PER_BUFFER.
Fix: resolve the value at runtime by parsing device.cpp directly
from the mlx-swift dependency's on-disk source (same source the
linked mlx library was built from, so the two can't diverge).
Resolution order:
1. $MLX_SWIFT_PATH/Source/Cmlx/mlx/mlx/backend/metal/device.cpp
2. {projectRoot}/../mlx-swift/... (sibling checkout)
3. {projectRoot}/.build/checkouts/mlx-swift/... (SPM cache)
Parser finds the `case 'X':` in Device::Device() matching the current
GPU arch suffix, then grabs the first `max_ops_per_buffer_ = N;` in
that case block. If any step fails (file missing, format drifted,
no matching case) the function falls back to a conservative
hardcoded table whose values track the committed defaults.
The Parameters row now carries a three-state provenance label:
"N (env)" — MLX_MAX_OPS_PER_BUFFER was set
"N (from device.cpp, <arch>)" — parsed live from source
"N (fallback, <arch>)" — device.cpp not located/parseable
Verified locally: the label now reads
`100 (from device.cpp, applegpu_g13s)`
on a fresh M1 Max run (matching the committed device.cpp value).
Previously it read `200 (hardware default, applegpu_g13s)` — stale.
Group speculative + n-gram fields
The Parameters table listed "N-gram size" and "Max n-gram draft
tokens" next to "Collect per-token data", while "Speculative
decoding" (the enclosing strategy name) sat many rows below near
batch size. Reordered the whole table into seven semantic groups
so related knobs read together:
KV cache → Generation budget → Sampling → Penalties →
Thinking / reasoning → Speculative decoding → Telemetry / runtime
Under Speculative decoding, the strategy name now sits immediately
above the n-gram parameters so readers see "Speculative decoding:
ngram (size=3, maxDraft=3)" then the two underlying size / draft
rows as a unit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…GPT-OSS)
After the previous PPL / KLD / harmony commits landed, GPT-OSS 20B with
--think --kld --ppl showed a ~33% decode regression at 1024 ctx vs the
no-flags baseline. Qwen3.5 0.8B with the same flags showed only ~1-2%.
The gap meant something was touching the hot path that hurt much more
on a 20B MoE than on a 0.8B dense.
Root cause: `token.item(Int32.self)` in the budget processors' didSample
Both `ThinkingBudgetProcessor` and `HarmonyThinkingBudgetProcessor`
extracted the sampled token's integer ID inside `didSample(token:)` via
`.item(Int32.self)`. `MLXArray.item()` calls `eval()` internally — a
blocking GPU→CPU synchronisation. One sync per token, called from
inside `convertToToken` BEFORE the next forward pass could dispatch.
When no processors are active (e.g. GPT-OSS flags-off, where no
repetition/presence penalties are registered for the family), the per-
step sync path is empty and the pipeline stays full. When a budget
processor joins the chain, every step now serialises on that sync
point, blocking issue of step N+1's forward pass until step N has
fully materialised on CPU. On a 20B MoE each forward is ~15-25 ms so
the stall dominates; on a 0.8B dense (~10 ms) it's barely visible —
explaining the divergence in observed regression.
Isolation test confirmed this is not a logprob-capture cost: running
`--ppl` only (no --think) on GPT-OSS at 1024 ctx turbo4v2 matched the
no-flags decode within 1%. The hit is specifically from --think
engaging the budget processor.
Three related fixes
1. Batched state-machine updates (primary)
`didSample` no longer calls `.item()` per token. Instead it appends
the lazy MLXArray to a `pendingTokens` queue and returns immediately,
letting the next forward pass dispatch without delay. The queue is
flushed every N tokens (default batch size 10) via a single
`eval(pendingTokens)` + id extraction pass, then the state machine
is run over the drained IDs in order.
Dynamic flush threshold: shrinks as we approach the thinking budget
so forcing triggers within a few tokens of the configured limit:
headroom=100 → flush every 10
headroom=5 → flush every 2
headroom=0 → flush every 1
Maximum overshoot ≤ flushBatchSize = 10 tokens, ≤5% of a typical
200-token budget.
2. Pre-computed EOS suppression mask
The scatter-per-EOS-token loop inside `process(logits:)`:
for eosId in eosTokenIds { modified[eosId] = -inf }
dispatched N scatter kernels per generation step during the
thinking phase. Replaced with a lazily-built `[V]` additive mask
constructed host-side and added once per call (one elementwise-add
kernel). Same for the post-exhaustion `<think>` / analysis-channel
suppression. 2-5 kernel dispatches → 1 per step.
Because `LogitProcessor.process(logits:)` is non-mutating on the
protocol, the cache lives in a `SuppressMaskCache` reference-type
box held by both processor structs. Stays const from the struct's
perspective; populates on first call.
3. Skip sync during forced transition (harmony)
During the 6-token force-emit in `HarmonyThinkingBudgetProcessor`,
each sampled token is deterministically the one we pinned in
`process()`. `didSample` now advances `forceIndex` without
appending to `pendingTokens` (no sync, no state-machine pass) —
saves 6 item() calls per thinking episode.
Validation (M1 Max, GPT-OSS 20B 4bit, ctx=1024, --ppl --kld --think)
Before fix After fix Baseline (no flags)
no-quant prefill 433.6 tok/s 667.8 tok/s 615.8 tok/s
no-quant decode 43.0 tok/s 68.1 tok/s 63.9 tok/s
turbo4v2 prefill 401.0 tok/s 674.0 tok/s 590.6 tok/s
turbo4v2 decode 42.3 tok/s 52.0 tok/s 53.3 tok/s
Flag-on decode now matches the flag-off baseline within noise
(+6.6% on no-quant, -2.4% on turbo4v2). Prefill regression
eliminated — flag-on prefill is slightly *faster* than flag-off
(masks upload once at first call; warmed caches).
Qwen3.5 0.8B bracket-path sanity check (ctx=1024 turbo4v2
--ppl --kld --think): prefill 246 / decode 159.7, think=201 gen=200
forced-decode split exactly respects the 200-token budget. Dynamic
flush threshold near the budget ceiling prevents overshoot on
bracket paths where exact accounting matters.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Actually populates the
GenerateCompletionInfofields that already existed on alpha as declared-only —thinkingPerplexity,generationPerplexity,perTokenLogProbs,perTokenIds,perTokenPhases. Before this change, every downstream consumer (benchmark harness PPL columns, the KLD forced-decode atInferenceBenchmark.swift:854, anyif let ids = info.perTokenIdsbranch) silently readnil.One commit:
67bf0c4—Libraries/MLXLMCommon/Evaluate.swiftonly, +218 / −5 net.Design goals
if let capture = perTokenCaptureguard — no extra MLX ops, no extra buffers, no extra syncs. The optimizer hoists the nil branch in the hot loop.asyncEval, so the logprob computation runs concurrently with the next forward pass rather than blocking it.GenerateCompletionInfofields andGenerateParametersflags already exist. This just populates them.TokenIteratorProtocol.finalizePerTokenData()has a defaultnilimplementation;SpeculativeTokenIteratoropts out automatically. PPL/KLD with spec decoding is a separate workstream.What's in the commit
New types near
TokenIteratorProtocol:public struct PerTokenData— flushed, phase-labeled per-token result with precomputed PPL.final class PerTokenDataCapture— reference-type box holding lazyMLXArrayhandles during the loop. Class (not struct) is required becauseTokenIteratoris a struct andfor token in iteratorcopies it; the shared reference lets the for-in's mutations reach the outer iterator.GenerateParameters.needsPerTokenCapture—trackPerplexity || collectPerTokenData.TokenIteratorchanges:thinkStartTokenId/thinkEndTokenId/thinkingPhasePrefilled(copied fromGenerateParametersso the finalizer can label phases without threading parameters throughgenerateLoopTask), plus the optionalperTokenCapturebox.convertToToken(logits:)gets a 7-line capture block emitting the lean scalar-output chain:finalizePerTokenData(): concatenates all captured 1-element tensors into one[N]tensor, performs a single GPU→CPU transfer for the whole generation, labels phases in pure Swift, computesexp(-mean(lp))per phase.Generation-loop wiring (both the async
generateLoopTaskand the deprecated syncgenerate(input:context:iterator:didGenerate:)returningGenerateCompletionInfo) callsiterator.finalizePerTokenData()and plumbs the five fields into theGenerateCompletionInfoconstructor.[INFO] PPL: yeslog line atscripts/benchmark.sh— cosmetic parity with--kldand--thinkwhich we already log.Performance validation
M1 Max, Qwen3.5-0.8B 4bit
none, summarization, 1024 ctx, 5 runs each:A first-pass implementation used
logSoftmax(logits)(materialising a[1, V]buffer) and showed ~8% decode regression. Swapping it for the scalar-outputlogSumExp + takeAlong - subtractchain got overhead into the noise floor.Correctness validation
Same config with
--ppl --kld --think:KLD is directionally correct — turbo4v2 (K 4-bit, V 2-bit asymmetric) diverges more from the bf16 baseline than
nonedoes. The benchmark harness's KLD forced-decode path atInferenceBenchmark.swift:854— previously dead code becauseperTokenIdswas always nil — now fires as designed.Test plan
xcodebuild test -scheme mlx-swift-lm-Package -only-testing MLXLMTests— 54 tests, 4 suites, passes. Verified locally at 41s../scripts/benchmark.sh --model qwen35-0.8b --quant 4bit --kv none --method summarization --context 1024(no flags) — prefill/decode tok/s within ~2% of pre-change baseline. Confirms the nil-branch path stays inert../scripts/benchmark.sh --model qwen35-0.8b --quant 4bit --kv none,turbo4v2 --method summarization --context 128 --ppl --kld --think— all four PPL/KLD columns populate with finite values; turbo4v2 KLD > none KLD.SpeculativeTokenIterator) still works — uses the protocol's defaultfinalizePerTokenData() → nil, info event emitted with nil PPL/KLD as before.Follow-ups (not in this PR)
SpeculativeTokenIteratorcurrently returnsnilfrom the default protocol method. A separate PR.