Repository navigation
Studio: linear-time tool signal scanning in the safetensors and healer paths - #8494
Conversation
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Ran this on a staging copy rather than adding to the org queue. Green: Unsloth API CI, Windows API, GGUF (Linux/Mac/Windows), Windows UI, Startup profile, Local Agent Guides. Three reds, all checked individually and none of them this branch: Backend CI,
Backend CI, the rest. 84 in Chat UI and Mac. "Voice model picker did not wheel-scroll" and a Playwright |
85ae833 to
be8fe0b
Compare
|
Rebased onto the updated base branch. #8428 picked up a fix for
|
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
be8fe0b to
69dca7f
Compare
|
Rebased again onto the updated base, which now carries the #8427 merge. All the rebase conflicts were comment-only, two independent comment-reduction passes over the same blocks, so I took the base wording throughout rather than have this PR carry comment churn in files it does not otherwise touch. The one code conflict was Re-measured after the merge, so the numbers are not stale:
|
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
69dca7f to
f595c07
Compare
|
Re-verified with the same deterministic harness as the rest of the series ( The defect. The hoist was not worth defending: it saved a dict lookup and a scan of a handful of tools. The expensive part is the name lookup over the growing buffer, and that is what Results. Streaming invariant within the head: 316,672 prefix comparisons, 0 mismatches. Idempotence measured on both sides, introduced by this PR: none. AST over the 4 changed files: 255 identical, 22 changed, 4 added, 0 moved across files, 0 removed. Tests: 382 in the tool and streaming suites, 391 in the safetensors suites. The two failures in Worst cases re-measured on the current head, so the numbers are not stale:
|
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Another differential pass over the merge base, this time with a shadow copy of the head that has the fix removed, so the corpora are proven to reach the case rather than merely not flagging it. The defect. The bounded closed-pair scan in Two things have to line up. Prose has to put a Fixed in 7c63e1e by extending the bound over that tail. The walk uses Coverage. 330,000 cases with 13 fields compared each, plus 20,000 streaming replays over 586,568 incremental
The remaining red checks are the base branch's, not this diff's. Chat UI Tests, Core, Repo tests and the three scan-packages jobs fail byte for byte the same way on #8428. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7c63e1e7af
ℹ️ 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".
| brace_end = ( | ||
| _balanced_brace_end(content, brace_start, gemma_quotes = gemma) | ||
| if last_brace is None or brace_start < last_brace | ||
| else None |
There was a problem hiding this comment.
Avoid rebalancing every opener before the final brace
A single trailing } makes brace_start < last_brace true for every preceding candidate, even though it can balance at most the innermost one. For truncated output shaped like '<tool_call>{' * N + '}', _balanced_brace_end therefore scans to EOF once per opener; doubling 400 to 800 candidates grows this path from about 0.16 to 0.65 seconds. This leaves _build_markers, and thus parsing and marker coverage, quadratic on a near-unclosed response; the candidates need a shared forward balance scan rather than using the existence of any later brace as permission to rescan.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The quadratic is real, but it is pre-existing and the suggested remedy is not sound.
Measured on '<tool_call>{' * N + '}', merge base against this branch:
| N | merge base | this PR |
|---|---|---|
| 400 | 0.0896s | 0.0893s |
| 800 | 0.3578s | 0.3554s |
| 1600 | 1.4289s | 1.4230s |
| 3200 | 5.7075s | 5.7049s |
Within noise of each other. The last_brace gate does not fire on this shape at all, because the single } is at EOF, so brace_start < last_brace holds for every candidate. This PR neither introduced the behaviour nor claims to remove it.
On the remedy: a shared forward balance scan is not equivalent to running _balanced_brace_end per candidate, because a candidate brace can sit inside a string literal of an earlier call, where a single global pass never treats it as a brace at all.
content = '<tool_call>{"x":"<tool_call>{"}'
{ at 11 -> _balanced_brace_end = 30 (succeeds)
{ at 28 -> _balanced_brace_end = None (fails)
The later candidate fails while the earlier one succeeds, so you also cannot prune candidates from a neighbour's result in either direction.
There is a sound version, memoising per position rather than per scan (every candidate scan starts outside a string, so two scans that reach the same index agree from there on), and it takes N=3200 from 5.71s to 0.018s. It needs three new module-level tables, which changes the module surface that refactor_guard.py pins, and it is a change to the balanced scanner rather than to the scan bounding this PR is about. Separate PR.
| "<parameter", last_param_start | ||
| ): | ||
| param_closers = tuple(reversed(param_closers)) | ||
| if any(content.find(tag, pos + 1) >= 0 for tag in param_closers): |
There was a problem hiding this comment.
Stop searching the remaining parameter suffix per marker
When a parameter is unclosed and its value contains many literal <function=...> markers, this find searches from each marker to EOF for an absent parameter closer. The reverse opener lookup therefore does not make the overall filtering linear: _parse_function_xml and the healer call _inside_open_parameter for every candidate, producing quadratic work on exactly the truncated code/XML argument case this optimization is intended to handle. Carry or precompute the next closer position instead of rescanning the suffix for every marker.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Pre-existing, and this PR already improves it rather than regressing it. _parse_function_xml end to end, milliseconds:
| N | merge base | this PR |
|---|---|---|
| 250 | 3.72 | 2.36 |
| 500 | 27.4 | 11.1 |
| 1000 | 106.1 | 70.7 |
| 2000 | 433.5 | 305.1 |
Both grow about 30x for 4x N, so the path was quadratic before this PR and still is; the reverse opener lookup made it faster without making it linear, which is a weaker claim than the one being rejected here but is the claim the change actually makes.
Worth recording that line 736 is not the only unbounded scan on that path. The two supposedly bounded finds above it are bounded on the suffix, not the prefix, so their window grows with pos as well. Fixing only the closer search leaves the realistic shape at roughly 135x. A version that indexes all of them, via an optional keyword defaulting to today's behaviour, takes N=2000 from 305ms to 2.3ms and the whole-turn streaming display arm from 42.2s to 9.6s at 800 lines. That is a new shared index and two new module symbols, which refactor_guard.py pins, so it belongs in its own PR alongside the _balanced_brace_end memo.
There was a problem hiding this comment.
Correcting my own table above: the N=500 base figure of 27.4 ms is not reproducible and the 2.47x it implies is wrong.
It fails an internal consistency check on the numbers I posted. The path is quadratic, so each doubling of N should cost about 4x. My base column gives 7.37x for 250 to 500, then 3.87x and 4.09x for the next two steps. That first step is the outlier, not the trend.
Re-measured just now, minimum over 5 rounds, _parse_function_xml on <function=a><parameter=x> followed by N literal <function=bN> markers, milliseconds:
| N | base | head | speedup |
|---|---|---|---|
| 250 | 1.41 | 1.00 | 1.41x |
| 500 | 5.04 | 3.41 | 1.48x |
| 1000 | 18.78 | 12.11 | 1.55x |
| 2000 | 110.80 | 43.64 | 2.54x |
Absolute numbers on this path swing by roughly an order of magnitude with the exact input shape, so the shape above is stated explicitly rather than left implicit as I left it the first time.
What does not change is the conclusion: head is faster than base at every N, never slower, and both remain quadratic. The improvement in the middle of the range is about 1.5x, not 2.5x.
| if not (auto_heal_tool_calls or tool_protocol_active): | ||
| return text | ||
| # Safetensors-only Magistral leading-reasoning removal first, then the shared strip. | ||
| return _streaming_stripper.strip(_strip_mistral_reasoning(text)) |
There was a problem hiding this comment.
Make leading Magistral reasoning removal incremental
For the standard Magistral stream that begins with [THINK], this call still runs _strip_mistral_reasoning over the entire cumulative snapshot before every incremental-strip invocation. While the block is unclosed, its find scans the growing reasoning prefix to EOF on every token; after it closes, each call searches that prefix again and allocates the complete visible suffix. Consequently long Magistral reasoning remains quadratic even though StreamingMarkupStripper itself resumes incrementally, so the leading-block cursor/removal also needs to carry state across snapshots.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
_strip_mistral_reasoning is byte-identical on both trees, and the merge base already called it on the whole cumulative snapshot at the same point. This PR only moved that unchanged call into _strip_streaming_display. Instrumented over one identical 4004-snapshot replay, the Magistral term is unchanged at 4005 calls and 32,088,054 summed input characters on both trees, while the scan this PR does target drops from 32.1M to 0.32M characters.
Per-token replay through run_safetensors_tool_loop:
| tokens | merge base | this PR |
|---|---|---|
| 8k | 384ms | 49ms |
| 16k | 2168ms | 251ms |
| 32k | 9099ms | 1000ms |
Quadratic on both, and 9.2x faster in absolute terms here.
Reachability is also narrower than it looks. With skip_special_tokens=True on the safetensors streamer, Magistral 1.1 and 1.2 mark [THINK]/[/THINK] as special ids, so the markers never reach this loop; only Magistral 1.0 tokenizes them as ordinary text. On that model the total overhead at the 32k ceiling is about 1.0s against 200s or more of generation.
A streaming version of the leading-block cursor exists and takes 1000ms to 230ms, but it is a pre-existing cost this PR reduces rather than one it adds, so it goes in the same follow-up.
There was a problem hiding this comment.
Correcting one sentence in my reply above. I said Magistral 1.0 tokenizes [THINK] and [/THINK] as ordinary text. That is wrong.
mistralai/Magistral-Small-2506 contains zero occurrences of the string THINK anywhere in tekken.json, and its system prompt uses plain <think> and </think>. So 1.0 does not tokenize those markers as text, it never emits them at all.
mistralai/Magistral-Small-2507 does carry them:
{'rank': 34, 'token_str': '[THINK]', 'is_control': False}
{'rank': 35, 'token_str': '[/THINK]', 'is_control': False}
The correction makes the original point stronger rather than weaker, which is exactly why it was worth getting right instead of leaving a claim a reader would spot-check and find false.
Two limits on the surrounding argument that I should have stated at the time. The decode premise holds only when markers is None (core/inference/inference.py:1780-1793); ReasoningTextIteratorStreamer forces it False. That is true for Magistral today by omission rather than by design. And third-party conversions do not necessarily ship the added tokens, so "never reaches this loop" covers the official and unsloth/* conversions, not every conversion on the Hub.
f3ea450 to
71aa0bf
Compare
7c63e1e to
f678f0c
Compare
|
Rebased onto Conflicts were the expected two kinds. Comment-only in three places, two independent comment-reduction passes over the same blocks, resolved to the base wording throughout so this PR carries no comment churn. The one code conflict was One fix this round, on the 256-byte gap probe. Details in the thread; the short version is that the probe only moved the cliff rather than removing it, and the bound it was gating is unconditionally sound, so it is now always applied. 8000 openers behind 360 bytes of prose went from 3.629s to 0.007s, and growth is linear. The other three items are all pre-existing quadratics measured on the merge base rather than regressions from this diff. Re-verified after the rebase against the new merge base: The red checks are repo-wide. Mac Studio UI + API + Update CI is failing on |
|
@codex review |
1 similar comment
|
@codex review |
f678f0c to
b99e8e6
Compare
|
Rebased onto Two conflicts, both resolved toward main:
Verification of the rebuild:
Also added a test this branch needed. The loop now drives a |
|
CI note. Every failing check on this PR fails at the same place, and none of them are this PR's doing.
|
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.
6e56fcf to
194da73
Compare
|
@codex review |
1 similar comment
|
@codex review |
|
Rebased onto The previous CI run on this PR predates #8534, so every red on it was the duplicate Local check on the rebased head, 760 passed: One red that will remain and is not from here: |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Stacked on #8428 (base branch
studio/streaming-strip-linear). Review that one first; this PR's diff on top is the three scans below.Before
#8428 made the llama.cpp streaming display strip linear. Three sibling scans in the same tool paths were still quadratic, and they are on the per-chunk path for every streamed answer that contains, or looks like it contains, tool markup.
safetensors_agentic.py_earliest_tool_signal()re-scanned the entire accumulated text on every chunk, so an answer of N chunks did N full scans.tool_healing.py_build_markers()and the Gemma opener scan intool_call_parser.pyrestarted from offset 0 after every candidate they could not use. Text with many openers (a model echoing markup, a code block full of<tool_call>{examples) is quadratic in the number of openers, independently of streaming.After
Each scan carries its position forward instead of restarting.
_earliest_tool_signal, 8k chunks_build_markersThe first two are now linear in response length rather than quadratic.
One thing deliberately not cached
_should_start_provisional_render_html()re-resolves the tool name on every chunk. Caching the first non-None answer looks safe and is not: the first call's name is not final until its marker is complete, and a later complete marker can resolve first. A truncated<function=rendesitting ahead of a finished<function=get_weather>reads asget_weatherwhile the earlier marker is still open, then asrender_htmlonce it closes. Caching would pin the wrong answer and drop the panel. The reasoning is in a comment at the call site so it does not get "optimized" later.Output equivalence
tests/tools/refactor_guard.py verifypasses against the existing snapshot, without re-snapshotting: symbol inventory, golden outputs, idempotence and monkeypatch targets all match.a7c1a1d2...), covering all three entry points (strip_tool_markup,strip_tool_call_markup,parse_tool_calls_from_text).No public signature changes, no new dependencies, no behaviour change intended or observed.