Skip to content

Studio: step streaming generators on a dedicated thread instead of the pool - #15590

Merged
danielhanchen merged 8 commits into
mainfrom
studio-stream-stepper
Oct 28, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-stream-stepper

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Studio's streaming routes advance a blocking generator once per token with asyncio.create_task(asyncio.to_thread(next, gen, sentinel)), so every token is a round trip through the default thread pool. The pool is also capped at min(32, cpu + 4) threads, so beyond that many concurrent streams, token steps queue behind each other.

What changes

  • New studio/backend/core/inference/gen_stepper.py: ThreadStepper(gen).next(default) behaves like asyncio.to_thread(next, gen, default) (the same contextvars copy per step, the same exception and cancellation semantics: a cancelled await abandons that step, which still finishes and its result is dropped), but every step of one stream runs on one dedicated daemon thread. The thread exits when idle and does not keep a dropped generator alive, so a dropped stream's upstream connection is not held open. When the stepper itself is dropped (the stream finished or was abandoned), a weakref callback puts a sentinel on its queue, so the worker exits at once instead of waiting out the 30 s idle timeout; a live stream that is briefly idle keeps the 30 s policy.
  • studio/backend/routes/inference.py: the nine streaming sites (including the audio-input chat stream) call the stepper instead of asyncio.to_thread(next, ...). Each step is still wrapped in the same asyncio.create_task, so the keepalive waits, stall watchdog, drain and close code are unchanged, and the generator is still advanced one step per request (no prefetch).

Results

CPU per event, create_task + asyncio.wait exactly as in the routes, main and this branch interleaved, 10 runs each, median (range):

Generator main this PR
Instant generator, 10k events 88.3 us (72.4 to 106.6) 54.7 us (51.2 to 60.5), -38%
Paced 2 ms per event (network-like), 1.5k events 180.6 us (130 to 222) 134.5 us (111 to 165), -26%

Same bench on a quiet 8 vCPU machine (default pool cap 12), ABBA, fresh process per run, 10 runs per arm, median (min to max):

Case main this PR
Instant generator, CPU per event 149.6 us (126.1 to 180.8) 67.2 us (61.1 to 74.4)
Paced 2 ms per event, CPU per event 440.6 us (414.3 to 482.4) 357.5 us (335.1 to 392.3)
64 concurrent streams, 5 ms blocking per token, tok/s per stream 35.9 (35.7 to 36.1) 123.9 (113.1 to 127.3)

The last row is the pool cap: with more concurrent streams than pool threads, token steps on main queue behind each other.

Tests

  • A stress run (64 streams x 5 rounds, random cancelled awaits, idle timeout forced to 0.5 ms so the worker exits and restarts about 900 times per round) saw no overlapping steps, no out-of-order tokens and no leaked threads.
  • New studio/backend/tests/test_gen_stepper.py (8): same results as to_thread, one thread and in order, an exception propagates and stepping continues, per-step context copy, a cancelled await abandons only that step, idle exit and restart, an idle worker does not keep a dropped generator alive, and dropping 32 steppers frees all 32 threads within seconds (without the wake-up all 32 are still alive after 5 s).
  • The streaming route test files give the same results on both sides; the tests that differed were load-sensitive timing tests that pass on both sides when run serially.
  • Staging CI on ubuntu-latest, windows-latest and macos-15 (Apple Silicon): the stepper tests ran and passed on each (7 passed per OS).

Not covered

  • One daemon thread per active stream instead of pool threads; a finished stream's thread exits once its stepper is dropped. At interpreter exit an in-flight step is not joined (the default executor joined it).
  • A prefetching producer thread was measured and not used: it only helps when tokens arrive faster than the network delivers them, and it would advance the generator after a cancel or disconnect check.

danielhanchen added a commit that referenced this pull request Oct 28, 2026
…, and name any test that still does (#15626)

## Summary

Backend CI (`(Python 3.13, a-f)`) and `Repo tests (CPU, rest)` have been
failing intermittently with dozens of errors like

```
AttributeError: torch._dynamo.config.recompile_limit does not exist
AttributeError: torch._dynamo.config.suppress_errors does not exist
AttributeError: torch._inductor.config.emulate_precision_casts does not exist
```

Seen on #15586, #15589, #15590, #15592, #15593, #15596 and #15601.
Locally, on pytest 9.1.1, it never reproduced.

### Root cause

CI resolves pytest 9.2.0, which changed `MonkeyPatch.setattr`
(pytest-dev/pytest#10644).
- For a non-class target it now records the old value from the instance
`__dict__`. Before, it used `getattr`.
- A torch `ConfigModule` (`torch._dynamo.config`,
`torch._inductor.config`, and its `SubConfigProxy` children such as
`torch._inductor.config.triton`) serves its entries from `__getattr__`.
They are never in `__dict__`, so pytest records "not set".
- On undo it therefore calls `delattr`. `ConfigModule.__delattr__` marks
the entry hidden, and every later read in that process raises `... does
not exist`.

So every `monkeypatch.setattr(torch._dynamo.config, ...)` in the suite
now deletes the entry it patched. Which shard fails depends on which
xdist worker such a test lands on.

Minimal reproduction:

```python
def test_patch(monkeypatch):
    monkeypatch.setattr(torch._dynamo.config, "suppress_errors", True)

def test_after():
    assert torch._dynamo.config.suppress_errors is False
```

On pytest 9.1.1 both pass. On 9.2.0 `test_after` fails with
`torch._dynamo.config.suppress_errors does not exist`.

## Change

`tests/_shared/torch_config_guard.py`, installed from
`tests/conftest.py` and `studio/backend/tests/conftest.py`:
- **`install_monkeypatch_fix()`:** wraps `pytest.MonkeyPatch.setattr`.
When the target is a torch `ConfigModule` or `SubConfigProxy`, including
the dotted-string form, it records the real value that was replaced, so
`undo()` restores it with `setattr` instead of deleting the entry. Every
other target goes through pytest unchanged. The fix is a no-op until
torch is imported, and it never imports torch itself.
- **`_no_deleted_torch_config_entries` autouse fixture:** any test that
still leaves a config entry deleted, by any route, errors at its own
teardown with the stack of the delete. The entry is then restored with
its previous value, so the rest of the worker is not poisoned. Cost is
about 24 us per test.

The guard is what found the cause. On the first push (guard only),
staging CI named 15 deletes, and every recorded stack ended in
`_pytest/monkeypatch.py, line 437, in undo: delattr(obj, name)`.

## Testing

**Under pytest 9.2.0** (CI's version):
- `tests/test_torch_config_guard.py`: 10 passed. Two tests pin the fix:
- `test_monkeypatch_undo_restores_a_config_entry_instead_of_deleting_it`
covers `torch._dynamo.config`, `torch._inductor.config` and
`torch._inductor.config.triton`.
- `test_monkeypatch_undo_restores_a_config_entry_named_by_import_path`
covers the dotted-string form.
- **Sabotage:** with `install_monkeypatch_fix` turned into a no-op,
those 4 cases fail and the guard errors at teardown.
- `tests/test_block_compile.py`: 13 failed on main (`suppress_errors` /
`recompile_limit does not exist`, the CI signature), 42 passed with this
change.

**Under pytest 9.1.1:**
- `tests/test_torch_config_guard.py`: 10 passed, and
`tests/test_block_compile.py`: 42 passed, on both trees.
- `studio/backend/tests/test_diffusion_*.py` (about 17,400 tests, run in
parallel with main on one loaded host): the guard fired 0 times. The
branch had 67 failed / 14 errors against 79 / 26 on main. The 3 failures
seen only on the branch pass when rerun alone, so they are load flakes.
- Meta-tests that read conftests and `tests/_shared`, plus
`test_ci_backend_pytest_shards.py`: 604 passed.
… earlier test cannot fail the count

[skip ci]
@danielhanchen
danielhanchen marked this pull request as ready for review October 28, 2026 05:54
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 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-10-28T07:53:01.872497Z ae0da85 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: a0decd10ca

ℹ️ 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 Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: ae0da8534d

ℹ️ 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 975715c into main Oct 28, 2026
4 of 49 checks passed
@danielhanchen
danielhanchen deleted the studio-stream-stepper branch October 28, 2026 08:21
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