Repository navigation
Continuous batching 4/8: BatchGenerationEngine + Mistral3 per-row scaling - #27
ronaldmannak wants to merge 4 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a continuous-batching engine for MLX-LM, implementing core components such as BatchGenerationEngine, DecodeBatch, and PrefillBatch to enable efficient batched inference. The review feedback identifies several critical improvements: fixing a potential crash in DecodeBatch when handling empty batches, correcting the order of operations for penalty processing to apply them to raw logits rather than log-probabilities, ensuring the engine correctly defaults to the configured state machine, and optimizing performance by batching eval calls in PrefillBatch.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| if !keep.isEmpty { | ||
| nextTokens = take(nextTokens, keepArr, axis: 0) | ||
| } |
There was a problem hiding this comment.
When the batch becomes empty (i.e., keep is empty), nextTokens is not updated and retains its stale values from the previous step. If this empty batch is later extended with another batch, nextTokens will be concatenated with the new tokens, leading to a shape mismatch and runtime crash. Removing the !keep.isEmpty check ensures nextTokens is always kept in sync with the batch size.
nextTokens = take(nextTokens, keepArr, axis: 0)There was a problem hiding this comment.
Fixed (hardening; the crash wasn't reachable). nextTokens is now updated unconditionally so an emptied batch stays consistent with its sibling arrays. Reachability note: the engine discards a drained batch (generationBatch = nil) and adoptActiveBatch rejects empty batches, and even under direct misuse extend would trap on the layer-count precondition (promptCache.count == 0) before the stale-nextTokens concat - so this was an internal inconsistency, not a reachable crash.
Generated by Claude Code
| let sampleLogits = | ||
| stepLogits.dtype == .bfloat16 ? stepLogits.asType(.float32) : stepLogits | ||
| let logprobs = sampleLogits - logSumExp(sampleLogits, axis: -1, keepDims: true) | ||
| var samples: [MLXArray] = [] | ||
| samples.reserveCapacity(uids.count) | ||
| for i in 0 ..< uids.count { | ||
| // Drive this row's penalty processor incrementally, exactly as | ||
| // the single `TokenIterator` does: feed it the current input | ||
| // token (`currentTokens[i]`, which was the previous step's | ||
| // sampled token), then `process()` the row's logit slice before | ||
| // the sampler runs. With the prompt prefix loaded in the | ||
| // constructor, the ring holds the full history through the | ||
| // current token at `process()` time -- matching the single | ||
| // path's `process -> sample -> didSample` invariant. These are | ||
| // GPU-only mask writes (see `TokenRing`), so they don't force a | ||
| // CPU sync and preserve `asyncEval` pipelining. | ||
| var rowLogprobs = logprobs[i ..< (i + 1), 0...] | ||
| if processors[i] != nil { | ||
| processors[i]?.didSample(token: currentTokens[i ..< (i + 1)]) | ||
| rowLogprobs = processors[i]?.process(logits: rowLogprobs) ?? rowLogprobs | ||
| } | ||
| let sampler = samplers[i] ?? fallbackSampler | ||
| samples.append(sampler(rowLogprobs)) | ||
| } | ||
| sampledTokens = concatenated(samples, axis: 0) |
There was a problem hiding this comment.
The per-row penalty processors are currently run on log-probabilities (logprobs) instead of raw logits. This mathematically distorts the penalties (which are designed to be applied to raw logits). Processing raw logits first and then computing log-probabilities per row resolves this issue.
let sampleLogits =
stepLogits.dtype == .bfloat16 ? stepLogits.asType(.float32) : stepLogits
var samples: [MLXArray] = []
samples.reserveCapacity(uids.count)
for i in 0 ..< uids.count {
// Drive this row's penalty processor incrementally, exactly as
// the single `TokenIterator` does: feed it the current input
// token (`currentTokens[i]`, which was the previous step's
// sampled token), then `process()` the row's logit slice before
// the sampler runs. With the prompt prefix loaded in the
// constructor, the ring holds the full history through the
// current token at `process()` time -- matching the single
// path's `process -> sample -> didSample` invariant. These are
// GPU-only mask writes (see `TokenRing`), so they don't force a
// CPU sync and preserve `asyncEval` pipelining.
var rowLogits = sampleLogits[i ..< (i + 1), 0...]
if processors[i] != nil {
processors[i]?.didSample(token: currentTokens[i ..< (i + 1)])
rowLogits = processors[i]?.process(logits: rowLogits) ?? rowLogits
}
let rowLogprobs = rowLogits - logSumExp(rowLogits, axis: -1, keepDims: true)
let sampler = samplers[i] ?? fallbackSampler
samples.append(sampler(rowLogprobs))
}
sampledTokens = concatenated(samples, axis: 0)There was a problem hiding this comment.
Fixed - confirmed. Penalties now run on RAW per-row logit slices, then each processed row is log-softmaxed individually before its sampler, matching TokenIterator's process-before-logSoftmax order (RepetitionContext branches on logit sign, so logprobs input inverted the penalty for positive-logit tokens). Penalty-free rows keep the shared batched logprobs node (MLX's laziness makes it free when unused). Added a capture test: a +4-peak fixture model asserts the processor sees values > 1, which logprobs (always <= 0) cannot produce.
Generated by Claude Code
| let batch = DecodeBatch( | ||
| model: model, | ||
| uids: uids, | ||
| seedTokens: seedTokens, | ||
| promptCache: caches, | ||
| tokens: priorTokens, | ||
| maxTokens: maxTokens, | ||
| samplers: samplers, | ||
| fallbackSampler: defaultSampler, | ||
| fallbackIsGreedy: defaultSamplerIsGreedy, | ||
| processors: processorSources.map { sources in | ||
| sources.map { $0?() } | ||
| }, | ||
| stateMachines: stateMachines, | ||
| numTokens: numTokens | ||
| ) |
There was a problem hiding this comment.
When stateMachines is nil in makeAdoptedBatch, it currently passes nil to DecodeBatch, which defaults to installing a never-matching matcher (StopSequenceMatcher()). It should instead default to the engine's defaultStateMachine to match the expected behavior.
| let batch = DecodeBatch( | |
| model: model, | |
| uids: uids, | |
| seedTokens: seedTokens, | |
| promptCache: caches, | |
| tokens: priorTokens, | |
| maxTokens: maxTokens, | |
| samplers: samplers, | |
| fallbackSampler: defaultSampler, | |
| fallbackIsGreedy: defaultSamplerIsGreedy, | |
| processors: processorSources.map { sources in | |
| sources.map { $0?() } | |
| }, | |
| stateMachines: stateMachines, | |
| numTokens: numTokens | |
| ) | |
| let batch = DecodeBatch( | |
| model: model, | |
| uids: uids, | |
| seedTokens: seedTokens, | |
| promptCache: caches, | |
| tokens: priorTokens, | |
| maxTokens: maxTokens, | |
| samplers: samplers, | |
| fallbackSampler: defaultSampler, | |
| fallbackIsGreedy: defaultSamplerIsGreedy, | |
| processors: processorSources.map { sources in | |
| sources.map { $0?() } | |
| }, | |
| stateMachines: stateMachines ?? Array(repeating: defaultStateMachine, count: tokens.count), | |
| numTokens: numTokens | |
| ) |
There was a problem hiding this comment.
Fixed. makeAdoptedBatch now defaults nil stateMachines to the engine's EOS matcher (the same default insert applies), so adopted rows honor EOS instead of running to maxTokens on a never-matching matcher.
Generated by Claude Code
| for cache in promptCache { | ||
| eval(cache.innerState()) | ||
| } |
There was a problem hiding this comment.
Evaluating each cache's inner state individually in a loop triggers multiple separate eval calls, which increases driver overhead. Collecting all cache states and evaluating them in a single eval call is much more efficient.
let statesToEval = promptCache.flatMap { $0.innerState() }
if !statesToEval.isEmpty {
eval(statesToEval)
}There was a problem hiding this comment.
Fixed - now one combined eval over all caches' innerState per chunk, so N GPU sync points become 1, mirroring the single path's whole-array eval(cache).
Generated by Claude Code
| for cache in promptCache { | ||
| cache.finalizeBatched() | ||
| eval(cache.innerState()) | ||
| } |
There was a problem hiding this comment.
Evaluating each cache's inner state individually in a loop during finalization triggers multiple separate eval calls. Collecting all cache states and evaluating them in a single eval call after finalization is much more efficient.
for cache in promptCache {
cache.finalizeBatched()
}
let statesToEval = promptCache.flatMap { $0.innerState() }
if !statesToEval.isEmpty {
eval(statesToEval)
}There was a problem hiding this comment.
Fixed. finalizeBatched() now runs for all caches first (the rolls are lazy), followed by a single combined eval, instead of interleaving one sync per cache.
Generated by Claude Code
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a1983c7fbc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| var rowLogprobs = logprobs[i ..< (i + 1), 0...] | ||
| if processors[i] != nil { | ||
| processors[i]?.didSample(token: currentTokens[i ..< (i + 1)]) | ||
| rowLogprobs = processors[i]?.process(logits: rowLogprobs) ?? rowLogprobs |
There was a problem hiding this comment.
Run penalty processors on raw logits
When a row is inserted with processorSources from GenerateParameters that include a repetition penalty, this calls LogitProcessor.process on log-probabilities (rowLogprobs) rather than raw logits. The single TokenIterator applies processors before logSoftmax, and RepetitionContext branches on logit sign; after logSoftmax nearly every value is negative, so repeated positive-logit tokens are penalized differently and batched generation diverges from single-stream for the same parameters.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed - same as the parallel thread from gemini: processors now see raw logits per row with per-row log-softmax after processing, and a parity capture test was added. Details are in the reply on that thread.
Generated by Claude Code
| processors: processorSources.map { sources in | ||
| sources.map { $0?() } | ||
| }, | ||
| stateMachines: stateMachines, |
There was a problem hiding this comment.
Honor engine EOS defaults for adopted batches
When the single-to-batch adoption path calls makeAdoptedBatch without explicit stateMachines (the default), this forwards nil and DecodeBatch replaces it with an empty StopSequenceMatcher() rather than the engine's defaultStateMachine built from eosTokens. In an engine configured with EOS stops, adopted rows will ignore EOS and continue until maxTokens, unlike rows admitted through insert.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed - same as the parallel gemini thread: nil stateMachines now default to the engine's defaultStateMachine in makeAdoptedBatch.
Generated by Claude Code
| self.processors = processors ?? Array(repeating: nil, count: uids.count) | ||
| let machines = stateMachines ?? Array(repeating: StopSequenceMatcher(), count: uids.count) | ||
| self.stateMachines = machines | ||
| self.matcherStates = machines.map { $0.makeState() } |
There was a problem hiding this comment.
Carry partial stop-match state when adopting rows
When makeAdoptedBatch migrates a request after it has already emitted the prefix of a multi-token stop sequence, this resets the matcher to makeState() instead of carrying or replaying the existing match progress from the generated history. The next batched token can complete the configured stop sequence but will not be recognized, so migrated rows can stream past multi-token stops.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not applying this round - the mechanism is real (fresh makeState() on adoption, no replay parameter, asymmetric with penalty processors, which do get history), but there is no missable stop in the shipped pipeline. The single path never uses StopSequenceMatcher (stop detection is single-token stopTokenIds.contains), GenerateParameters has no stop-sequence field, and every matcher the pipeline builds is single-token EOS - so there is no multi-token progress to replay across the migration boundary. It's a latent gap only for external callers of the public makeAdoptedBatch with custom multi-token matchers, and the API currently gives them no way to seed state; tracked as a follow-up (optional matcherStates parameter).
Generated by Claude Code
| } | ||
| uids.append(contentsOf: other.uids) | ||
| tokens.append(contentsOf: other.tokens) | ||
| samplers.append(contentsOf: other.samplers) |
There was a problem hiding this comment.
Preserve the appended batch's fallback sampler
When extend(_:) appends a DecodeBatch whose rows rely on a non-greedy fallbackSampler (for example via adoptActiveBatch with an externally built batch), only the nil entries in other.samplers are appended. Those rows are later decoded with this batch's fallbackSampler instead of other.fallbackSampler; even though line 311 disables the argmax fast path, the affected rows still sample from the wrong fallback.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed (hardening; not reachable through real construction paths). extend now materializes other's fallback into its nil sampler slots when the two sides' fallbacks differ (detected via the fallbackIsGreedy flags), so those rows keep their sampling behavior. In every real construction path both sides get the engine's greedy defaultSampler, so this was latent - reachable only through an externally built batch handed to adoptActiveBatch.
Generated by Claude Code
| return ( | ||
| StopSequenceMatcherState( | ||
| currentState: currentState, | ||
| trieNode: child, | ||
| allStates: state.allStates, |
There was a problem hiding this comment.
Check shorter suffix stops before keeping a prefix
With overlapping stop sequences where a shorter stop is a suffix of a longer partial match, for example [1, 2, 3] and [2], after seeing 1 then 2 this returns as soon as [1, 2] is found as a nonterminal prefix. The matcher never tries the shorter suffix [2], so that stop is missed and generation can continue past a configured stop sequence.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed - confirmed. The matcher committed to the longest viable prefix and never examined shorter suffixes that had just completed, so stops [[1,2,3],[2]] fed 1,2 lost the [2] stop permanently (and resync couldn't recover it since findPrefix only fires terminals at walk end). match() now scans proper suffixes for a terminal hit before committing to the longer pending match; a completed longer match still wins at the same token. Two regression tests added: the shadowed shorter stop fires, and [[1,2],[2,3]] fed 1,2,3 still fires [1,2].
Generated by Claude Code
ce92824 to
c808900
Compare
a1983c7 to
2f6738b
Compare
Review-round fixes (PR #27 threads), each verified against the single-stream reference before changing code: - DecodeBatch.step: apply per-row penalty processors to RAW logit slices, then log-softmax per row, matching TokenIterator's process-before- logSoftmax order. RepetitionContext branches on logit sign, so processing logprobs (all <= 0) penalized repeated positive-logit tokens the wrong way and batched output diverged from single-stream for identical parameters. Penalty-free rows keep the shared batched logprobs node. - makeAdoptedBatch: default nil stateMachines to the engine's EOS matcher so adopted (single->batch upgraded) rows honor EOS like inserted rows, instead of silently installing a never-matching matcher. - StopSequenceMatcher: a shorter stop completing inside a longer viable partial match (stops [[1,2,3],[2]] fed 1,2) was shadowed forever; scan proper suffixes for a terminal hit before committing to the longer pending match. Completed longer matches still win at the same token. - DecodeBatch.filter: update nextTokens unconditionally so an emptied batch doesn't retain stale rows out of step with its sibling arrays. - DecodeBatch.extend: when the two sides' fallback samplers differ, materialize other's fallback into its nil sampler slots instead of silently switching those rows to self's fallback. - PrefillBatch: one combined innerState eval per chunk (and per finalize) instead of one GPU sync point per cache, mirroring the single path's whole-array eval. Tests: raw-logits capture test (a +4-peak fixture model distinguishes logits from logprobs at the processor boundary) and two matcher regressions (shorter-stop-inside-longer fires; longer match still wins). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
c808900 to
673b5bc
Compare
2f6738b to
d63c100
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d63c1003b1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if other.fallbackIsGreedy != fallbackIsGreedy { | ||
| // The merged batch keeps `self`'s fallback, so materialize | ||
| // `other`'s (different) fallback into its nil sampler slots -- | ||
| // otherwise those rows would silently switch sampling behavior. | ||
| samplers.append(contentsOf: other.samplers.map { $0 ?? other.fallbackSampler }) | ||
| } else { | ||
| samplers.append(contentsOf: other.samplers) | ||
| } |
There was a problem hiding this comment.
Preserve non-greedy fallback samplers
When merging an externally built batch whose fallback sampler is also non-greedy but configured differently from this batch's fallback (for example a different seed or temperature), this condition is false and other's nil sampler slots are appended unchanged. Those rows then resolve through self.fallbackSampler after the merge, so their sampling behavior changes even though both batches correctly disabled the greedy fast path. Fresh evidence in this revision is that the guard compares only fallbackIsGreedy, not whether the fallback sampler/configuration is the same.
Useful? React with 👍 / 👎.
| let admitCount = min(capacity, prefillBatchSize, unprocessed.count) | ||
| let batchSlice = Array(unprocessed.prefix(admitCount)) |
There was a problem hiding this comment.
Gate ragged batches for offset-unsafe models
For models already documented as unsafe for ragged KVCacheSimple batches in BatchedCache.swift:359-388 (for example PaliGemma reads the scalar cache.offset at Paligemma.swift:59-61), this admits arbitrary queued prompt lengths into one PrefillBatch. Because BatchKVCache.offset is the padded max width, shorter rows in those models use the longest row's position and produce corrupted logits; group by length or reject these model families instead of batching ragged prompts together.
Useful? React with 👍 / 👎.
| let currentTokens = nextTokens | ||
| let inputs = currentTokens[0..., .newAxis] | ||
|
|
||
| let logits = model.callAsFunction(inputs, cache: promptCache.map { $0 as any KVCache }) |
There was a problem hiding this comment.
Reject models without the simplified call path
When the engine is constructed with a LanguageModel that only implements the primary stateful callAsFunction(_:cache:state:) entry point, initialization can still succeed but the first decode step calls the optional simplified MLXArray overload, whose default implementation in LanguageModel.swift is a fatalError. Repo search shows Qwen2VL/Qwen25VL-style models in this category, so this path should either reject them up front or use an interface that cannot dispatch to the default trap.
Useful? React with 👍 / 👎.
673b5bc to
cc89c11
Compare
d63c100 to
34631a1
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 34631a19c9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let currentTokens = nextTokens | ||
| let inputs = currentTokens[0..., .newAxis] | ||
|
|
||
| let logits = model.callAsFunction(inputs, cache: promptCache.map { $0 as any KVCache }) |
There was a problem hiding this comment.
Pass nil for empty cache arrays
When the probed cache list is empty, this passes a non-nil empty array into the model instead of nil. I checked DeepseekV3Model: its KVCacheDimensionProvider currently returns an empty kvHeads, so the engine accepts it, while DeepseekV3ModelInner.callAsFunction uses cache?[i]; with cache == [] that optional subscript traps on the first layer. The single-token iterator avoids this by passing nil when cache.isEmpty, so the batch path should do the same or reject empty-cache models up front; the same non-nil empty array is also passed from PrefillBatch for multi-token prompts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Both batched forward passes now pass nil instead of a non-nil empty cache array, matching the single path, and the engine init additionally rejects models whose cache probe is empty -- a model with no per-layer caches has nothing to batch over, and DeepseekV3's cache?[i] would trap on layer 0.
Generated by Claude Code
| self.model = model | ||
| self.prefillStepSize = prefillStepSize | ||
| self.prefillBatchSize = prefillBatchSize | ||
| self.completionBatchSize = max(completionBatchSize, prefillBatchSize) |
There was a problem hiding this comment.
Honor smaller completion batch caps
When a caller intentionally sets completionBatchSize below prefillBatchSize to cap decode memory or latency, this silently raises the active decode limit to the prefill size. Admission later uses this stored value to compute free completion slots, so a configuration like prefillBatchSize: 8, completionBatchSize: 1 can run eight active decode rows instead of the requested one; honor the supplied cap or reject the combination rather than widening it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. The silent max() clamp is gone and completionBatchSize is honored exactly. Admission already bounds each prefill sub-batch by remaining completion capacity, so a smaller decode cap simply admits smaller sub-batches.
Generated by Claude Code
| let (subkey, nextKey) = MLXRandom.split(key: value) | ||
| current = nextKey | ||
| return subkey |
There was a problem hiding this comment.
Use the split subkey for seeded sampling
For makeRowSampler(..., seed:), MLXRandom.split's documented pattern is to keep the first result as the next PRNG state and use the second result as the per-draw subkey. This code does the reverse, so seeded temperature sampling takes a different random stream from TopPSampler(seed:) even though the sampler comments promise single-stream parity; swap the returned key and stored key here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Confirmed against mlx-swift 0.31.6's RandomState.next() (split[0] = next state, split[1] = draw key): the roles were exactly swapped. SamplerKeyHolder now matches, restoring seeded single-vs-batched parity from the first draw.
Generated by Claude Code
cc89c11 to
37f330b
Compare
34631a1 to
b2778d5
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b2778d5669
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| self.cacheFactories = try makeBatchedCacheFactories( | ||
| for: model.newCache(parameters: cacheParameters) | ||
| ) |
There was a problem hiding this comment.
Reject unsupported KV quantization parameters
For models using the default KVCacheDimensionProvider.newCache, a cacheParameters value with kvBits or kvScheme still probes as plain KVCacheSimple, and those parameters are discarded after these factories are built. Unlike TokenIterator.step, the batched path never calls maybeQuantizeKVCache and BatchKVCache is not quantized, so callers requesting KV quantization get full-size caches silently; reject these fields until batched quantization is implemented.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed. Engine init now throws for kvBits/kvScheme when the cache probe contains no QuantizedKVCache layer, mirroring the scheduler's parametersAreBatchable rationale. Models whose newCache builds QuantizedKVCache directly (FalconH1) still route through the quantized factory.
Generated by Claude Code
37f330b to
9e90449
Compare
b2778d5 to
482fda6
Compare
9e90449 to
04b7535
Compare
482fda6 to
c92c25c
Compare
04b7535 to
208af68
Compare
c92c25c to
a3cb04d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a3cb04d8e7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| precondition( | ||
| uids.isEmpty && other.uids.isEmpty, | ||
| "PrefillBatch.extend currently only supports merging two empty batches" |
There was a problem hiding this comment.
Fix PrefillBatch.extend to merge real queued rows
When a caller uses this public method for the documented case—two batches that already have rows/uids but have not run prefill yet—the precondition requires both UID arrays to be empty, so it traps before appending anything. That makes the advertised merge path unusable for real rows; the check should be based on the cache prefill state and should merge the row metadata/caches instead of requiring no rows.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed by removal -- you were right. The precondition (both batches must have zero rows) made the documented merge impossible and the method a permanent no-op with zero callers. Deleted rather than repaired; a real pre-prefill merge can be designed when a caller exists.
Generated by Claude Code
208af68 to
7b04433
Compare
a3cb04d to
698e5b4
Compare
7b04433 to
e0617e9
Compare
698e5b4 to
d845ad7
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d845ad7dc2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // CPU sync and preserve `asyncEval` pipelining. | ||
| let rowLogprobs: MLXArray | ||
| if processors[i] != nil { | ||
| processors[i]?.didSample(token: currentTokens[i ..< (i + 1)]) |
There was a problem hiding this comment.
Preserve prompt semantics for custom processors
For custom LogitProcessors where prompt(_:) and didSample(token:) have different meanings, this changes the first decode step: the last prompt token is delivered through didSample immediately before process, whereas TokenIterator gives the full prompt to prompt and only calls didSample for sampled output tokens. A processor that counts generated tokens or enables rules after the first sample will therefore see different state and can produce different logits in batched vs single generation for the same prompt.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not applying this. The flow difference is real (the final prompt token reaches the processor via didSample instead of prompt()), but for every in-repo processor the ring contents at each process() call are identical between paths (verified including ring-capacity overflow), so no behavioral divergence exists. It is observable only by a custom LogitProcessor assigning different semantics to prompt() vs didSample(). Rather than restructure the priming flow for that case, the DecodeBatch seeding comment now documents the equivalence argument.
Generated by Claude Code
e0617e9 to
b54461c
Compare
d845ad7 to
0ec5200
Compare
b54461c to
f6166ed
Compare
0ec5200 to
214ad62
Compare
f6166ed to
878ce37
Compare
214ad62 to
6da9c8c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6da9c8c6ad
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let positions = | ||
| rowStarts[0..., .newAxis].asType(.float32) | ||
| + MLXArray(Int32(0) ..< Int32(length)).asType(.float32) | ||
| let scaling = | ||
| 1 + beta | ||
| * MLX.log( | ||
| 1 + MLX.floor(positions / Float(maxPositionEmbeddings)) |
There was a problem hiding this comment.
Clamp left-padded positions before logarithmic scaling
When Mistral3 is prefetched with the documented left-padded BatchKVCache representation, batchOffset starts at -leftPadding, so padded positions reach this expression as negative values. For any padding smaller than maxPositionEmbeddings, floor(position / maxPositionEmbeddings) is -1 and the code evaluates log(0), producing non-finite padded queries; in later transformer layers those non-finite hidden states become padded keys/values and can contaminate otherwise valid tokens despite masking. Clamp padding positions to zero (scale 1) before applying the logarithm while retaining the existing per-row positions for real tokens.
Useful? React with 👍 / 👎.
PrefillBatch/DecodeBatch step loop, per-row samplers and logit processors, stop-sequence matching, and the queue->prefill->decode engine. CI adds the engine suites and the batched-vs-single model parity regressions (in-process random-weight models, no downloads). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jxj5hG5kLt2kkr5WDmHU5S
…okens not responses DecodeBatch.extend materialized other's fallback sampler into its nil sampler slots only when the fallbackIsGreedy flags differed, so merging two batches with different non-greedy fallbacks (equal flags, e.g. different temperatures) silently re-bound other's nil-slot rows to the receiver's fallback. Closures are not comparable, so materialize whenever either side samples; the nil-preserving fast path now applies only when both fallbacks are argMax and thus semantically identical. BatchGenerationEngine.next counted responses instead of tokens for its generatedTokens metric; BatchStepResult.tokens is plural precisely so a future multi-token step is possible, and this counter would silently undercount it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
Folds the integration branch's M-13 fix into the engine PR (whose regression suite hosts the parity coverage): the llama-4 attention scale previously read the scalar cache[0].offset -- the padded max width -- so a short row in a ragged batch was scaled with the longest row's positions on every layer. Batched paths now dispatch on BatchPositionedKVCache and scale per row from batchOffsets (true absolute positions, [B,1,L,1] broadcast); the scalar branch is type-gated and byte-identical for single-stream callers. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
The M-13 fix routes llama-4 attention scaling through a batched cache's per-row batchOffset (BatchPositionedKVCache) instead of the scalar cache-0 offset, which in a ragged batch is the longest row's absolute position. Mistral3BatchParityTests pins it end to end with a tiny random-weight ministral3 text model decoded from a JSON config whose rope_parameters carry the exact keys the model reads (llama_4_scaling_beta, original_max_position_embeddings) and whose layer_types mix full_attention with sliding_attention so BOTH cache types (BatchKVCache and BatchRotatingKVCache) appear: - ragged 2-row parity: 24- vs 4-token prompts prefilled single-stream, merged into hand-built batch caches (regression-suite merge pattern), then greedy-decoded two steps batched vs single. With original_max_position_embeddings = 8, the long row decodes at positions >= 24 (scale > 1) while the short row must stay at scale 1; under the scalar-offset bug the short row's queries were scaled ~2x and its logits diverge far beyond the tolerance; - batch-of-1 parity on the long prompt (scaling path live), two steps; - a config guard that fails if the rope keys or layer types ever drift, so the parity tests cannot silently go vacuous. Argmax parity is asserted alongside logit closeness, gated on a clear top-2 margin so numeric near-ties cannot flake. The model runs float16 (the SpeculativeDecodingTests move) so batch and single paths use the same kernels on NAX hardware. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn
6da9c8c to
4f6fc7e
Compare
878ce37 to
3c85f3e
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f6fc7ea20
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let sampleLogits = | ||
| stepLogits.dtype == .bfloat16 ? stepLogits.asType(.float32) : stepLogits |
There was a problem hiding this comment.
Preserve single-stream bfloat sampling semantics
For bfloat16 models, this unconditional promotion does not match every single-stream sampling path: CategoricalSampler.sample in Evaluate.swift keeps plain temperature-only logits in bfloat16, while penalty processors are also applied before TopPSampler performs its bfloat16-to-float32 conversion. Here both plain categorical rows and processed rows operate in float32 before normalization, so the same parameters and seed can cross a categorical boundary and produce a different token than single-stream generation. Apply promotion at the same stage and only for the row configurations whose corresponding single-stream sampler promotes.
Useful? React with 👍 / 👎.
| let sortedIdxAsc = argSort(logprobs, axis: -1) | ||
| let sortedLogits = takeAlong(logprobs, sortedIdxAsc, axis: -1) | ||
| let sortedProbs = softmax(sortedLogits, axis: -1) | ||
| let cumProbs = sortedProbs.cumsum(axis: -1) |
There was a problem hiding this comment.
Compute top-P mass directly from log-probabilities
When top-P is enabled and the cumulative probability lies near the cutoff, applying softmax here renormalizes the already-normalized log-probabilities a second time. The single-stream TopPSampler.applyTopP instead uses exp(sortedLogprobs) directly; especially for float16 logits, the extra reduction and normalization can move the nucleus boundary, retain a different token set, and break same-parameters/same-seed parity. Use the same direct exponentiation as the single-stream implementation.
Useful? React with 👍 / 👎.
Proposed changes
Chain 4/8 (stacked on #26). The explicit, opt-in batch engine — the level below the auto-upgrade scheduler:
PrefillBatch(right-padded ragged chunked prefill) →DecodeBatch(double-buffered step loop mirroring upstreammlx_lm.GenerationBatch, greedy whole-batchargMaxfast path, per-row samplers/penalty processors, stop-sequence matching).RowSamplers(single-pathTopPSamplerfilter-order parity, per-row PRNG with per-request seeds) andStopSequenceMatcher(token-trie stop machine).BatchGenerationEngine: queue → prefill admission → decode loop,insert/next/cancel/close, and the single→batch adoption seam (makeAdoptedBatch/adoptActiveBatch) used by 6/8.BatchModelRegressionTests— batched-vs-single numerical parity on in-process random-weight models (no downloads), running on Metal.The M-1 (penalties on raw logits) and M-4 (adopted-row EOS matcher) parity fixes are folded in, with tests.
Update 2026-07-13 (audit follow-ups):
cache[0].offset— the padded max width — so a short row in a ragged batch was scaled with the longest row's positions on every layer. Batched paths now dispatch onBatchPositionedKVCacheand scale per row frombatchOffsets; the scalar branch is type-gated and byte-identical for single-stream callers. Pinned by the newMistral3BatchParityTests(ragged 24-vs-4 parity withllama_4_scaling_beta, both cache topologies, batch-of-1 exactness).DecodeBatch.extendnow materializesother's fallback sampler whenever either side samples — two different non-greedy fallbacks (equal flags, different temperatures) previously re-boundother's nil-slot rows to the receiver's fallback silently.BatchGenerationEngine.nextcounts tokens (not responses) for itsgeneratedTokensmetric, honest for future multi-token steps.Checklist
github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document🤖 Generated with Claude Code
https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn