Repository navigation
Add fixed-batch token and decoded generation streams - #97
ronaldmannak wants to merge 16 commits into
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
3fc905b to
3394218
Compare
09aa9fc to
4b236d1
Compare
3394218 to
05bdca8
Compare
05bdca8 to
71f07c2
Compare
4b236d1 to
045c21d
Compare
dd7bdff to
fe57954
Compare
825bb5a to
46e5197
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fe57954d5e
ℹ️ 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".
d484159 to
f716203
Compare
46e5197 to
5254d24
Compare
f716203 to
e361606
Compare
5254d24 to
472604a
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e3616060c5
ℹ️ 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".
| } | ||
| iterator.remove(iterator.uids) | ||
| // Cache owners and consumers may proceed only after queued device work settles. | ||
| Stream.defaultStream.synchronize() |
There was a problem hiding this comment.
Synchronize the stream used by the batch worker
When generation runs with an overridden MLX execution stream, BatchTokenIterator submits its pipelined asyncEval work to that stream, but cleanup synchronizes Stream.defaultStream instead. The producer can therefore finish while its queued device work is still running, violating the task API's cleanup guarantee when callers await task.value before reusing resources. Capture StreamOrDevice.default.stream and synchronize it here, as the existing generateLoopTask in Evaluate.swift does.
Useful? React with 👍 / 👎.
472604a to
a5b9179
Compare
e361606 to
e40c18a
Compare
Treat CancellationError as task cancellation only while the producer is cancelled, finish unfinished rows once, and retain the common cache/device cleanup. Preserve error propagation for actual model failures and uncancelled model-thrown CancellationError. Exercise real between-chunk cancellation and the error control in raw and decoded streams. AI assistance: implemented, reviewed and validated with Codex for this origin fork.
Main added Generation.steering for chat-session steering. The batch streams take no steering control and never emit it, so the helper records it as unexpected, as it does an embedded info event. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e40c18a to
84a3adf
Compare
a5b9179 to
13957b4
Compare
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The batch generation task now captures StreamOrDevice.default.stream when it is created and synchronizes that stream in cleanup, as the single-sequence generateLoopTask does, instead of reading Stream.defaultStream at the end. MLX's default stream is task-local (withNewDefaultStream, withDefaultDevice and using(device:) all bind it with TaskLocal), and task locals carry into the Task and through the GenerationWorker hop, so both expressions name the same stream today. The change makes the stream explicit and keeps the two generation paths alike; it has no observable effect, so there is no test that fails without it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PR 91 changed BatchTokenIterator.next() to return events, so the stream driver in BatchGeneration.swift now consumes them: - .token goes to the row's handler; .finished(stopToken:) takes the stop path that a stop-token Response took before; .finished(.length) completes the row after its last token; .failed fails the stream with that error after the step's other output, as an admission throw did before. - Each token the driver counts is recorded with recordEmittedToken(id:token:) before its handler sees it, as the single-sequence loop does: generated tokens always, stop tokens (EOS or a protocol stop) only with includeStopToken. Tokens after a consumer stops partway through a step are never recorded. - Cleanup removes every row of the batch, including rows that ended in the last step, so each processor is finalized exactly once however the stream ends. New BatchGenerationTests check that lifecycle with a ThinkingBudgetProcessor behind a recording processor, for EOS (with and without includeStopToken), length, a stop string, a protocol stop token, a consumer that stops partway through a step, task cancellation and failed rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BatchGenerationEvent gains failed(uid:_:). A row that cannot join the batch (its supplied cache does not match, its prefill throws, or the model's state allows one row) now ends with that event after its handler finishes, and the other rows carry on to their own info events. Before, the first such row ended the whole stream with its error. Every row ends with exactly one info or failed event. A prefill stopped by the task's own cancellation still completes its row as .cancelled. An error from a batched model step still ends the stream. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 48f689afdb
ℹ️ 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".
| // Cancellation is checked before next(), which pipelines more MLX work. | ||
| while !Task.isCancelled, !terminated { | ||
| guard let events = try iterator.next() else { break } |
There was a problem hiding this comment.
Stop admission before decoding when prefill is cancelled
If cancellation occurs during a later prompt's chunked prefill after an earlier row was admitted, checking cancellation only before iterator.next() does not prevent new GPU work. BatchTokenIterator.admit() catches the later row's CancellationError, then samples the previously admitted rows, and next() proceeds into decode() despite the cancelled task. The new .failed handling runs only after those forwards have been submitted; with maxTokens: 1, the earlier row even completes as .length instead of .cancelled. Ensure cancellation interrupts admission before sampling or batched decoding, while still finalizing all unfinished rows and synchronizing already-submitted work.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed at the source in PR 91 (1e95cae), merged into this PR. A CancellationError from a prefill while the current task is cancelled now stops admission at once: the rows that have not failed go back to the queue, failures already recorded arrive with the next call, and next() throws before any sampling or decoding, so this driver completes the rows as .cancelled. cancelledAdmissionStopsBeforeSampling fails on acebd0b (7 issues) and passes on 1e95cae.
There was a problem hiding this comment.
Fixed at the source in PR 91 (1e95cae), merged into this PR. A CancellationError from a prefill while the current task is cancelled now stops admission at once: the rows that have not failed go back to the queue, failures already recorded arrive with the next call, and next() throws before any sampling or decoding, so this driver completes the rows as .cancelled. cancelledAdmissionStopsBeforeSampling fails on acebd0b (7 issues) and passes on 1e95cae.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The scenario Codex reported on this PR: the first row is prefilled and the task is cancelled during the second row's chunked prefill. With PR 91's fix, merged in, no row decodes, no decode forward is submitted, and both rows complete as .cancelled. Before it, the first row decoded and completed as .length. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Stacked on #94. Optional benchmark tooling remains separate in #93.
Closes #96.
What changed
batchGenerateTokensandbatchGenerateText, with task-returning variants for cancellation and deterministic MLX cleanup. Events identify the prompt by its zero-based UID.AsyncThrowingStream.BatchCompletionInforeports prompt and emitted token counts, stop reason, time to first model token and elapsed batch time. Streams buffer losslessly; callers stopping early should cancel and await the returned task..cancelled, including cancellation observed between prefill chunks. A model-thrownCancellationErrorstill propagates when the producer task is not cancelled.Prefill cancellation follow-up
CancellationErrorcompletes unfinished rows as.cancelledonly when the producer task is cancelled. Other errors retain their stream-failure behavior. Both paths still remove iterator rows, synchronize queued device work and finish the continuation.The regression runs raw-token and decoded-text streams through the real
PrefillParameters.forEachChunkcancellation check. It cancels after one CPU prefill forward and verifies one completion per row, zero generated tokens, nil first-token time and no later forwards. Control cases verify that an uncancelled model throwingCancellationErrorstill fails the stream. Every case awaits producer cleanup, including the negative run.Both actual-cancellation cases fail on the previous implementation. The focused fixed run passes 50 Swift tests and 15 XCTest cases. The restacked candidate
76993b3passes 58 targeted Swift tests across 3 suites and 15 XCTest cases; CI-pinned swift-format 603 checks pass. These are local results; fork CI remains skipped.Evidence
Earlier validation (71f07c2), including the streaming suite this PR adds and the Qwen VL tests from #94:
An earlier whole
MLXLMTestsrun reported in #98: 1600 Swift Testing tests and 869 XCTest cases. That earlier run's only failure is the pre-existingEmbeddingGemmaMaskTestsG7 (output in #98).Codex's earlier validation of this patch reported DocC for all 11 library products with warnings as errors and zero diagnostics. DocC was not re-run for this restack. Origin-fork GitHub Actions jobs are skipped by the workflow's repository-owner condition; the results above are local (M5 Max).
Restack (2026-11-06c)
Both commits are rebased unchanged onto #94's new head (
5254d24), which carries #90's recurrent offset fix: the streaming patch and the cancellation follow-up (d484159, nowf716203). At this head (f716203):Rebased onto main
4ab2679(2026-11-07)Rebased from
c8dabc6onto main4ab2679, which adds seven commits (22bdf2c..4ab2679): surrogate-pair escapes, weight-loading progress, LFM2.5, chat-session steering, VLM image prompts out of float32, LFM3, and Qwen 3.5 VLM YaRN. Git applied every commit of the stack without conflicts.git range-diffshows the earlier commits unchanged.Main's chat-session steering adds a
Generation.steeringcase, so the test helperBatchStreamTextResult.append(added by this PR) no longer compiled: itsswitchoverGenerationwas not exhaustive. New commite361606adds the case and records it as an issue, as the helper already does for an embedded.info: the batch streams take no steering control and never emit it. The library code needs no change.At this head (
e361606):Batch row operations move to
BatchableKVCache(2026-11-07b)Rebased onto #94's
a5b9179(theBatchableKVCachechange in #88-#94; see #88). This PR's commits are unchanged (git range-diff); the generation streams use no row operation.At this head (
e40c18a, wase361606):Merge validation and padding-only extraction (2026-11-07c)
Rebased onto #94's
13957b4(the round 8 changes in #88-#94). This PR's other commits are unchanged (git range-diff); the only new commits in the stack are #88's1c399b0, #89's081b109, #90'sa35cbe2and #94's13957b4.At this head (
84a3adf, wase40c18a):Batch cleanup synchronizes the captured stream (2026-11-07d)
Merged #94 (which carries #90's
e222aa2), then new commit316cacd; head316cacd, was84a3adf. No rebase. It answers the Codex finding on the batch worker's cleanup:StreamOrDevice.default.streamwhen it is created and synchronizes that stream in cleanup, asgenerateLoopTaskinEvaluate.swiftdoes, instead of readingStream.defaultStreamat the end.Stream.withNewDefaultStream,Device.withDefaultDeviceandusing(device:)all bind it with@TaskLocal, and task locals carry into theTaskand through theGenerationWorkeractor hop. SoStream.defaultStreamread at cleanup already resolves to the stream the iterator submitted its work to, even insidewithNewDefaultStream(worked out from MLX'sStream.swiftand the worker; no such test was run). The change keeps the two generation paths alike and the stream explicit.At
316cacd:54 tests here; 54 at
84a3adf.Driver on iterator events, with emission recording (2026-11-07e)
Merged #94, which carries #91's event API (head
058907f, was316cacd; no rebase). The merge commit movesBatchGeneration.swiftonto the events:.tokengoes to the row's handler..finished(stopToken:)takes the path a stop-tokenResponsetook before..finished(.length)completes the row after its last token..failedfailed the stream with that error, after the step's other output. That kept this PR's contract, which an admission throw used to trigger.522d71c(below) replaces this with a per-row failure event.recordEmittedToken(id:token:)exactly where it counts a token, before the handler sees it, as the single-sequence loop does. Generated tokens are always recorded; stop tokens (EOS or a protocol stop) only withincludeStopToken. Tokens after a consumer stops partway through a step are never recorded.New
BatchGenerationTestscover the lifecycle with aThinkingBudgetProcessorbehind a recording processor. Each row's log must be its delivered tokens, in order, then exactly one finalization, and the finalized reasoning count must match a single-sequenceThinkingBudgetProcessorthat emitted the same tokens. The tests cover:includeStopToken(the stop token is recorded only when delivered).atem)The same six tests with the driver's
recordEmittedTokencalls removed and the old cleanup (iterator.remove(iterator.ids)):At
058907f:That is 64 tests here; 54 at
316cacd. The additions are #91's 4 iterator tests and these 6.Then merged #91's follow-up
ca604a2through #94 (head2eb1b49): 65 tests, all passing.Per-row failures in the stream (2026-11-07f)
New commit
522d71c, made at the maintainer's request.BatchGenerationEventgainsfailed(uid:_:). A row that cannot join ends with that event after its handler finishes, and the other rows carry on to their owninfoevents. Before, the first such row ended the whole stream with its error. A row can fail this way when its supplied cache does not match the batch, its prefill throws, or the model's state allows only one row.infoorfailedevent..cancelled. An error from a batched model step still ends the stream.switchexhaustively overBatchGenerationEvent. The guide's example inusing.mdnow handles the new case.With the driver changed back to throwing the row's error, the affected tests fail:
The cancellation failures are only in its two
cancelTask: falsecases (the model throwsCancellationErroron its own); thecancelTask: truecases pass both ways.At
522d71c:That is 66 tests, up from 65:
rowFailureLeavesOtherRows, with raw and decoded cases.GenerateParametersand cancellation merged in (2026-11-07g)Pushed one commit at a time; Codex gave each a thumbs up before the next went out.
48f689a(Add continuous batched token generation with checked admission #91'sacebd0b, Add affine quantized KV caches for continuous batching #94's3dc6642anda80c49d).maxTokens: 1, the first row finished as.lengthinstead of.cancelled. The cause was Add continuous batched token generation with checked admission #91's per-row admission, fixed there in1e95caeand merged here ineef185c.8eb03f3addslaterPrefillCancellation, the scenario Codex described. The first row is prefilled and the task is cancelled during the second row's chunked prefill. Expected: no tokens, no decode forward (widths == [1, 1, 1, 1, 1, 1]), and both rows.cancelledwith 0 tokens. With the iterator from48f689ait fails with 4 issues: the first row decodes, finishes as.length, and a decode forward is submitted.Head
8eb03f3: 73 tests, all passing.Resumable prefill merged in (2026-11-07h)
Merged #94 (
05786a9), bringing #91's resumable prefill; Codex gave it a thumbs up. No changes in this PR. The stream drivers ignore.prefill. Head05786a9: 76 tests, all passing.Two-chunk prefill merged in (2026-11-07j)
Merged #94 (
2aef5be), which brings #91 at6dd7f3c. 15 more model families opt into resumable prefill, the family test seeds its weights, and two prefill chunks stay in flight (6dd7f3c): a batch of one now reaches its first token as fast as a single run. The merge was clean.BatchTokenIteratorTests+BatchGenerationTests+QwenVLBatchedPositionTestsat2aef5be:Merged #94 again (
9fcb0d3). It brings:ab5075e: chunk markers instead of the cache's own arrays. At 128-token chunks, a batch of one's first token came 125 ms sooner.31b3e7d.bf000b7and3e3c8d1: a row whose prefilled cache cannot meet the affine policy now fails.The merge was clean. Focused suites at
9fcb0d3, two more tests than before, both from #94:#91's marker and layer-count fixes merged in (2026-11-08)
Merged #94 (
65d8b65). It brings #91 at3ac324a:6c28e8c: each prefill chunk now has one marker that owns its memory. Before, its markers were views of the cache buffers, which forced every in-place chunk to copy its buffer.3ac324a: a first row whose supplied cache has fewer layers than the model now fails withKVCacheErrorinstead of trapping in the model.The merge was clean. Focused suites at
65d8b65:Merged #94 again (
9f75ec3), which brings #91'sc9145a2. The prefill chunk marker is now a single element: one element of the last cache array instead of every array's. That removes the ~10 ms that6c28e8cadded to a batch of four's first-row TTFT on 2048-token prompts, and the marker still owns its memory. The merge was clean. Focused suites at9f75ec3:Not done on purpose
Test changes
9f75ec3): no test changes.65d8b65): no test changes.9fcb0d3): no test changes.2aef5be): no test changes.522d71c), for per-row failures:preparationFailuresPropagateexpected the stream to throw the preparation error. It now expects that row'sfailedevent and a normal end, and is renamed "A preparation failure ends its row with a failed event, not the stream". It still checks for no output.prefillCancellation(cancelTask: false) expected the model's ownCancellationErrorto end the stream. It now expects every row to end withfailedcarrying aCancellationError, with still noinfo, output, progress or forward. ThecancelTask: trueexpectations are unchanged.emissionAtFailure(added in 2026-11-07e) expected a throw. It now reads both rows'failedevents; its lifecycle check is unchanged.rawModelFailurePreservesPriorOutputand thecollectBatchStreamTokensandBatchStreamTextResulthelpers handle the new case: a row ends exactly once withinfoorfailed, and emits nothing after it. No assertion was removed.rowFailureLeavesOtherRows.BatchStreamTextResult.appendinBatchTokenIteratorTests.swiftgains a.steeringcase that records an issue (e361606), so the helper compiles against main's newGenerationcase. No existing assertion changes.BatchGenerationTestsgains the four-case prefill-cancellation regression; its existing model fixture and locked probe gain optional chunked-prefill/cancellation modes.AI assistance: implementation, tests, documentation and stack cleanup were prepared with Codex at the maintainer's request for this origin fork. The earlier restack was made with Claude Code. Codex prepared the cancellation follow-up and its regression coverage for this origin fork.
🤖 Generated with Claude Code