Skip to content

Studio: wait on worker exit instead of fixed sleeps when switching models - #16344

Merged
danielhanchen merged 13 commits into
mainfrom
perf/r18-model-switch-waits
Nov 2, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
perf/r18-model-switch-waits

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

What changes

When a model is loaded while a transformers / MLX inference worker is alive, the switch path slept a fixed 0.8 s before it even told the old worker to exit:

  • load_model: _cancel_generation() then time.sleep(0.3), then _shutdown_subprocess()
  • _shutdown_subprocess_locked: _cancel_generation() then time.sleep(0.5), then drain, send shutdown, join(timeout)

Both sleeps date from the switch to an mp.Event cancel ("brief wait for generation to stop"). The worker reads commands in order, so a shutdown sent straight after the cancel only runs after the cancelled reply has ended. Waiting for the process to exit is the condition the sleeps stood in for, and it is a stricter one.

This PR:

  • removes the 0.3 s sleep in load_model (_shutdown_subprocess sets the same cancel event straight away)
  • removes the 0.5 s sleep in _shutdown_subprocess_locked, sends shutdown right after the cancel and drain, and waits for exit in 50 ms join slices, draining the reply queue between slices
  • adds the old 0.5 s to the exit budget (timeout + 0.5), so terminate / kill fire no earlier than before when the worker is slow or never exits
  • handles without a sentinel (test doubles) get one join(timeout + 0.5), the old call shape

Draining while waiting also fixes a latent stall. A child process only exits once its queue feeder has flushed. The old code drained once, then stopped reading, so a stream that kept writing after the cancel could fill the pipe and hold the worker until the terminate fallback. The new test covers this: base hits the fallback after the full join timeout; head exits cleanly.

Not changed: the dispatcher stop, the VRAM settle wait after the worker exits (_wait_for_worker_vram_settle, which polls real telemetry), the survivor guard that refuses to spawn over a live worker, and the GGUF / diffusion / video paths. Those already wait on a condition (process.wait, health event, VRAM polling, busy probes).

