Skip to content

Studio: strip tool markup from streamed text without rescanning the whole turn per token - #14143

Merged
danielhanchen merged 7 commits into
mainfrom
studio-incremental-display-strip
Oct 19, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
studio-incremental-display-strip

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Problem

The GGUF and safetensors tool streams clean tool markup out of the displayed text by running _strip_tool_xml_for_display on the whole cumulative text of the current model turn, once per token, on the event loop. The strip is about a dozen regex passes, so the cost per token grows with the turn and the total is quadratic. On a long reasoning turn this alone caps how fast Studio can forward output, and it keeps the event loop busy for most of every token interval, which also slows the durable run producer and every follower sharing that loop.

Measured per call on a realistic turn (40% <think> block, rest prose and code):

Turn length Per-token strip cost Max tok/s from this call alone
1k chars 134 us 7.5k
10k chars 1.47 ms 680
30k chars 3.6 to 5.2 ms 190 to 275
60k chars 7.1 to 9.4 ms 106 to 142

Whole turn: about 3.9 s of event loop CPU for 4000 tokens and 57 to 60 s for 16000 tokens, against 32 s and 128 s of generation at 125 tok/s.

Fix

_StreamingDisplayStrip wraps the existing function for a buffer that grows one token at a time:

  • No arm of _strip_tool_xml_for_display can edit text that contains none of <tool_call, </tool_call, <|tool_call, <function, </function, [TOOL_CALLS], [/TOOL_CALLS], [ARGS], <|python_tag|>, <|, </param and no call: (a superset of the markerless Gemma form). Such a buffer is returned unchanged.
  • The sentinel scan resumes where the previous call stopped (with overlap for a literal split across tokens, and a held tail for a split call), so a prose-only turn costs a few microseconds per token at any length.
  • Once a sentinel appears, that buffer goes to the unchanged full strip on every call, exactly as before.
  • A buffer that does not extend the previous one (a new tool iteration) starts over.

Output is byte-identical to the current function by construction. Nothing changes for turns that contain real tool markup.

The non-streaming tool loops (GGUF and safetensors) also ran the full strip on every cumulative content event and kept only the last result; they now strip the final text once. unsloth studio run --model turns tools on for every request, so plain stream: false calls take this path.

Results

Turn Before After
Prose, 4000 tokens 3.88 s 0.015 s
Prose, 16000 tokens 57.4 s 0.072 s
Turn with tool markup unchanged unchanged (falls back to the full strip)

Tests

  • test_streaming_display_strip.py: every prefix of prose, think, Hermes XML, function XML, Mistral [TOOL_CALLS], DeepSeek, Kimi, Llama <|python_tag|>, markerless Gemma call: and near-miss prose (recall:) transcripts, replayed with random 1 to 16 character splits through one instance across turns, matches _strip_tool_xml_for_display exactly, with auto-heal on and off and three tool-name gates. Also covers a call: split across tokens and asserts that a prose turn never reaches the full strip.
  • test_a_call_with_a_long_gap_before_its_colon_is_still_stripped: a markerless Gemma call followed by a long run of whitespace before its : is still held and stripped.
  • Differential fuzz: every test string in studio/backend/tests plus random marker splices, wrapped five ways, four name gates, random splits and buffer resets: 23.8M prefixes compared, 0 mismatches.
  • End to end on a GPU (real Studio backend, llama-server, Qwen3-1.7B Q4_K_M, a forced python tool call, temperature 0): the streamed text is identical to main on all 18 runs, and non-streaming tool responses are identical on all 3 requests per side, at the same speed.
  • The 34 backend test files covering the strip, tool streams and auto-heal pass (5265 passed). Three process-lifetime tests in test_tool_output_streaming.py failed once under heavy parallel load and pass on rerun; one of them also fails on main under the same load.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 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-18T16:11:37.710154Z 08aa3a1 Manual request
