Repository navigation
[Perf] function_call: Stop re-scanning the open DSML invoke on every streamed delta (DeepSeek V3.2/V4/V4.1) - #44940
Conversation
…delta DeepSeekV32Detector.parse_streaming_increment (also used by the V4 and V4.1 detectors) holds a long-form invoke in _buffer until its closer arrives, and re-runs invoke_regex over the whole buffer on every delta to find out that it is still open. The lazy body scan makes each delta O(n) in the length of the call, so a long tool call (e.g. a file write) costs O(n^2): about 3.5 s of CPU for a 30K-token call in 18-char deltas, with deltas near the end costing ~1.2 ms each. While the invoke is open, the result is always empty and only the buffer changes. The open invoke stays the leftmost match, since its header is complete, and any closer starting before the old end minus the closer length was already ruled out. So remember the open invoke and search only the newly arrived text for the closer; when it appears, or the buffer was replaced from outside, or a subclass replaced invoke_regex / invoke_end_token, fall through to the unchanged full path. Output is identical; the 30K-token call drops to ~20 ms. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
+1, we ran into the same thing serving DeepSeek V4. Sometimes the model gets stuck repeating inside a string arg, e.g. a One more thing, not blocking.
Each delta is still well under 1ms, so it's not a hang, just more total CPU. The catch is |
|
Thanks, glad it matched what you saw. Good catch on |
|
@hnyls2002 friendly ping on this one. It removes the quadratic re-scan of an open DSML invoke in the DeepSeek V3.2/V4/V4.1 streaming detector: on main, a single 30K-token tool call costs about 3.5 s of event-loop CPU, and @YangChen-pro hit the same hang in production. It needs |
Motivation
DeepSeekV32Detector.parse_streaming_increment, which the V4 and V4.1 detectors inherit, keeps a long-form invoke in_bufferuntil</|DSML|invoke>arrives. On every delta it runsre.search(self.invoke_regex, current_text, re.DOTALL)over the whole buffer, only to find that the invoke is still open and break out of the loop. The(?P<body>.*?)(?P<end>(?:</…invoke>|$))part lazily walks the entire held body each time. So each delta costs O(n) in the length of the call, and one long tool call costs O(n^2).We hit this in production serving of DeepSeek V4.1 with long agentic tool calls, where
write_file/ edit-style calls carry 20-30K tokens of code in one string parameter. On an older build, from before #39632, the same path also re-parsed and diffed the partial arguments on every delta. That capped delivery at about 1-2K tok/s per replica once a few such calls were in flight, and it backed up the tokenizer-manager output path. #39632 removed argument streaming, which cut the cost about 6x, but the re-scan is still quadratic. On currentmain(14ad64c), a 30K-token call in 18-char deltas costs 3.5 s of CPU, and each delta near the end of the call costs about 1.2 ms. That works out to:Profile on
main(V4.1, 10K-token string parameter, 1,959 deltas): 0.389 s of the 0.406 s total (96%) isre.Pattern.search. Everything else is constant per delta.Modifications
python/sglang/srt/function_call/deepseekv32_detector.py, +33 lines. Nothing else changes.(buffer, scan_from)inself._open_invoke.scan_fromis the start of the invoke body, orlen(buffer) - len(invoke_end_token) + 1if that is later.self._bufferis still that exact object, search only fromscan_fromforinvoke_end_token:StreamingParseResult(). This is exactly what the full path returns for an open invoke, and the full path changes no state other than the buffer.finish(), a buffer replaced from outside (_bufferis not the recorded object), and a subclass that replacesinvoke_regexorinvoke_end_tokenafter__init__(the fast path is never armed).Why this preserves behaviour:
[^"]+name ends at the first", which lies at or before the open invoke's own header. Adding text cannot change that.$. Any closer starting beforeold_len - len(closer) + 1would have been entirely inside the old buffer, and it was not there.normal_text=""and no calls, and it changes nothing except the buffer.test/registered/unit/function_call/test_deepseek_dsml_long_streaming.py(new, CPU), for V3.2, V4 and V4.1. Each transcript is a 3K-char code string parameter that contains<,</,<|DSML|and a partial invoke closer, followed by a JSON-body invoke and a self-closing invoke:test_incremental_matches_full_rescan: chunk sizes 1, 3, 7 and 18. Per delta, the results and_bufferequal those of a detector whose shortcut is cleared before every delta (the full re-scan).finish()also matches, and the calls and arguments match the expected ones.test_open_invoke_is_not_rescanned_per_delta: a 60K-char call in 18-char deltas. The total length of strings handed tore.searchmust stay under 4x the transcript length. This bound does not depend on timing. Onmainthe count is about 216M characters, against a bound of about 0.5M, so the test fails without the fix.Accuracy Tests
No output changes: streamed
normal_text, tool calls, detector state,finish()anddetect_and_parse()are identical. That was checked by:sglang's own tests: every file in
test/registered/unit/function_call/, plustest/registered/unit/parser/test_reasoning_parser.py, passes with and without the change. This includes the 25 tests intest_deepseekv4_detector.py,test_unexpected_parse_error_fails_closed(thepatch.objecterror path), and the V4.1 encoder round trip throughReasoningParser+FunctionCallParserat chunk sizes 1-1000. The one exception is two subtests intest_iquest_q1_detector.py, which need the full serving stack (fastapi) that was not installed locally. They fail the same way onmain.Differential fuzz,
main's original detector vs this change: 20,000 generated DSML transcripts across V3.2, V4 and V4.1, 46.8M characters in total. The transcripts include:<,</, partial and complete DSML tags inside values and names;Each transcript is replayed under 1-char, random 1-40, token-like and empty-chunk chunkings, plus every 2-way split for short ones. That is 422,412 stream runs and 21.4M deltas, of which 17.8M took the new path. After every delta, the comparison covers
normal_text, the calls, logged warnings/errors and the detector state. At the end it also coversfinish()anddetect_and_parse(). 0 divergences.Hand-written edge cases: 51, including:
_parse_parameters_from_xmlorhas_tool_call, or replaceinvoke_regexwith one that also ends an invoke at a blank line, or changeinvoke_end_token;_bufferwith an equal copy, with"", or with different text.0 divergences. Three deliberately broken variants of the change were each caught: one that skips the boundary overlap, one with no
invoke_regexguard, and one with no buffer-identity check.A separate adversarial differential fuzzer, with its own generators, chunkers and comparator, also compares raised exceptions: 454K cases and 65.6M deltas (exhaustive short splits, grammar-generated, mutated, random-walk and long values), with 0 counterexamples.
Speed Tests and Profiling
This is CPU time (
time.process_time) for one streamed call in 18-char deltas, about 5 tokens each at 3.5 chars/token, on Python 3.13 on an Apple M4 Pro, single thread. "identical" means the per-delta results are equal between the two versions.string="true"string="true"string="true"string="true"string="true"string="true"string="false"(JSON array)string="false"(JSON array)main, 4.3 µs with this PR. The one delta that delivers the closer still runs the full parse once, about 1-2 ms for a 105K-char body.mainand 1.3-1.8M tok/s with this PR, with identical outputs.<b>/</p>/a<3): 1,537 ns per delta onmain, 1,590 ns with this PR, about +3% (~50 ns). That comes from one extra attribute swap and anischeck per delta.What remains O(n) per delta is
self._buffer += new_text, a C-level copy that the buffer contract already requires. For a 105K-char buffer it is a few µs.Checklist
pre-commit runon the changed files: isort 7.0.0, ruff 0.15.1 check + format, codespell 2.4.1 and the repo's local hooks all pass)test/registered/unit/function_call/test_deepseek_dsml_long_streaming.py, CPU)Pre-existing streaming-parser behaviours found while fuzzing, which this PR deliberately does not change, are filed separately: #44941
Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ci🤖 Generated with Claude Code
CI States
Latest PR Test (Base): ❌ Run #39091707139
Latest PR Test (Extra): ❌ Run #39091706896
Latest PR Test (AMD ROCm 10): ❌ Run #39091706967