Skip to content

Wait for the streams a generation actually used before it completes - #78

Open
ronaldmannak wants to merge 3 commits into
claude/upstream-pr-basefrom
claude/upstream-generation-stream-sync
Open

ronaldmannak wants to merge 3 commits into
claude/upstream-pr-basefrom
claude/upstream-generation-stream-sync

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner

Fork staging PR — do not merge. Stages a pull request for ml-explore/mlx-swift-lm so Xcode Cloud and review can run first. The base, claude/upstream-pr-base, is upstream main (efcedcd) plus the fork's Xcode Cloud scripts. Squash this branch's commits into one for the upstream PR, and delete this note before opening it.

Proposed changes

Before a generation completes, the generation loop waits for in-flight asyncEval work so teardown doesn't race it. It only synchronizes Stream.defaultStream as the loop sees it. So work the iterator submitted elsewhere can still be running when the generation completes, for example:

  • prefill and decode inside a different task-local stream scope (Stream.withNewDefaultStream);
  • a token that a custom sampler computes on a stream of its own.

Changes:

  • TokenIteratorProtocol gains synchronizeGeneration(), which waits for the work the iterator submitted with asyncEval.
    • Both generation loops call it, then upstream's existing Stream.defaultStream.synchronize(), which is unchanged.
    • The default implementation does nothing, for iterators that evaluate synchronously.
  • TokenIterator and SpeculativeTokenIterator follow each batch they pass to asyncEval with a small completion marker. The marker uses depends(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.
    • The marker is submitted in its own 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.
    • Holding the marker keeps no graph alive, because MLX releases an array's inputs once it schedules it. Until the marker finishes, though, its command buffer holds the buffers it depends on, so the cache can't reuse them in place.
    • In single-stream decode the marker finishes right after its step, which holds those buffers until then anyway. A slow array on another stream, such as a token a sampler computes on its own stream, holds them until it finishes.
  • MTPSpeculativeTokenIterator evaluates synchronously, so it keeps the default.

Unchanged:

  • The loop still synchronizes Stream.defaultStream after the iterator's wait, as upstream does today. Later work on that stream can still delay the end of a generation.
  • eval holds mlx-swift's global evaluation lock while it waits, as any eval does.
  • An array's completion event can come before the Metal completion handlers of its command buffer have run. The default-stream sync still covers those for that stream; this change doesn't claim it for other streams.

Example

// The caller prefills on a stream of its own, S.
let iterator = try Stream.withNewDefaultStream(device: .gpu) {
    try TokenIterator(input: input, model: model, parameters: parameters)  // asyncEval on S
}
let (stream, task) = generateTask(
    promptTokenCount: input.text.tokens.size, modelConfiguration: configuration,
    tokenizer: tokenizer, iterator: iterator)

// Before: the generation task called Stream.defaultStream.synchronize() before it
// completed. That waits for the task's own default stream, not for S, so work on S
// could still be running at teardown.
// After: the task first calls iterator.synchronizeGeneration(). It waits on the
// iterator's completion marker: everything submitted, on S or any other stream, and
// nothing queued later. Then the task synchronizes its default stream as before.

Tests:

  • GenerationStreamTests (Swift Testing). Each test keeps the work under test pending with a few hundred milliseconds of CPU work on a private stream:

    • a step whose token was already available, while its cache work is still running. That's the case a token-only wait misses. It also covers next() submitting nothing at the token limit afterwards.
    • a token sampled on another stream;
    • an earlier step's work after a later step submitted (the chained marker);
    • later work someone else queues on the default CPU stream isn't waited for;
    • waiting reads no cache state and runs no forward, so it starts no new work;
    • SpeculativeTokenIterator waits 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_available through import Cmlx, since mlx-swift doesn't expose it.

  • GenerationExecutionTests.testProducerSynchronizesIteratorBeforeCompleting checks that the generation task calls synchronizeGeneration() before it completes, both on normal completion and on cancellation.

Throughput shows no measurable cost. The benchmark measured TokenIterator decode with greedy sampling:

  • random weights at real Qwen3 shapes, in bf16;
  • a Release build on an Apple M5 Max;
  • 256 tokens after a 64-token prompt;
  • 15 runs per cell, over 3 rounds with the variant order rotated.
Model shape upstream main stream tracker (previous commit) completion marker
Qwen3 0.6B 305.9 tok/s 306.1 (+0.1%) 306.7 (+0.3%)
Qwen3 4B 60.5 tok/s 59.7 (−1.3%) 61.0 (+0.9%)
Qwen3 0.6B, 8192-token prompt, 128 tokens 161.4 tok/s 160.9 (−0.3%) 161.9 (+0.3%)

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 x in the boxes that apply.

  • I have read the CONTRIBUTING (github.com/ml-explore/mlx-swift-lm/blob/main/CONTRIBUTING.md) document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: the change, its tests and this description were drafted with Claude Code (Claude Opus 5.5).

🤖 Generated with Claude Code

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>
@ronaldmannak

ronaldmannak commented Oct 27, 2026 •

Copy link
Copy Markdown
Owner Author

Local run of upstream's pull_request.yml steps on 9de70d2 (this PR's head), Xcode 27.1 on an Apple silicon Mac, against mlx-swift ml-explore/mlx-swift @ 0.32.3, upstream's own requirement. Xcode Cloud on this fork builds only the IntegrationTesting project, so this covers what upstream CI runs.

