Skip to content

Studio: wake the dispatcher on stop instead of waiting out its queue poll - #16350

Merged
danielhanchen merged 29 commits into
mainfrom
perf/r18-dispatcher-stop
Nov 2, 2026
Merged

danielhanchen merged 29 commits into
mainfrom
perf/r18-dispatcher-stop

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Stacked on #16344 (perf/r18-model-switch-waits). Review that one first; this PR only adds the commit on top.

What changes

When the inference dispatcher thread is running (compare mode, concurrent requests), a model switch first calls _stop_dispatcher. That sets the stop flag and joins the thread, but the thread sits in resp_queue.get(timeout=_DISPATCH_POLL_INTERVAL) (0.5 s) and only sees the flag when that poll times out. So every switch with a live dispatcher paid 0 to 500 ms of dead wait. The same goes for the idle stop path.

_stop_dispatcher now puts a wake message ({"type": "_dispatcher_wake"}) on the response queue after it sets the flag, and only if the thread is alive. The dispatcher gets it, goes back to its loop check, and exits. The poll interval stays the same.

Why nothing gets dropped or reordered:

  • The wake message has no request_id, and the worker never sends this type. The three places that read the queue directly (_dispatcher_loop, _read_resp, _drain_queue) skip it. Every other reader goes through _read_resp or _drain_queue. _read_resp keeps reading until its original timeout runs out, so finding a wake message does not look like a timeout to the caller.
  • Real replies keep the order they arrive in on the single pipe. A reply that came in before the wake message is still routed by the dispatcher exactly as before, then the loop exits. The switch path only drains after the join, as it already did.
  • If a stop races a real reply and the dispatcher exits without reading its wake message, the leftover is skipped by later readers. A dispatcher restarted on the same worker also skips it and keeps running. Each load creates a new worker with new queues (_CTX.Queue() in the spawn path), and shutdown sets _resp_queue to None, so a leftover never reaches the next worker's readers.
  • The wake put is best effort. put_nowait does not block, any exception is logged at debug level, and the dispatcher then stops on its next poll timeout, the same as before. cancel_join_thread() is called on the parent's side of the queue first, so interpreter exit never waits on this one put if the pipe is full or dead. The parent sends nothing else on that queue.
  • Dispatcher exception handling is unchanged (EOFError/OSError/ValueError still break the loop, and routing errors are still logged and skipped). The spawn context is unchanged. On Windows the parent already holds both ends of the queue.

Results

CPU only, Linux. Stub spawn worker with the same shutdown protocol. Times are for _shutdown_subprocess(). Before each switch the dispatcher waits a random time between 0.05 and 0.55 s, with fixed seeds, so the poll phase is spread out. n=12 per arm, two runs per arm.

