Skip to content

MLX: drain GPU work before clearing the cache around a generation burst - #1128

Merged
danielhanchen merged 4 commits into
unslothai:mainfrom
Lyxot:mlx-metal-sync-hygiene
Sep 1, 2026
Merged

danielhanchen merged 4 commits into
unslothai:mainfrom
Lyxot:mlx-metal-sync-hygiene

Conversation

@Lyxot

@Lyxot Lyxot commented Aug 28, 2026

Copy link
Copy Markdown
Collaborator

Both mx.clear_cache() calls in _generation_cache_hygiene released MLX's buffer pool without first draining submitted GPU work.

Why this is reachable

The async work belongs to mlx-lm, not to this repo — grepping here for async_eval finds nothing, which makes the hazard look inapplicable. In the pinned mlx-lm, GenerationBatch._step submits the next step with mx.async_eval before yielding, and this repo's batch adapters drive exactly that loop while the stop-string scanner breaks out of it early. So a clear can run with command buffers still in flight, which is the ordinary case rather than an edge case.

What the drain actually buys

Scoped honestly: MLX keeps buffers that a live command buffer reads alive through that command buffer's completion handler, so the common case is already safe — which is why mlx-lm itself clears every 256 tokens right after mx.async_eval without synchronizing. The completion handler does not pin the evaluated array's own output buffer, so an output array dropped mid-flight can still reach the pool. Draining first keeps the release independent of that.

This is defensive ordering. No fault was reproduced, and none is claimed.

Cost

mx.synchronize() measured at ~33 us (max 46 us), twice per generation burst and never per token. Interleaved A/B over a real 4-prompt x 64-token burst on a small model — the worst case for this ratio — was 862.4 ms with versus 859.6 ms without, a +0.33% median delta against ~30 ms run-to-run noise.

Also

The RuntimeWarning raised when cleanup fails while an exception is active previously read mlx.core.clear_cache() failed, but its try now covers the synchronize too, so a synchronize failure would have been misattributed. The message and the bound exception name now cover both calls.

Validation

python -m pytest tests/test_mlx_generate.py tests/test_mlx_distributed_loader.py -q

Three tests added to tests/test_mlx_generate.py, alongside the existing hygiene coverage: both clears drain first, the exit clear still drains when the body raised, and a runtime without mlx.core.clear_cache is still rejected before any work — parametrized so that the mx.metal.clear_cache shape is refused here too, since this path never accepted it. Each was mutation-checked: removing either synchronize, swapping the order, or re-accepting the mx.metal shape fails exactly the test that covers it.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@Lyxot
Lyxot force-pushed the mlx-metal-sync-hygiene branch from a919925 to 3ef1b5d Compare August 28, 2026 09:32
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…n burst

`_generation_cache_hygiene` cleared MLX's buffer pool on entry and again in its `finally` without first draining submitted GPU work. mlx-lm's batched generation submits the next step with `mx.async_eval` before yielding, and the stop-string scanner breaks out of that loop early, so a clear can run while command buffers are still in flight.

MLX keeps buffers that an in-flight command buffer reads alive through that command buffer's completion handler, but it does not pin an output array dropped mid-flight. Draining first keeps the release independent of that. `mx.synchronize()` costs ~33us and runs twice per burst, never per token.

The warning raised when cleanup fails while an exception is active now names both calls, since the `try` covers the synchronize as well.
@Lyxot
Lyxot force-pushed the mlx-metal-sync-hygiene branch from 3ef1b5d to a9efe22 Compare August 28, 2026 09:42
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: a9efe2288b

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this lands on the _generation_cache_hygiene path in unsloth_zoo/mlx/generate.py where the clear could run with generation-stream work still submitted, and reusing _VLM_STREAM_MODULES keeps the candidate lists from drifting. Will get this reviewed.

test_missing_clear_cache_is_rejected_before_any_work failed on every
non-Apple host. monkeypatch.delattr("mlx.core.clear_cache") does not make
the attribute missing under tests/mlx_simulation: the shim synthesises a
trampoline for any name it does not implement, so getattr() still returns
something callable, the "clear_cache missing" guard never fires, and the
shim raises its own not-implemented error instead.

Measured on this branch: tests/test_mlx_generate.py is 51 passed at the
merge base and 2 failed, 54 passed at the head, both failures being the
new parametrized case. The file only executes on the mlx-labelled macOS
job, so upstream CI never showed it, but the command this PR gives as its
own validation step reproduces it directly on Linux.

Setting the attribute to None is what the guard actually tests for, and it
reads the same on real MLX and on the shim.
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Sep 1, 2026
…ve stream

The drain sat in front of both clears with nothing catching it, and the entry
one is outside every try, so anything it raised cancelled the entry
clear_cache() that always ran before and killed the generation burst with it.
That is a worse failure than the one the drain guards against: not draining is
the behaviour we had until this branch, and no fault was ever reproduced
against it.