🔒 Security Review ⚠️ Failed 2026-10-18T14:41:04.343421Z cdd2194 PR opened
ℹ️ 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

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 0cf68304f4

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

Comment on lines +7339 to +7340
if not text.startswith(self._prev):
self._reset()

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 Avoid comparing the whole previous buffer on every token

For the monotonic cumulative snapshots emitted by both the GGUF and safetensors loops, text.startswith(self._prev) compares essentially the entire prior response on every token. The work therefore remains O(total_output²) and still runs on the event loop, so sufficiently long generations can incur the same growing latency this change is intended to eliminate; reset the stripper explicitly at iteration boundaries or track continuity without repeatedly comparing the accumulated prefix.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Measured: startswith on a 60k char buffer is about 1 us per token (3.4 us at 200k), so roughly 10 ms over a whole 16k token turn, against the 57 s per turn this removes. Not worth extra state to avoid.

Comment on lines +7331 to +7332
tail = _DISPLAY_GEMMA_TAIL_RE.search(text, max(self._gemma_from, len(text.rstrip()) - 4))
self._gemma_from = tail.start() if tail is not None else len(text)

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 Avoid copying whitespace-terminated cumulative buffers

When a streamed snapshot ends in whitespace, text.rstrip() creates a copy of the entire cumulative prefix merely to calculate the tail search offset. Repeating this for whitespace-ending tokens reintroduces quadratic copying and event-loop CPU usage even after the sentinel scan itself becomes incremental; retain the possible Gemma tail position incrementally instead of stripping the full string.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Measured: rstrip on a 60k char buffer ending in whitespace is about 1.5 us per token (4.7 us at 200k), negligible next to the per token full strip this replaces. Keeping the simpler form.

@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: 0cf68304f4

ℹ️ 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 LeoBorcherding/unsloth that referenced this pull request Oct 18, 2026
@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. Another round soon, please!

Reviewed commit: 08aa3a1be0

ℹ️ 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 LeoBorcherding/unsloth that referenced this pull request Oct 18, 2026
@danielhanchen
danielhanchen merged commit 1de12ab into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the studio-incremental-display-strip branch October 19, 2026 06:11
danielhanchen added a commit that referenced this pull request Oct 19, 2026
## Summary

Main is over the startup bundle budget again, by 28 B raw, so `Frontend
build + bundle sanity` fails on every PR based on it:

```
over the startup budget: raw 6666.1 KB > 6666.1 KB      (main at 1de12ab)
```

#14198 set both limits to the measured build plus a 160 B raw / 189 B
transfer margin. #14197 then added 188 B raw / 66 B transfer to the
startup chunks (it keeps the FLUX.3 Image Klein GGUF row under its Fast
FP8 row). It merged while its own bundle check was still queued, so it
never raised the limit.

## Cause

#14197 changes `model-selector/model-catalog.ts`, `recommended-fit.ts`
and `pickers.tsx`. The picker catalog is imported by startup code
(`features/chat/api/chat-adapter.ts` among others), so the new ordering
rule ships in the eager chunks. It is small real growth with no lazy
home. #14143, the other commit since, changes no frontend code.

## Change

- **`check-bundle-budget.ts`:** a BUDGET comment entry for #14197, and
both limits moved to the measured build plus the same margin:
  - `rawBytes`: 6,826,062 -> 6,826,250.
  - `transferBytes`: 2,054,313 -> 2,054,379.

## Testing

One machine and build, Node 24, exact byte totals from the budget
script, 95 chunks throughout. CI has matched this machine to the byte on
every earlier budget change.

| tree | raw B | transfer B |
|---|---|---|
| `94464babd6` (#14198) | 6,825,902 | 2,054,124 |
| main `1de12ab309` (+ #14197, #14143) | 6,826,090 | 2,054,190 |

- **Main against the old limits:** `over the startup budget: raw 6666.1
KB > 6666.1 KB`.
- **With this change:** `within budget (0.2 KB transfer, 0.2 KB raw to
spare)`.
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