Skip to content

Continuous batching 4/8: BatchGenerationEngine + Mistral3 per-row scaling - #27

Open
ronaldmannak wants to merge 4 commits into
claude/cb2-3-batch-rotatingfrom
claude/cb2-4-engine
Open

ronaldmannak wants to merge 4 commits into
claude/cb2-3-batch-rotatingfrom
claude/cb2-4-engine

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Jul 2, 2026 •

Copy link
Copy Markdown
Owner

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 upstream mlx_lm.GenerationBatch, greedy whole-batch argMax fast path, per-row samplers/penalty processors, stop-sequence matching).
  • RowSamplers (single-path TopPSampler filter-order parity, per-row PRNG with per-request seeds) and StopSequenceMatcher (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):

  • Mistral3 per-row llama-4 attention scaling folded in (M-13): the 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; the scalar branch is type-gated and byte-identical for single-stream callers. Pinned by the new Mistral3BatchParityTests (ragged 24-vs-4 parity with llama_4_scaling_beta, both cache topologies, batch-of-1 exactness).
  • DecodeBatch.extend now materializes other's fallback sampler whenever either side samples — two different non-greedy fallbacks (equal flags, different temperatures) previously re-bound other's nil-slot rows to the receiver's fallback silently.
  • BatchGenerationEngine.next counts tokens (not responses) for its generatedTokens metric, honest for future multi-token steps.

Checklist

  • I have read the CONTRIBUTING (github.com/ml-explore/mlx/blob/main/CONTRIBUTING.md) document
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

🤖 Generated with Claude Code

https://claude.ai/code/session_011xThp8Po34ruijNS8TaShn

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +285 to +287
if !keep.isEmpty {
nextTokens = take(nextTokens, keepArr, axis: 0)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +353 to +377
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +372 to +387
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
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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
)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +153 to +155
for cache in promptCache {
eval(cache.innerState())
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)
            }

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +166 to +169
for cache in promptCache {
cache.finalizeBatched()
eval(cache.innerState())
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)
            }

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +369 to +372
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +141 to +145
return (
StopSequenceMatcherState(
currentState: currentState,
trieNode: child,
allStates: state.allStates,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from ce92824 to c808900 Compare July 2, 2026 23:17
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from a1983c7 to 2f6738b Compare July 2, 2026 23:17
ronaldmannak pushed a commit that referenced this pull request Jul 2, 2026
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
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from c808900 to 673b5bc Compare July 3, 2026 00:00
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 2f6738b to d63c100 Compare July 3, 2026 00:00

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +303 to +310
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)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +409 to +410
let admitCount = min(capacity, prefillBatchSize, unprocessed.count)
let batchSlice = Array(unprocessed.prefix(admitCount))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 673b5bc to cc89c11 Compare July 4, 2026 15:22
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from d63c100 to 34631a1 Compare July 4, 2026 15:22

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 })

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +203 to +205
let (subkey, nextKey) = MLXRandom.split(key: value)
current = nextKey
return subkey

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from cc89c11 to 37f330b Compare July 4, 2026 17:09
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 34631a1 to b2778d5 Compare July 4, 2026 17:09

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +98 to +100
self.cacheFactories = try makeBatchedCacheFactories(
for: model.newCache(parameters: cacheParameters)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 37f330b to 9e90449 Compare July 4, 2026 23:31
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from b2778d5 to 482fda6 Compare July 4, 2026 23:31
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 9e90449 to 04b7535 Compare July 4, 2026 23:35
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 482fda6 to c92c25c Compare July 4, 2026 23:35
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 04b7535 to 208af68 Compare July 6, 2026 23:58
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from c92c25c to a3cb04d Compare July 6, 2026 23:58

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +250 to +252
precondition(
uids.isEmpty && other.uids.isEmpty,
"PrefillBatch.extend currently only supports merging two empty batches"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 208af68 to 7b04433 Compare July 7, 2026 00:13
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from a3cb04d to 698e5b4 Compare July 7, 2026 00:13
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 7b04433 to e0617e9 Compare July 7, 2026 00:18
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 698e5b4 to d845ad7 Compare July 7, 2026 00:18

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from e0617e9 to b54461c Compare July 7, 2026 06:04
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from d845ad7 to 0ec5200 Compare July 7, 2026 06:04
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from b54461c to f6166ed Compare July 17, 2026 00:54
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 0ec5200 to 214ad62 Compare July 17, 2026 00:54
@ronaldmannak ronaldmannak changed the title Continuous batching 4/6: BatchGenerationEngine (explicit batch engine) Continuous batching 4/8: BatchGenerationEngine + Mistral3 per-row scaling Jul 17, 2026
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from f6166ed to 878ce37 Compare July 17, 2026 01:35
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 214ad62 to 6da9c8c Compare July 17, 2026 01:35

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +38 to +44
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

claude added 4 commits July 17, 2026 01:53
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
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-4-engine branch from 6da9c8c to 4f6fc7e Compare July 17, 2026 01:54
@ronaldmannak
ronaldmannak force-pushed the claude/cb2-3-batch-rotating branch from 878ce37 to 3c85f3e Compare July 17, 2026 01:54

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +376 to +377
let sampleLogits =
stepLogits.dtype == .bfloat16 ? stepLogits.asType(.float32) : stepLogits

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants