Skip to content

Studio: decode and parse gpt-oss Harmony streams incrementally - #15589

Merged
danielhanchen merged 5 commits into
mainfrom
studio-harmony-incremental
Oct 28, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-harmony-incremental

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Streaming a gpt-oss reply through the Transformers backend gets slower with every token. HarmonyTextStreamer.put decodes all generated ids on every token and re-parses the whole reply for Harmony channel markers, so the work per token grows with the reply length. It runs inside the generate thread, between decode steps, so near the end of a long reply it adds milliseconds to every token.

What changes

studio/backend/core/inference/inference.py:

  • HarmonyTextStreamer.put decodes only the ids after the last settled boundary, a point where the decoded text does not end in U+FFFD (a partial UTF-8 character). It does this only when the tokenizer has no clean-up pass and its backend decoder is exactly tokenizers.decoders.ByteLevel (gpt-oss, Qwen), and it is a PreTrainedTokenizerFast whose decode and _decode are the stock methods (a subclass or instance override may post-process the whole text): for those, decode(a + b) == decode(a) + decode(b) whenever decode(a) does not end in U+FFFD. Every other tokenizer keeps the full decode.
  • _process_incremental resumes the Harmony parse: channels closed by <|end|> / <|channel|> are never re-matched, and the open channel only searches the new tail for its terminator. If earlier text is rewritten, it falls back to the full re-match.

Results

CPU time of the streamer alone with the gpt-oss tokenizer, fresh process per run, main and this branch interleaved, 6 runs each, median (range):

Reply main this PR
2.3k tokens 502 us/token (422 to 531), 1.15 s total 9.2 us/token (8.2 to 10.5), 0.021 s
9.2k tokens 2.1 ms/token (1.89 to 2.21 ms), 19.2 s total 12.3 us/token (9.6 to 14.3), 0.11 s
Token ids decoded for the 9.2k reply 41,884,127 19,060

Equivalence

  • Base and head emit identical chunk lists on 5,000 random gpt-oss cases (Harmony-structured text with multibyte UTF-8, split markers, partial <|end markers, literal U+FFFD, random special and byte ids, multi-id puts, skip_prompt on and off, stop sequences), on transformers 5.5.0; also 2,450 cases on 4.57.6, a Qwen3 tokenizer, and 2,000 rewritten-text cases.
  • New studio/backend/tests/test_harmony_stream_incremental.py (7 tests, a byte-per-token ByteLevel tokenizer built in memory, no download) compares against the whole-reply algorithm. Weakening the terminator search window, dropping the final-channel replay, or settling on a U+FFFD tail each make it fail.
  • The streaming 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), with CPU torch, transformers, tokenizers, peft and unsloth_zoo installed so the module imports: test_harmony_stream_incremental.py ran and passed on each (6 passed per OS).
  • test_overridden_decode_takes_the_whole_reply_path: subclass decode, subclass _decode and instance decode overrides that strip whitespace are kept on the whole-reply decode and stream exactly what it gives. The real openai/gpt-oss-20b tokenizer (tokenizer files only) still takes the incremental path on transformers 4.57.6.

Not covered

  • The numbers are for the streamer, not end-to-end GPU generation.

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 27, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 27, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 27, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 27, 2026
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.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 28, 2026
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review October 28, 2026 05:55
@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-28T08:00:06.326058Z bc1e6ba 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. Chef's kiss.

Reviewed commit: ca3b0d68ea

ℹ️ 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. Can't wait for the next one!

Reviewed commit: bc1e6ba214

ℹ️ 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 6a3ecd6 into main Oct 28, 2026
2 of 35 checks passed
@danielhanchen
danielhanchen deleted the studio-harmony-incremental branch October 28, 2026 08:22
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