Skip to content

Studio: stop rescanning the whole answer on every streamed token - #8538

Merged
danielhanchen merged 1 commit into
mainfrom
studio/streaming-strip-linear
Aug 12, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio/streaming-strip-linear

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Reopened from #8428, which GitHub auto-closed when #8427's branch was deleted on merge. Same change, rebuilt on main now that #8427 has landed.

The problem

generate_chat_completion_with_tools ran the full tool-markup strip over the entire accumulated response, once per content token:

cumulative_display += token
cleaned = _strip_tool_markup_streaming(cumulative_display)   # llama_cpp.py:15813

Each of those calls runs strip_outside_think plus the mistral / bracket-tag / gemma / function-XML / GLM scans, ~10 regex substitutions and the rehearsal tail arm, over a string that grows with every token. That is quadratic in the response length, and on a long answer it is the dominant cost in the streaming path.

The fix

StreamingMarkupStripper replaces the per-token full rescan. Two properties make it possible, and both are tested rather than assumed:

  1. Sentinel completeness. Every strip arm is anchored on one of a small set of literals (<tool_call, <|tool_call, <function, [TOOL_CALLS], [ARGS], <|python_tag|>, <|, <think, call:, ...), so text containing none of them comes back unchanged and does no regex work at all.
  2. Prefix split. No arm can match before the first of those literals, so the text before it can be sliced off and the strip run on the remainder only.

The scan for that first literal resumes where the previous call stopped, with a _SENTINEL_MAX_LEN - 1 overlap so a literal split across two appends is still found. That makes the pre-markup phase amortized constant per token instead of linear.

A completed reasoning block is folded into a settled prefix: strip_outside_think already processes each segment in isolation, so a segment boundary is a point nothing downstream reaches back across. While a clean block is still streaming the buffer is unchanged, so that phase is constant too. Both are deliberately conservative and only fire on an unambiguous block whose body carries no other markup, because a </think> inside a call's arguments is that call's data, not a closer.

Measured

Per-token strip over a whole response, old vs new:

tokens scenario before after
16k plain prose 69.4s 0.04s 1875x
16k prose then a tool call 69.0s 0.62s 111x
16k reasoning block then an answer 44.9s 0.62s 72x
16k markup at offset 0 8.75s 8.95s 0.98x
4k plain prose 4.59s 0.006s 750x
4k reasoning block then an answer 3.05s 0.024s 126x

The last row is the honest one: with markup at the very start there is nothing to settle and nothing to slice, so it does the same work as before. A degenerate-state flag keeps it from paying the bookkeeping on top, leaving it within the run-to-run spread (~2.5% measured in isolation).

Note this is not the cumulative += token concatenation. CPython grows that in place here, so it is already amortized linear; the full-string rescan was the problem.

Three subtleties the property tests caught

Each of these produced wrong display text while this was being written, and each was found by the differential replay rather than by reading the code:

  1. The rehearsal arm matches NAME[ARGS], so the match starts before its [ARGS] literal. Cutting at the literal splits the match. The cut backs up over the preceding non-whitespace run.
  2. The [TOOL_CALLS] and [ARGS] arms are gated on markdown code spans, and an opening fence can sit arbitrarily far back. A backtick before the cut means no cut is safe.
  3. The fence pattern is ^ anchored, so cutting mid-line can turn a mid-line fence into one that opens a block and flip the in-code gate. The cut snaps to a line start.

Verification

test_streaming_stripper.py:

  • asserts sentinel completeness over the corpus and over 20k fuzz samples drawn from the characters markup is made of, so near-miss markup a too-narrow sentinel list would let through is actually generated;
  • asserts the prefix-split property over the corpus and 20k more fuzz samples;
  • replays every corpus entry through both the old and the new implementation one character at a time and asserts the results are equal at every prefix, plus the same over random multi-character chunkings and 400 fuzz strings;
  • checks a rewind resets cached state, and that growth rate stays linear against the reference's quadratic (compared as a ratio, so it stays meaningful on a noisy box).

test_refactor_guard.py from #8427 still passes unchanged: the AST and runtime surface, the output digests over the corpus, idempotence and all 210 string patch targets.

890 targeted tests pass, and the failure list over the touched areas is identical to a clean tree.

End to end in Studio

Isolated UNSLOTH_STUDIO_HOME, driven through the real UI with Playwright, against unsloth/gemma-4-E2B-it-GGUF:UD-Q4_K_XL and unsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL:

  • plain chat, reasoning ("Thought for 1 second" renders), and a fenced code example that must survive the strip, all clean at 176-511 tok/s;
  • a real tool loop: the model emitted a call, the sandbox ran Python, returned 6765, and the final answer rendered as "The 20th Fibonacci number is 6,765." with no tool markup reaching the display.

Rebuilt on main after the tool-call strip dedup landed as a squash.
@danielhanchen
danielhanchen merged commit 0e47051 into main Aug 12, 2026
22 of 54 checks passed
@danielhanchen
danielhanchen deleted the studio/streaming-strip-linear branch August 12, 2026 10:47

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 71aa0bf107

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

out = self._full_strip(text)
self._note(text)
return out
stripped = tail[:cut] + self._full_strip(tail[cut:]) if cut else self._full_strip(tail)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Advance past sentinels that resolve to prose

When a streamed answer contains a sentinel that is intentionally retained—such as an inactive foo[ARGS]{} example or an unanchored call:a{} mention after a visible prefix—_first remains pinned to it, so this branch runs _full_strip over the ever-growing remainder on every subsequent token (in addition to the whole-buffer checks above). In the GGUF _S_STREAMING callsite this leaves the operation quadratic and makes such answers slower than the implementation being replaced; a confirmed non-markup sentinel needs to be retired or folded into the settled prefix.

