Repository navigation
Wait for the streams a generation actually used before it completes - #78
ronaldmannak wants to merge 3 commits into
Conversation
The generation loop synchronized only the loop's default stream. Prefill can run in another task-local stream scope, and work can go to the CPU stream (distributed collectives), so teardown could race in-flight evaluations. TokenIteratorProtocol gains synchronizeGeneration(), which the loop calls before completing. Its default waits for the default, GPU and CPU streams; the built-in iterators also wait for the streams they captured while prefilling and decoding. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Local run of upstream's
This PR's new tests:
Before the upstream PR: This commit differs from |
Codex Review SummaryThis 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. |
testProducerSynchronizesIteratorBeforeCompleting awaited a task that returns the generated tokens without using them, so the compiler warned that the expression of type '[Int]' is unused. The staging PR for this change (#78) carries the same line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The previous commit synchronized every stream an iterator had used, plus the GPU and CPU streams. That missed a token a sampler computes on a stream of its own, and it waited for unrelated work queued later on those shared streams, while holding mlx-swift's global evaluation lock. TokenIterator and SpeculativeTokenIterator now follow each batch they pass to asyncEval with a small marker that depends on that batch and on the previous marker. synchronizeGeneration() waits on the latest marker: everything the iterator submitted, on whichever streams it ran, and nothing queued later. - The marker is evaluated separately from its batch. Within one evaluation MLX orders streams by fences on the computation, so an array on another stream could finish after the marker. Across evaluations the marker waits for each array's completion event. - MLX releases an array's inputs once it schedules it, so the marker keeps no cache arrays alive and buffer reuse is unaffected. - The generation loop keeps upstream's Stream.defaultStream.synchronize() after the iterator's wait. - MTPSpeculativeTokenIterator evaluates synchronously and keeps the protocol's default, which now does nothing. GenerationStreamTracker is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Revised in 5467dbc. Codex reviewed 9de70d2 locally, so its findings aren't on this PR. Here they are, with what changed. Findings:
What changed:
Before the change. The new tests, run against 9de70d2 with The last two are guards: no new work at the end, and the speculative iterator's marker. They pass either way. After the change, with each test run 10 times ( Upstream's The docs check fails only on Throughput.
All within run-to-run noise. The benchmark code isn't part of this PR. Test changes.
Both were added earlier in this PR. No upstream test changed. |
The previous commit said the marker doesn't stop the cache reusing its buffers. Holding the marker keeps no graph alive, but until the marker finishes, its command buffer holds the buffers of the arrays it depends on, so the cache can't reuse them in place. In single-stream decode the marker finishes right after its step, and that step holds the same buffers until then anyway. Decode throughput and peak memory at an 8192-token context matched upstream main. A slow array on another stream, such as a token a sampler computes on its own stream, holds the buffers until it finishes. Comment only; no code change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
5b040ed corrects what 5467dbc says about buffer reuse. Codex reviewed 5467dbc locally and found the claim was too strong. Holding the marker keeps no graph alive. Until the marker finishes, though, its command buffer holds the buffers it depends on, the cache state among them, so the cache can't reuse them in place. Codex reproduced it with a How much this matters depends on how long a marker stays pending in a real decode loop. In single-stream decode the marker finishes right after its step, and that step's own command buffer holds the same buffers until then anyway. To check, I added a long-context case to the throughput benchmark: the Qwen3 0.6B shape with an 8192-token prompt and 128 decode tokens, 15 runs per variant with the order rotated. A cache that lost buffer reuse would copy about 1 GB per step at this length.
The marker holds the buffers longer than its step only when a dependency on another stream finishes later than the step, for example a token a sampler computes on its own slow stream. 5b040ed rewrites the helper's doc comment to say exactly that, and the description now does too. It changes no code. Upstream's The docs check fails only on Codex's other finding was in PicoCore's batch engine, which isn't part of this PR. It is fixed separately there. |
Proposed changes
Before a generation completes, the generation loop waits for in-flight
asyncEvalwork so teardown doesn't race it. It only synchronizesStream.defaultStreamas the loop sees it. So work the iterator submitted elsewhere can still be running when the generation completes, for example:Stream.withNewDefaultStream);Changes:
TokenIteratorProtocolgainssynchronizeGeneration(), which waits for the work the iterator submitted withasyncEval.Stream.defaultStream.synchronize(), which is unchanged.TokenIteratorandSpeculativeTokenIteratorfollow each batch they pass toasyncEvalwith a small completion marker. The marker usesdepends(input:dependencies:)on that batch and on the previous marker.synchronizeGeneration()evaluates the latest marker. That only waits: it covers everything the iterator submitted, on whichever streams it ran, and nothing queued later.asyncEval. Within one evaluation, MLX orders streams with fences on the computation, so an array on another stream could finish after the marker. Across evaluations, the marker waits for each array's completion event.MTPSpeculativeTokenIteratorevaluates synchronously, so it keeps the default.Unchanged:
Stream.defaultStreamafter the iterator's wait, as upstream does today. Later work on that stream can still delay the end of a generation.evalholds mlx-swift's global evaluation lock while it waits, as anyevaldoes.Example
Tests:
GenerationStreamTests(Swift Testing). Each test keeps the work under test pending with a few hundred milliseconds of CPU work on a private stream:next()submitting nothing at the token limit afterwards.SpeculativeTokenIteratorwaits for the draft token its prefill submitted.The first four fail against a stream-based wait. The tests check readiness with mlx-c's
_mlx_array_is_availablethroughimport Cmlx, since mlx-swift doesn't expose it.GenerationExecutionTests.testProducerSynchronizesIteratorBeforeCompletingchecks that the generation task callssynchronizeGeneration()before it completes, both on normal completion and on cancellation.Throughput shows no measurable cost. The benchmark measured
TokenIteratordecode with greedy sampling:All differences are within run-to-run noise. Individual runs ranged from 296 to 311 tok/s for 0.6B and from 58.5 to 61.6 tok/s for 4B, apart from one stream-tracker run at 49.8.
The 8192-token row checks buffer reuse. Peak memory during decode was 349 MB above the starting point in all three variants. A cache that couldn't reuse its buffers would copy about 1 GB per step at that length.
Checklist
Put an
xin the boxes that apply.github.com/ml-explore/mlx-swift-lm/blob/main/CONTRIBUTING.md) documentpre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.
🤖 Generated with Claude Code