An in-flight stream still gets to read its cancelled tail: the sleeps were also what gave a stream up to 0.8 s to read its last tokens and gen_done before the worker handle changed. Teardown drains now deliver replies to waiting compare-mode mailboxes (the dispatcher's job once it has stopped) instead of discarding them, a registered direct reader is left to read the queue itself, and once the worker has exited, a stream that is still registered may keep reading its tail while it makes progress: it is abandoned after 0.8 s (the old total) without a read, with a 5 s hard cap. An idle switch waits for nothing. A fixed 0.8 s window lost the tail of a slow reader on a loaded macOS runner (test_streaming_reader_keeps_its_tail_across_a_switch[direct], 10 tokens then "worker stopped unexpectedly"); with a 60 ms/token reader the fixed window failed 6 of 6 runs and the progress-based one passed 6 of 6.

Results

CPU host, no GPU. Each arm is the same harness on the same host: the PR's merge base vs this branch.

Teardown segment of load_model against a stub worker that speaks the real command protocol (median of 7, two repeats, repeats agreed within 5 ms):

Scenario Base Head Fixed sleep base / head
idle worker, no dispatcher 835 ms 30 ms 800 / 0 ms
generating, cancelled mid-stream 1041 ms 33 ms 800 / 0 ms
idle, slow unload (0.2 s) + slow exit (0.1 s) 1336 ms 833 ms 800 / 0 ms
idle, dispatcher running 1034 ms 532 ms 800 / 0 ms

The last row still pays the dispatcher's 0.5 s queue poll on stop. In the bench the dispatcher had just started, so head pays the full 0.5 s; in real use the phase is random. That is unchanged by this PR.

Real orchestrator + real worker, switching between hf-internal-testing/tiny-random-LlamaForCausalLM and trl-internal-testing/tiny-LlamaForCausalLM-3.2 on CPU, with 3 s idle before each switch (12 switches per arm, interleaved):

Base Head
fixed sleep per switch 0.8 s 0 s
_shutdown_subprocess wall, median 1.90 s (+0.3 s before it) 1.41 s
whole switch, median (dominated by worker spawn + import on a loaded host) 11.95 s 11.38 s

Tests

  • test_streaming_reader_keeps_its_tail_across_a_switch[direct|dispatched]: every token the worker sent before the switch reaches the stream, for a direct reader and a compare-mode mailbox, at four reader speeds, matching main; test_idle_switch_does_not_wait_for_readers.

  • New studio/backend/tests/test_orchestrator_switch_waits.py (7 tests, with real spawned workers where it matters):

    • idle worker exits with no fixed sleep
    • slow teardown (1 s unload) is waited out, not terminated
    • a cancelled generation still finishes before exit
    • a full reply pipe (cancel ignored for 0.8 s, 4 KB tokens) exits without the terminate fallback
    • a worker that never exits keeps the old 0.5 + timeout budget, then escalates
    • a handle without a sentinel gets one join(timeout + 0.5)
    • source contract: no fixed sleeps left in the switch path
    • a registered reader that never reads is abandoned after the 0.8 s idle grace, not the 5 s cap

    5 of the 7 fail on base, including the full-pipe test; 7 pass on head.

  • Neighbour suites: all 96 backend test files that reference the orchestrator or _shutdown_subprocess. Base 5 failed / 8111 passed; head 5 failed / 8118 passed. The 5 failing test IDs are identical on both sides and pre-existing (test_cached_gguf_routes, test_export_reap, 3x test_mlx_bnb_substitution).

  • python -m pytest -q tests/studio -k "switch or unload or load": 1119 passed, 43 skipped on both base and head.

Not covered

  • With a stream in flight the switch waits while that stream keeps reading (at most 0.8 s idle, 5 s total); the 800 ms saving is for switches with no stream registered.

  • Switching while an idle dispatcher thread runs still costs about 0.5 s from _stop_dispatcher joining its queue poll; not changed here.

  • No GPU on this host. CUDA, ROCm, XPU and Apple Metal worker teardown were not exercised. The post-exit VRAM settle wait is unchanged and still gates the replacement spawn.

  • Windows and macOS were not run. The change has no platform branch: Process.join(timeout) and Process.sentinel behave the same on Windows. Any Windows handle or driver release happens at process exit, which is still awaited.

  • MLX workers use the same _shutdown_subprocess path; no Apple Silicon run.

  • The dispatcher stop still costs up to 0.5 s (its queue poll interval) when a dispatcher is running. Left for a separate change.

…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

On the Windows xplat staging leg for this PR (danielhanchen#3673), the PR's new test missed its wall-clock bound by 3 ms:

test_orchestrator_switch_waits.py::test_idle_worker_shutdown_has_no_fixed_sleep
E   assert 0.45299999999997453 < 0.45

The other 9 tests in the file passed. A 0.45 s ceiling on a Windows hosted runner, where process and pipe teardown alone can take a few hundred ms, will flake. To prove there is no fixed sleep, patching time.sleep (or the wait primitive) and asserting it is never called with the old constant, or asserting that shutdown returns as soon as the fake worker exits, would not depend on runner speed.

danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 1, 2026
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 1, 2026
@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:29:18.294126Z 691725b 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. Already looking forward to the next diff.

Reviewed commit: 31b6bf1de6

ℹ️ 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 added a commit to NilayYadav/unsloth that referenced this pull request Nov 2, 2026
danielhanchen added a commit to NilayYadav/unsloth 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. What shall we delve into next?

Reviewed commit: a77c8c9e77

ℹ️ 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. Chef's kiss.

Reviewed commit: 691725b512

ℹ️ 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 82e9740 into main Nov 2, 2026
@danielhanchen
danielhanchen deleted the perf/r18-model-switch-waits branch November 2, 2026 13:40
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 2, 2026
…poll (unslothai#16350)

Stacked on unslothai#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 (unslothai#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 unslothai#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.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 2, 2026
…t settle poll (unslothai#16404)

Stacked on unslothai#16344 (it edits the same switch path in `load_model`);
review that one first.

## What changes

When Studio switches chat models it stops the old inference worker and
then waits for its VRAM to come back (`_wait_for_worker_vram_settle`).
If the switch has a free-VRAM target (auto-selected single GPU with a
size estimate), the first poll already passes and nothing changes here.

Without a target (an explicit GPU pick, a model sharded over several
GPUs, or a model whose size cannot be estimated), the wait only returns
once it has seen memory come back between two polls and then one stable
sample. By the time `_shutdown_subprocess` has joined the worker, the
driver has already handed its memory back, so the first poll already
reads the freed state. No release is ever seen between polls, and every
such switch sits out the full 2 s deadline.

This PR takes one free-VRAM sample while the old worker is still alive
(right after the generation is cancelled, so cancellation never waits on
telemetry), and only on the no-target path. If the first poll after the
kill shows a gain past the existing tolerance (max(256 MiB, 2%))
compared with that sample, it counts as the release. Because that gain
could be a partial release, it then needs two stable polls instead of
one; a release seen between polls keeps the existing one-stable-poll
rule. The probe body moved unchanged into a `_free_vram_mib` helper so
both reads share it.

Release semantics stay the same. The worker is still joined
(terminate/kill ladder untouched), the settle wait still needs a release
plus a stable sample, the free-VRAM target path is unchanged, and with
no pre-kill sample the function behaves exactly as before.

## Results (base vs head)

Real A100 (Colab), a spawned CUDA worker holding 1 GiB that exits and
gets joined, then the settle wait with no target. 5 repeats per arm,
with base run twice as an A/A check:

| arm | settle wait median | min / max | free MiB after join | free MiB
after settle |
|---|---|---|---|---|
| base A | 2.000 s | 2.000 / 2.000 | 40441 | 40441 |
| base B (A/A) | 2.000 s | 2.000 / 2.000 | 40441 | 40441 |
| head without pre-kill sample | 2.000 s | 2.000 / 2.000 | 40441 | 40441
|
| head, one stable poll (first revision) | 0.250 s | 0.250 / 0.250 |
40441 | 40441 |

The worker exit code was 0 in every trial, and free VRAM matches between
arms: the memory had already come back before either arm's first poll.
The final rule asks for a second stable poll after a pre-kill-only
release, which on this already-settled card returns at 0.50 s by
construction (one extra 0.25 s poll; not re-measured on the GPU). On the
switch path this saves about 1.5 s, minus one telemetry read (an
`nvidia-smi` / `amd-smi` call on that path, typically 50 to 200 ms,
taken before the worker is joined).

## Tests

- `studio/backend/tests/test_inference_worker_vram_settle.py` (new, 7
tests, including the order cancel, sample, shutdown and the no-target
guard in `load_model`): a release before the first poll is recognised
with a pre-kill sample (2.0 s -> 0.5 s); a small gain before the first
poll followed by the bulk later returns at the same time as without the
sample; no release, or a gain under the tolerance, still waits to the
deadline; a late release still has to settle; a sample from other
devices is ignored; the target path and the unreadable-telemetry answers
are unchanged. These fail on base, which has no helper.
- Base vs head differential over 4000 seeded scripted telemetry
sequences (1-2 devices, jumps, noise, unreadable samples, varied
targets, deadlines, intervals and tolerances). Without a pre-kill
sample, result, probe count and elapsed time are identical in all 4000.
With one, head differs in 264 cases, and in each of them it only returns
True earlier on the no-target path (never a different answer on a
target).
- Backend tests importing the orchestrator (95 files) on top of unslothai#16344:
8076 passed, with the same 5 failures on base and head
(`test_mlx_bnb_substitution`, `test_cached_gguf_routes`,
`test_export_reap`, pre-existing on this host). The pre-kill sample is
wrapped so an unreadable telemetry call keeps the plain wait.
- `pytest tests/studio -k "orchestrator or settle or switch"`: 214
passed on both base and head.

## Not covered

- The full `load_model` wiring was not run end to end on a GPU (this
session has no local GPU). The GPU run calls the settle wait with a real
dead worker and a real NVML sample. No test drives the pre-kill sample
through a real `load_model` switch (a source-order test pins where it is
taken); the CPU switch run never enters the settle loop.
- ROCm, XPU and Windows telemetry were not run. They use the same
`get_visible_gpu_utilization` read as before.
- Apple Silicon is not helped: the parent's MLX reading cannot see the
worker, so no release is ever seen and the 2 s wait stays. That is left
for a separate change.
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