Skip to content

Make CommandEncoder thread local - #3348

Merged
zcbenz merged 1 commit into
ml-explore:mainfrom
zcbenz:encoder-refactor-4
Apr 1, 2026
Merged

zcbenz merged 1 commit into
ml-explore:mainfrom
zcbenz:encoder-refactor-4

Conversation

@zcbenz

@zcbenz zcbenz commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

Refs #3078, #3216.

  • Do synchronization in ~CommandEncoder instead of ~Scheduler: so we can clean up when each thread exits, instead of when process exits, and avoid issues about thread safety and destruction order.
  • Store CommandEncoder in thread local storage and throw error when accessing a stream not created from current thread.

@zcbenz
zcbenz force-pushed the encoder-refactor-4 branch 4 times, most recently from d27cbb7 to a58624e Compare April 1, 2026 03:40

@angeloskath angeloskath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome! And really nice broken up in several PRs the past few days. Kudos

@zcbenz
zcbenz force-pushed the encoder-refactor-4 branch 2 times, most recently from 247c227 to 0aefd88 Compare April 1, 2026 07:53
@zcbenz
zcbenz force-pushed the encoder-refactor-4 branch from 0aefd88 to 8a40a06 Compare April 1, 2026 08:01
@zcbenz
zcbenz merged commit 5e2c442 into ml-explore:main Apr 1, 2026
16 checks passed
@zcbenz
zcbenz deleted the encoder-refactor-4 branch April 1, 2026 09:42
Thump604 added a commit to Thump604/mlx-lm that referenced this pull request Apr 1, 2026
MLX ml-explore/mlx#3348 (Make CommandEncoder thread local) makes each
thread maintain its own Metal command encoder. The module-level
generation_stream created at import time belongs to the main thread's
command encoder. When generation runs in a thread pool (e.g., via
vllm-mlx BatchedEngine), mx.eval and mx.synchronize on that stream
fail with:

    RuntimeError: There is no Stream(gpu, 0) in current thread.

Fix: replace the module-level mx.Stream with a thread-local factory
function. Each thread gets its own stream on first use. The public
name `generation_stream` becomes a function returning the current
thread's stream, keeping the call-site diff minimal.