The calls can genuinely fail. mlx made command encoders thread local in 0.31.2
(ml-explore/mlx#3348), and at the mlx-vlm pin floor 0.4.4 generation_stream is
still a plain mx.new_stream (mlx_vlm/generate.py:240), so synchronizing it from
a thread that did not create it raises "There is no Stream(gpu, N) in current
thread". A module-level __getattr__ can raise too; getattr's default only
swallows AttributeError.

Two other corrections found while checking the candidate list against the
supported range:

mlx_vlm/speculative/common.py:6 has owned a second generation_stream since
0.6.0, created on import and never routed through wired_limit, so nothing
drained it. It cannot go in _VLM_STREAM_MODULES, which resolves wired_limit,
so the drain now builds its own list. That list is a function because
_VLM_STREAM_MODULES is defined further down the module.

0.6.x defines the stream once in mlx_vlm/generate/common.py and re-exports it
from all three candidate names, so the drain was synchronizing one object three
times. Dedupe on identity.

Also drop the falsey-stream branch in the test recorder: it labelled a falsey
stream "default", which made an over-drain of the default stream
indistinguishable from a real hit.

Five tests added, each mutation checked: removing the per-stream try, the
identity dedupe, the speculative module, or the try around getattr fails
exactly the test that covers it.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 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-09-01T09:02:43.713894Z 8350fcb Manual request
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 2dd9facefe

ℹ️ 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 lines added by the branch go 34 to 17. Comments only: comment_tools.py
check --strip-docstrings passes on both files, and the 61 tests still pass.

Half rather than the usual target, because what is left is one distinct fact per
line and none of them restate the code: why the argument form of mx.synchronize
exists, why the drain is best effort, that it only works on the generating
thread, that 0.6.x aliases one stream across three names, that the shim
trampolines a deleted attribute, that _VLM_STREAM_MODULES may only hold modules
exporting wired_limit, and that the module list is a function because that
constant is defined further down.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 8350fcbfd9

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from Lyxot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from Lyxot Sep 1, 2026
@unslothai unslothai deleted a comment from Lyxot Sep 1, 2026
@unslothai unslothai deleted a comment from Lyxot Sep 1, 2026
@unslothai unslothai deleted a comment from Lyxot Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed and validated. Summary of what was checked and what changed.

Is the hazard real. The mechanism is, the fault is not. Every clause of the description checks out against mlx 0.32.1 and current main: mlx/backend/metal/eval.cpp:47-57 builds the pinned set from inputs and siblings and only ever erases arr.data_shared_ptr(), never inserts it, and the queue is commandBufferWithUnretainedReferences at device.cpp:323. So the output buffer really is unpinned. But the same diagnosis was filed upstream as ml-explore/mlx#3689 with a fix in #3688 and both were closed unmerged, and upstream mlx-lm clears every 256 tokens right after mx.async_eval without synchronizing. Defensive ordering, honestly labelled, worth having.

Hardware. A macOS-15 Apple Silicon run with the pinned set (mlx 0.32.1, mlx-lm 0.31.3, mlx-vlm 0.6.4) passed the full MLX suite. Measurements from it drove the changes below.

Three fixes committed.

  1. test_missing_clear_cache_is_rejected_before_any_work failed on every non-Apple host. monkeypatch.delattr("mlx.core.clear_cache") does not make the attribute missing under tests/mlx_simulation: the shim synthesises a trampoline for any name it does not implement, so getattr stays callable and the guard never fires. This file is 51 passed at the merge base and was 2 failed, 54 passed at the head. Setting the attribute to None is what the guard actually tests for and reads the same on real MLX and on the shim.

  2. The drain is now best effort. It sat in front of both clears with nothing catching it, and the entry one is outside every try, so a failure cancelled the entry clear_cache() and killed the burst. That is reachable: at the mlx-vlm pin floor 0.4.4 generation_stream is a plain mx.new_stream (mlx_vlm/generate.py:240), and mlx made command encoders thread local in 0.31.2. Executed on the runner rather than argued:

bare mx.synchronize(stream) from a worker thread: RuntimeError: There is no Stream(gpu, 8) in current thread.
_generation_cache_hygiene() survived it
  1. Two corrections to the candidate list. mlx_vlm/speculative/common.py:6 has owned a second generation_stream since 0.6.0, created on import and never routed through wired_limit, so nothing drained it. And the three mlx_vlm.generate names are one object:
mlx_vlm.generate            ThreadLocalStream(Device(gpu, 0), 2)  id=4922301472
mlx_vlm.generate.dispatch   ThreadLocalStream(Device(gpu, 0), 2)  id=4922301472
mlx_vlm.generate.ar         ThreadLocalStream(Device(gpu, 0), 2)  id=4922301472

Deduping on identity and adding the speculative module takes the drain from 5 synchronize calls at p50 214.6 us to 4 at p50 159.2 us, while covering three distinct streams instead of two. Worth noting for the description: that is 8 calls per burst on this runtime, not 2, and the per-drain cost is not the ~33 us of a single idle synchronize.

Cross-platform. Linux, 56 passed. Windows, 1 failed 55 passed, and that failure is not this PR: test_vlm_requests_reject_token_id_prompts_and_unsupported_controls at tests/test_mlx_generate.py:508 asserts '/tmp/i.png' against os.fspath(pathlib.Path("/tmp/i.png")), which is \tmp\i.png on Windows. It is not in this diff and this file only runs on the macOS lane, so nobody had seen it. Separate fix.

Five tests added, each mutation checked: removing the per-stream try, the identity dedupe, the speculative module, or the try around getattr fails exactly the test that covers it.

@danielhanchen
danielhanchen merged commit c602c3c into unslothai:main Sep 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants