Repository navigation
MLX: drain GPU work before clearing the cache around a generation burst - #1128
Conversation
a919925 to
3ef1b5d
Compare
…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.
3ef1b5d to
a9efe22
Compare
|
Codex Review: Didn't find any major issues. You're on a roll. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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.
…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.
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. |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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.
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
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: 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.
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: 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. |
Both
mx.clear_cache()calls in_generation_cache_hygienereleased 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_evalfinds nothing, which makes the hazard look inapplicable. In the pinned mlx-lm,GenerationBatch._stepsubmits the next step withmx.async_evalbefore 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_evalwithout 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
RuntimeWarningraised when cleanup fails while an exception is active previously readmlx.core.clear_cache() failed, but itstrynow covers the synchronize too, so a synchronize failure would have been misattributed. The message and the bound exception name now cover both calls.Validation
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 withoutmlx.core.clear_cacheis still rejected before any work — parametrized so that themx.metal.clear_cacheshape is refused here too, since this path never accepted it. Each was mutation-checked: removing either synchronize, swapping the order, or re-accepting themx.metalshape fails exactly the test that covers it.