Step Command Result
Lint swift-format format --in-place --configuration .swift-format over every tracked .swift file, then git diff (swift-format 604.0.0; CI pins 603.0.0) No files changed
Build xcodebuild build-for-testing -skipPackagePluginValidation -skipMacroValidation -scheme mlx-swift-lm-Package -destination 'platform=macOS' ** TEST BUILD SUCCEEDED **, 0 warnings in this PR's files
Tests xcrun xctest …/Debug/MLXLMTests.xctest (as CI) Executed 843 tests, with 4 tests skipped and 0 failures (0 unexpected) in 113.276 (113.327) seconds
Test run with 1201 tests in 107 suites passed after 73.267 seconds.
Docs scripts/verify-docs.sh 0 DocC warnings. Built: BenchmarkHelpers, IntegrationTestHelpers, MLXEmbedders, MLXLLM, MLXLMCommon, MLXRerankers, MLXScriptedLM, MLXVLM. Failed locally: MLXGuidedGeneration, MLXHuggingFace (see below)

This PR's new tests:

  • Test Case '-[MLXLMTests.GenerationExecutionTests testProducerSynchronizesIteratorBeforeCompleting]' passed (0.000 seconds).
  • Test "The tracker waits for streams captured in other task-local scopes" passed after 0.001 seconds.

verify-docs.sh exits 1 on this Mac for a reason outside this PR: symbol extraction for the C++ MLXCXGrammar module (xgrammar's bundled picojson) fails with fatal error: 'algorithm' file not found under Xcode 27.1, which fails MLXGuidedGeneration and MLXHuggingFace. The base commit fails the same way. The targets this PR changes build their documentation without warnings.

Before the upstream PR: git rebase --onto upstream/main claude/upstream-pr-base claude/upstream-generation-stream-sync drops the fork-only Xcode Cloud commit.

This commit differs from c1ecba1 on pico/0.32.4-upstream in one line: the new test now reads _ = await task.value. The first local build flagged expression of type '[Int]' is unused at GenerationExecutionTests.swift:64, and upstream keeps the build warning-free (ml-explore/mlx-swift-lm#594).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T01:46:25.841736Z 5b040ed New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

ronaldmannak added a commit that referenced this pull request Oct 27, 2026
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>
@ronaldmannak

Copy link
Copy Markdown
Owner Author

Revised in 5467dbc. Codex reviewed 9de70d2 locally, so its findings aren't on this PR. Here they are, with what changed.

Findings:

  1. The stream tracker missed a token that a sampler computes on a stream of its own.
  2. It waited for whatever was queued on the shared GPU and CPU streams, including other work. Stream.synchronize() holds mlx-swift's global eval lock, so other threads stall during the wait. In Codex's probe, with a 250 ms CPU job queued, the tracker waited 251 ms where the old wait took 0.8 ms.
  3. Waiting on the token alone misses a step's other work when the token was already available.
  4. The tests checked which streams were recorded, not that the work finished.

What changed:

  • After each batch an iterator passes to asyncEval, it now submits a completion marker that depends on that batch and on the previous marker. synchronizeGeneration() waits on the latest marker.
  • The marker goes in its own asyncEval. With the batch and the marker in one evaluation, the token-on-another-stream test failed in 1 of 2 runs. Within one evaluation MLX orders streams by fences on the computation, so the token's completion event could still be pending after the marker finished.
  • Upstream's Stream.defaultStream.synchronize() stays in both loops, unchanged.
  • GenerationStreamTracker is removed. MTPSpeculativeTokenIterator only evaluates synchronously, so it keeps the default synchronizeGeneration(), which now does nothing.

Before the change. The new tests, run against 9de70d2 with xcodebuild test-without-building -only-testing:MLXLMTests/GenerationStreamTests:

Test "Waiting covers a step's cache work when its token was already available" recorded an issue at GenerationStreamTests.swift:34:9: Expectation failed: isAvailable(pending)
Test "Waiting covers a token sampled on another stream" recorded an issue at GenerationStreamTests.swift:55:9: Expectation failed: isAvailable(pending)
Test "Waiting covers earlier steps' work, not only the last step's" recorded an issue at GenerationStreamTests.swift:75:9: Expectation failed: isAvailable(earlier)
Test "Waiting excludes work someone else queues later on a shared stream" recorded an issue at GenerationStreamTests.swift:90:9: Expectation failed: !isAvailable(unrelated)
Test "Waiting at the end reads no cache state and runs no forward" passed after 0.007 seconds.
Test "A speculative iterator waits for the draft token its prefill submitted" passed after 0.467 seconds.
Test run with 6 tests in 1 suite failed after 1.610 seconds with 4 issues.

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 (-test-iterations 10):

Test run with 6 tests in 1 suite passed after 15.788 seconds.

Upstream's pull_request.yml steps on 5467dbc. These ran in the same environment as the first comment: Xcode 27.1, and swift-format 604.0.0 because CI's 603.0.0 couldn't be built here.

format: files reformatted repo-wide=0, in this PR's files=[]
build-for-testing: exit 0 (37s), warnings in PR files: 0
mlx-swift: https://github.com/ml-explore/mlx-swift @ 0.32.3
Executed 843 tests, with 4 tests skipped and 0 failures (0 unexpected) in 129.771 (129.838) seconds
Test run with 1206 tests in 107 suites passed after 101.120 seconds.
verify-docs: exit 1 (36s) Documentation build failed with warnings.

The docs check fails only on MLXGuidedGeneration and MLXHuggingFace, with the pre-existing 'algorithm' file not found at picojson.h:44, the same as on the base. MLXLMCommon builds its docs with no DocC warnings.

Throughput. TokenIterator decode, random weights at real Qwen3 shapes in bf16, Release, Apple M5 Max, 256 tokens, 15 runs per cell with the variant order rotated. Median tok/s:

Model shape upstream main 9de70d2 (tracker) 5467dbc (marker)
Qwen3 0.6B 305.9 306.1 (+0.1%) 306.7 (+0.3%)
Qwen3 4B 60.5 59.7 (−1.3%) 61.0 (+0.9%)

All within run-to-run noise. The benchmark code isn't part of this PR.

Test changes.

  • GenerationStreamTests now holds the completion tests. Its previous test checked GenerationStreamTracker, which this commit removes.
  • The mock iterator in GenerationExecutionTests no longer calls the tracker.

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>
@ronaldmannak

Copy link
Copy Markdown
Owner Author

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 KVCacheSimple and a marker held pending: the next update allocated a new buffer instead of reusing the old one.

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.

upstream main 9de70d2 (tracker) 5467dbc (marker)
Decode median 161.4 tok/s 160.9 (−0.3%) 161.9 (+0.3%)
Peak memory during decode, above start 349 MB 349 MB 349 MB

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 pull_request.yml steps on 5b040ed (Xcode 27.1, swift-format 604.0.0):

format: files reformatted repo-wide=0, in this PR's files=[]
build-for-testing: exit 0 (13s), warnings in PR files: 0
mlx-swift: https://github.com/ml-explore/mlx-swift @ 0.32.3
Executed 843 tests, with 4 tests skipped and 0 failures (0 unexpected) in 116.373 (116.429) seconds
Test run with 1206 tests in 107 suites passed after 76.283 seconds.
verify-docs: exit 1 (29s) Documentation build failed with warnings.

The docs check fails only on MLXGuidedGeneration and MLXHuggingFace, with the same pre-existing 'algorithm' file not found as before.

Codex's other finding was in PicoCore's batch engine, which isn't part of this PR. It is fixed separately there.

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.

1 participant