Backward compatible: on MLX versions without thread-local command
encoders, per-thread streams work identically to a shared stream.
uakihir0 added a commit to uakihir0/mlx that referenced this pull request Apr 6, 2026
When eval is called from a thread different from the one that created
the stream, the thread-local CommandEncoder map may not have an entry.
Instead of throwing, create it on demand (restoring pre-ml-explore#3348 behavior).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
ausimian added a commit to ausimian/emily that referenced this pull request Apr 18, 2026
Pre-1.0 pass over the documentation surface users consume on HexDocs.

- Moduledoc pass: added Public API sections to Emily, Emily.Backend,
  and Emily.Compiler to distinguish user-facing helpers from
  Nx.Backend / Nx.Defn.Compiler callback implementations. Added
  iex> examples to Emily.{to_binary, shape, dtype}, Emily.Compiler,
  Emily.Stream, Emily.Quantization, Emily.QuantizedWeight,
  Emily.MixedPrecision, and Emily.Telemetry. Reorganised
  Emily.Backend's divergences into a dedicated "Divergences from
  Nx.BinaryBackend" subsection.
- Emily.to_binary/1 now documents the zero-copy semantics: the
  pinned buffer refcount disqualifies MLX's donation path, and the
  ProcBin accounting footgun is flagged with mitigations.
- HexDocs nav via mix.exs: extras now grouped into README and
  Notebooks; modules grouped into Core / Concurrency /
  Quantization / Training / Performance / Observability.
- README rewrite: Overview + Features bullets, Prerequisites with
  the xcodebuild -downloadComponent MetalToolchain step, Building
  with a "Why vendored?" subsection covering ml-explore/mlx#3348
  and #3405, and an expanded Concurrency model section covering
  the worker-thread dispatch architecture.
- Two runnable Livebooks under notebooks/: distilbert_qa.livemd
  (Bumblebee QA through Emily.Compiler) and qwen3_quantized.livemd
  (Qwen3-0.6B int4-quantized + Emily.Stream concurrent serving).
- CHANGELOG cutover: moved the M0-M22 release history from
  RELEASE.md into CHANGELOG.md, then drastically simplified it to
  a top-level feature summary under [0.1.0] - unreleased. Users
  who want per-milestone detail can consult the git history.
  RELEASE.md now carries only M23 notes.
- mix docs runs clean (zero warnings).
@BrewTestBot BrewTestBot mentioned this pull request Apr 22, 2026
1 task done
danielhanchen pushed a commit to Lyxot/unsloth-zoo 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.
danielhanchen pushed a commit to Lyxot/unsloth that referenced this pull request Sep 1, 2026
…ve stream

All four sites are cleanup paths whose previous body, a bare mx.clear_cache(),
could not fail. The drain put two to five fallible calls in front of that with
nothing catching them, so a stream that cannot be synchronized now takes the
clear with it. clear_gpu_memory() is the worst of the four: unsloth/__init__.py
aliases it to torch.cuda.empty_cache() on MLX, and library code calls that from
finally arms, on whatever thread it happens to be on.

The calls do fail in practice. mlx made command encoders thread local in 0.31.2
(ml-explore/mlx#3348), and mlx-lm bound generation_stream with a plain
mx.new_stream until 0.31.3 (ml-explore/mlx-lm#1090), as mlx-vlm did until 0.5.0,
so synchronizing one of those 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. Not draining is the
behaviour we had before this branch and no fault was ever reproduced against it,
so skipping a drain we cannot perform is the right trade.

Exercised by lifting the MLX-only clear_gpu_memory out of unsloth/__init__.py
and running it against a synthetic mlx.core, ten shapes each on the merge base,
this branch, and this commit. The base clears in all ten and raises in none.
This branch raises in four and clears in none of those four: no synchronize
attribute, synchronize raising, an undrainable stream, and the old
mx.metal.clear_cache shape without synchronize. This commit clears in all ten
and raises in none, with the drain still happening.

Two corrections from checking the candidate list against real packages on an
Apple Silicon runner (mlx 0.32.1, mlx-lm 0.31.3, mlx-vlm 0.6.4):

mlx_vlm.generate, .dispatch and .ar are one object, id 4922301472, because
0.6.x defines the stream in mlx_vlm/generate/common.py and re-exports it. The
drain was synchronizing it three times. Dedupe on identity: measured 5 calls
per drain before, 3 after.

mlx_vlm/speculative/common.py has owned a second generation_stream since 0.6.0,
created on import and never routed through wired_limit, so nothing drained it.

Nine tests added. On Linux the Studio suite goes 857 passed to 865 with the two
pre-existing failures and one pre-existing collection error unchanged; removing
the per-stream try, the identity dedupe, the speculative module or the
synchronize guard fails exactly the test that covers it.
danielhanchen pushed a commit to unslothai/unsloth-zoo that referenced this pull request Sep 1, 2026
…st (#1128)

* fix(mlx): drain GPU work before clearing the cache around a generation 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.

* Test the clear_cache guard with a non-callable, not a deleted attribute

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.

* Make the generation-stream drain best effort, and drain the speculative 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.

* Tighten the comments this branch added

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.

---------

Co-authored-by: danielhanchen <elliegouldingstuff@gmail.com>
danielhanchen pushed a commit to unslothai/unsloth that referenced this pull request Sep 1, 2026
* fix(mlx): drain GPU work before clearing the cache

`clear_gpu_memory()` and the three cache clears in the MLX inference backend released MLX's buffer pool without first draining submitted GPU work. 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, so draining first keeps the release independent of that.

`clear_gpu_memory()` is public and torch-shaped, so a TRL callback can call it at any point during training. The inference backend clears on model unload, while probing KV-cache quantizability, and when resetting generation state after a cancel — all points where submitted work may still be in flight.

The backend's ordering is covered by an AST check rather than a text match, so a newly added clear that skips the drain fails the test.

* Make the generation-stream drain best effort, and drain the speculative stream

All four sites are cleanup paths whose previous body, a bare mx.clear_cache(),
could not fail. The drain put two to five fallible calls in front of that with
nothing catching them, so a stream that cannot be synchronized now takes the
clear with it. clear_gpu_memory() is the worst of the four: unsloth/__init__.py
aliases it to torch.cuda.empty_cache() on MLX, and library code calls that from
finally arms, on whatever thread it happens to be on.

The calls do fail in practice. mlx made command encoders thread local in 0.31.2
(ml-explore/mlx#3348), and mlx-lm bound generation_stream with a plain
mx.new_stream until 0.31.3 (ml-explore/mlx-lm#1090), as mlx-vlm did until 0.5.0,
so synchronizing one of those 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. Not draining is the
behaviour we had before this branch and no fault was ever reproduced against it,
so skipping a drain we cannot perform is the right trade.

Exercised by lifting the MLX-only clear_gpu_memory out of unsloth/__init__.py
and running it against a synthetic mlx.core, ten shapes each on the merge base,
this branch, and this commit. The base clears in all ten and raises in none.
This branch raises in four and clears in none of those four: no synchronize
attribute, synchronize raising, an undrainable stream, and the old
mx.metal.clear_cache shape without synchronize. This commit clears in all ten
and raises in none, with the drain still happening.

Two corrections from checking the candidate list against real packages on an
Apple Silicon runner (mlx 0.32.1, mlx-lm 0.31.3, mlx-vlm 0.6.4):

mlx_vlm.generate, .dispatch and .ar are one object, id 4922301472, because
0.6.x defines the stream in mlx_vlm/generate/common.py and re-exports it. The
drain was synchronizing it three times. Dedupe on identity: measured 5 calls
per drain before, 3 after.

mlx_vlm/speculative/common.py has owned a second generation_stream since 0.6.0,
created on import and never routed through wired_limit, so nothing drained it.

Nine tests added. On Linux the Studio suite goes 857 passed to 865 with the two
pre-existing failures and one pre-existing collection error unchanged; removing
the per-stream try, the identity dedupe, the speculative module or the
synchronize guard fails exactly the test that covers it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten the comments this branch added

Comment lines added by the branch go 33 to 23 across the four files it changed
for its own purpose. Comments only: comment_tools.py check --strip-docstrings
passes on all four, and the Studio suite still reports 133 passed, 16 skipped.

Deleted the section banner and the two copies of the release-layout note that
the module tuple already carries. What survives is one fact per line: why the
argument form of mx.synchronize exists, why the drain is best effort, that
empty_cache routes here from finally arms, that 0.6.x aliases one stream across
three names, and that speculative decoding owns a second one.

---------

Co-authored-by: danielhanchen <elliegouldingstuff@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

2 participants