Arm dispatcher running: mean / median (min-max) no dispatcher: median
base (#16344 head 99f4386) 304.5 / 321.3 ms (70.8-521.5) ; 288.7 / 299.3 ms (69.9-512.3) 51.7 ; 40.0 ms
head 37.6 / 36.1 ms (33.7-42.3) ; 37.3 / 35.4 ms (33.6-43.1) 33.8 ; 34.1 ms

That is about 260 ms off the mean of a switch with a live dispatcher, and up to about 480 ms in the worst case. With the dispatcher running, a switch now costs the same as one without it.

Tests

  • New file studio/backend/tests/test_orchestrator_dispatcher_wake.py:
    • stop returns promptly even with a 60 s poll (fails on base: the join runs to its timeout)
    • a failed wake put still stops on the poll
    • a leftover wake message is never seen by _read_resp or _drain_queue and is never passed to the observer (fails on base)
    • a restarted dispatcher skips leftover wake messages and delivers token then gen_done in order
    • no wake message is sent when no dispatcher is alive
  • tests/test_orchestrator_switch_waits.py, including test_streaming_reader_keeps_its_tail_across_a_switch[direct|dispatched], plus tests/test_inference_dispatcher_resilience.py: 28 passed, 3 repeats.
  • python -m pytest -q tests/studio -k "orchestrator or dispatch or switch": 254 passed, 40 skipped on base and on head.
  • studio/backend tests matching orchestrator or dispatch or switch or stream or shutdown or unload or worker or inference: base 76 failed / 72 errors / 7258 passed, head 76 failed / 72 errors / 7263 passed. The failing IDs are the same on both (mmproj placement, pricing, diffusion compile and similar, all failing before this change). The extra 5 passes are the new tests.

Independent checks: a worker sending 300 messages of about 70 KB while the parent sends 300 wakes delivers every worker message intact and in order (both sides share the queue's write lock under spawn). A stress run of 200 switches with two compare-mode streams in flight, half of them with the worker killed 0-30 ms into the stop, had no hangs, no out-of-order or missing tokens, no wake reaching a stream and no dispatcher left alive, with the same error outcomes as #16344's head.

Not covered

  • If the worker is killed while it holds the queue's write lock and a wake is still waiting to be written, the parent's queue feeder thread stays blocked until the process exits (one daemon thread and the queue's two pipe descriptors); cancel_join_thread() keeps it from blocking interpreter exit, and the dispatcher stops at its next 0.5 s poll as before. This did not happen in 200 kill -9 iterations. Windows queues have no write lock, so it cannot happen there.

  • No real Windows or macOS run. Spawn semantics are only argued from the code; the stub harness ran on Linux.

  • No real model worker or GPU. The latency numbers come from a stub worker, so a real switch still includes the model unload time, which this change does not touch.

…dels

The live-worker switch slept 0.3 s in load_model and another 0.5 s in
_shutdown_subprocess before sending shutdown. Send shutdown right after the
cancel and wait for the worker to exit, draining replies while waiting so a
late-cancelling stream cannot hold the child on a full pipe. The old 0.5 s
grace is added to the exit budget, so the terminate fallback fires no
earlier than before.
…itch swaps the worker

Without the old 0.3 s + 0.5 s sleeps, the teardown drained a live stream's unread tokens and
gen_done and swapped the worker handle before the stream caught up, so a direct or dispatched
stream ended with a worker-crash error or a silently truncated reply. Route drained replies to
the dispatched mailboxes, leave the queue to a direct reader, and wait (bounded by the old 0.8 s)
only while a stream is still registered; an idle switch still waits for nothing.
@danielhanchen

Copy link
Copy Markdown
Member Author

The Core zoo (HF=latest + TRL=latest) red here is unrelated to this PR. It is the zoo test test_chunked_logprob.py::test_grpo_switches_keep_entropy_policy_and_reference_on_one_scorer, which demanded bit equality between two scorer paths, and that equality does not hold on some runners (maxdiff 3.0040740966796875e-05, the same value on an earlier unrelated run). unslothai/unsloth-zoo#2336 changes it to check which scorer ran. A rerun should pass once that lands.

danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Nov 1, 2026
…uality (#2336)

## Problem


`tests/test_chunked_logprob.py::test_grpo_switches_keep_entropy_policy_and_reference_on_one_scorer[UNSLOTH_GRPO_CHUNKED_LOGPROBS]`
fails on some GitHub runners in unsloth's `Core zoo (HF=latest +
TRL=latest)` job, which runs this suite. It failed on
unslothai/unsloth#16350 (an orchestrator change) and earlier on
unslothai/unsloth#16312's staging run (a diffusion change), both at zoo
`604c131a`. Both times the result was identical:

```
AssertionError: {'equal': False, 'maxdiff': 3.0040740966796875e-05}
```

The same value twice means the runner hardware determines it, not
chance. The test runs the reference scorer (fully eager) and the
recompute scorer (eager matmul, with an Inductor-compiled
`post_forward`) on CPU, and asserts bit equality. On this host the two
agree exactly at every thread count (1 to 4), every Inductor `simdlen`
tried (1, 4, 8, 16), and with ATen pinned to AVX2. On those runners the
two most likely reduce in a different order. I could not reproduce it
here, so the exact cause is unconfirmed.

Bit equality was also the only way this test could catch the regression
it guards. On CPU, when the switch is off but the policy is still scored
by the fused kernel, the drift from the old reference scorer is only
9.5e-7. That is smaller than the 3e-5 the two old-scorer paths differ by
on those runners, so no tolerance separates the bug from the noise.

## Change

The child process now wraps the two fused entry points,
`fused_linear.fused_linear_logprobs` and
`chunked_logprob.unsloth_chunked_logprobs`, and records every call. With
either switch off, the test asserts that neither one ran, which is the
actual meaning of "on one scorer". It also keeps a sanity bound of
`maxdiff < 1e-3` on the values.

## Verification

- Both parametrisations pass. The whole file passes, with 77 passed and
3 skipped under `-n 8`.
- Sabotage 1: the recompute scorer's `fused_linear` default ignores the
switches. The `UNSLOTH_GRPO_CHUNKED_LOGPROBS` case fails with `{'calls':
['fused_linear_logprobs'], 'maxdiff': 9.5367431640625e-07}`.
- Sabotage 2: the reference scorer ignores the switches. That case fails
with `{'calls': ['unsloth_chunked_logprobs', 'fused_linear_logprobs'],
...}`.
- In both sabotages the `UNSLOTH_FUSED_LINEAR` case still passes, as it
should: that flag also disables `chunked_logprob._FUSED_LINEAR` at
import, which gates the fused path on its own.
- The sabotage drift of 9.5e-7 shows that a plain tolerance in place of
the old `torch.equal` would have let both regressions through.
@danielhanchen danielhanchen self-assigned this Nov 1, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review November 1, 2026 09:33
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 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-11-02T13:44:05.697223Z 06aecbd 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. Nice work!

Reviewed commit: 83953229f5

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 2, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 2, 2026
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 2, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 17cb3e2527

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 2b7c61291c

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

Base automatically changed from perf/r18-model-switch-waits to main November 2, 2026 13:40
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 06aecbd390

ℹ️ 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
danielhanchen merged commit 879a00f into main Nov 2, 2026
@danielhanchen
danielhanchen deleted the perf/r18-dispatcher-stop branch November 2, 2026 14:08
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