Useful? React with 👍 / 👎.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 12, 2026
…r paths (unslothai#8494)

* Studio: linear-time tool signal scanning in the safetensors and healer paths

Rebuilt on main after unslothai#8427 and unslothai#8538 landed as squashes.

* Studio: pin the safetensors loop's display strip to the exported helper

The loop now drives a StreamingMarkupStripper, so the exported
strip_tool_markup_streaming had no call site left in the module while ten
assertions in this file still targeted it. Agreement is now asserted at every
prefix, so the suite guards the path the loop actually runs.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Aug 17, 2026
  E AssertionError: early markup cost 1.451s against the reference's 1.316s
  E assert 1.4506334609999385 <= (1.3157524960000728 * 1.1)

Introduced by #8538 (2026-08-12), which added the test with time.perf_counter.
The source it guards is fine and is untouched here; the test has measured the
wrong quantity since it was written.

It compares how much WORK two code paths do, with a 10% margin, but timed them
on the wall clock, which also measures whatever else the machine is running. A
10% margin does not survive that. On a 4-vCPU runner with other pytest workers
in flight it failed while the code under test had not changed.

process_time measures this process's CPU time, which is what the assertion is
about and what neighbours cannot move. The margin and the min-of-3 sampling are
untouched.

I have NOT reproduced the original failure locally, so this is not verified as a
fix for that specific run: three busy processes on the same core slow both arms
equally and the ratio holds. What is demonstrated is the mechanism, on identical
work:

  idle core:                  wall=0.0161s  cpu=0.0160s
  core shared with 3 hogs:    wall=0.0599s  cpu=0.0150s

Wall clock inflates 3.7x, CPU time does not move.

Robustification: process_time is coarser than perf_counter, and 0.0 <= 0.0 * 1.10
is true, so a stopped clock or a lowered count would silently turn this into an
assertion that cannot fail. Both arms now have to measure something. Checked by
mutating the clock to return 0.0:

  reference arm measured 0.0000s; too small to compare against

Whole file: 64 passed.
danielhanchen added a commit that referenced this pull request Aug 17, 2026
* Measure the streaming stripper against CPU time, not wall clock

  E AssertionError: early markup cost 1.451s against the reference's 1.316s
  E assert 1.4506334609999385 <= (1.3157524960000728 * 1.1)

Introduced by #8538 (2026-08-12), which added the test with time.perf_counter.
The source it guards is fine and is untouched here; the test has measured the
wrong quantity since it was written.

It compares how much WORK two code paths do, with a 10% margin, but timed them
on the wall clock, which also measures whatever else the machine is running. A
10% margin does not survive that. On a 4-vCPU runner with other pytest workers
in flight it failed while the code under test had not changed.

process_time measures this process's CPU time, which is what the assertion is
about and what neighbours cannot move. The margin and the min-of-3 sampling are
untouched.

I have NOT reproduced the original failure locally, so this is not verified as a
fix for that specific run: three busy processes on the same core slow both arms
equally and the ratio holds. What is demonstrated is the mechanism, on identical
work:

  idle core:                  wall=0.0161s  cpu=0.0160s
  core shared with 3 hogs:    wall=0.0599s  cpu=0.0150s

Wall clock inflates 3.7x, CPU time does not move.

Robustification: process_time is coarser than perf_counter, and 0.0 <= 0.0 * 1.10
is true, so a stopped clock or a lowered count would silently turn this into an
assertion that cannot fail. Both arms now have to measure something. Checked by
mutating the clock to return 0.0:

  reference arm measured 0.0000s; too small to compare against

Whole file: 64 passed.

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 31, 2026
…ead of timing it (#16315)

## Problem


`studio/backend/tests/test_streaming_stripper.py::test_prose_containing_the_word_call_is_still_amortized`
failed in `(Python 3.13, a-f)` on #16311, a frontend-only PR:

```
AssertionError: incremental cost grew 5.7x vs the reference's 8.6x on prose containing the word 'call'
```

The test timed 300 and then 1200 tokens once each and required the
stripper's growth to stay under half of the reference strip's growth.
Both measurements take a few milliseconds (about 1 ms and 4 ms locally),
so on a loaded runner the linear code read 5.7x and the quadratic
reference only 8.6x, where 4x and 16x are expected. The code under test
is unchanged on main. The timing was what flaked.

## Change

The test now counts work in the same way
`test_scan_is_amortized_not_quadratic` above it already does. It counts
the characters handed to `_first_sentinel` and to
`StreamingMarkupStripper._full_strip`, and it also asserts that the
prose comes back unchanged on every token. The counts are deterministic:

| | 300 tokens | 1200 tokens | growth |
|---|---|---|---|
| main | 13,132 | 51,832 (2.7 per buffer character) | 3.9x |
| `_first_sentinel` returning every bare `call` unconfirmed | 722,400 |
11,529,600 (600 per buffer character) | 16.0x |

The assertion requires under 8x growth and at most 8 characters of work
per buffer character.

## Verification

- The new test passes on main, and the whole file passes 67/67 three
times under `-n 4`.
- Sabotage: with the confirmation in `_first_sentinel` removed, so that
any bare `call` counts as a sentinel, the test fails with `work grew
16.0x for 4x the tokens (722400 -> 11529600 characters over a
19200-character buffer)`. That is the regression the test was written
for in #8538.
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