Skip to content

Fix SGLANG_DEFAULT_THINKING ignored by dsv4/dsv32 reasoning parser - #28288

Open
WeiLai5432 wants to merge 2 commits into
sgl-project:mainfrom
WeiLai5432:fix-dsv4-default-thinking-parser-mismatch
Open

WeiLai5432 wants to merge 2 commits into
sgl-project:mainfrom
WeiLai5432:fix-dsv4-default-thinking-parser-mismatch

Conversation

@WeiLai5432

@WeiLai5432 WeiLai5432 commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

For the DeepSeek V4 / V3.2 custom encoder path, SGLANG_DEFAULT_THINKING is only read on the prompt-encoding side (_apply_jinja_template, serving_chat.py:648). The reasoning parser side (_get_reasoning_from_request) never consults the env.

As a result, when an operator sets SGLANG_DEFAULT_THINKING=1 and the client does not pass chat_template_kwargs={"thinking": true}:

  • the prompt is built in thinking mode (ends with <|Assistant|><think>), so the model does think;
  • but _get_reasoning_from_request returns False (dsv4 has no chat template → reasoning_config=None → the explicit_thinking branch only returns True when the request explicitly sets thinking=True);
  • so is_force_reasoning=False, and since the model output does not re-emit a leading <think> (it's already in the prompt), the detector treats nothing as reasoning.

Net effect: the leading reasoning text and the literal </think> marker leak into content, while reasoning_content comes back empty. This is confusing — the env appears to "half-enable" thinking.

Modification

Make the resolved thinking decision a single source of truth: after resolving thinking_requested (request value, falling back to the env), persist it back onto request.chat_template_kwargs so the reasoning parser agrees with the prompt we actually built.

  • Scoped to the dsv4/dsv32 custom encoder path (chat_encoding_spec in ("dsv4", "dsv32")) — the only path the env actually drives. Jinja-template models are unaffected.
  • Uses setdefault, so an explicit thinking value in the request still wins over the env default.

Tests

Added three unit tests in test_serving_chat.py:

  • env default ON + request silent → request normalized to {"thinking": True} and parser agrees (reasoning enabled);
  • env default OFF + request silent → {"thinking": False}, parser stays off;
  • explicit thinking=False in request + env ON → explicit value wins.

Note: I was unable to run the suite locally due to unrelated dependency-version mismatches in my local env (openai / huggingface_hub / datasets). Relying on CI for full verification.

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ❌ Run #33157064760
Latest PR Test (Extra): ❌ Run #33157064494
Latest PR Test (AMD ROCm 7.2): ❌ Run #33157064716

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request addresses an issue where the reasoning parser and prompt template disagree on the thinking mode for DeepSeek v4/v32, which can cause tags to leak into the output. It resolves this by persisting the resolved thinking decision back onto the request's chat_template_kwargs and adds unit tests to verify the behavior. However, the review feedback correctly points out that performing this normalization inside _apply_jinja_template is too late in the pipeline, as _process_messages evaluates the thinking mode beforehand and can bypass _apply_jinja_template entirely. It is recommended to move this logic to the beginning of _process_messages.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +651 to +660
# Single source of truth: persist the resolved thinking decision back
# onto the request so the reasoning parser agrees with the prompt we
# actually built. Otherwise SGLANG_DEFAULT_THINKING turns thinking ON
# in the dsv4/dsv32 prompt while _get_reasoning_from_request still
# treats the request as non-thinking, leaking </think> into content.
# Scoped to the custom encoder path, which is the only one env drives.
if self.chat_encoding_spec in ("dsv4", "dsv32"):
ctk = dict(request.chat_template_kwargs or {})
ctk.setdefault("thinking", thinking_requested)
request.chat_template_kwargs = ctk

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

While persisting the resolved thinking decision back onto the request is the correct approach, doing it inside _apply_jinja_template is too late for some parts of the pipeline:\n\n1. At line 569 (inside _process_messages), thinking_mode = self._get_reasoning_from_request(request) is called before _apply_jinja_template runs. This means thinking_mode (and consequently xgrammar_reasoning) will be evaluated using the un-updated request.chat_template_kwargs, ignoring the SGLANG_DEFAULT_THINKING default.\n2. If request.input_ids is provided, _process_messages returns early (line 612) and bypasses _apply_jinja_template entirely, meaning the default is never persisted.\n\nTo make this more robust and centralized, we should perform this request normalization at the very beginning of _process_messages instead, and remove it from here.

@WeiLai5432

Copy link
Copy Markdown
Contributor Author

Thanks for the review — good catch, the feedback is correct. _process_messages evaluates thinking_mode via _get_reasoning_from_request (for the xgrammar tool-call constraint) before _apply_jinja_template runs, and _apply_jinja_template is skipped entirely when request.input_ids is set or a conversation template is used — so normalizing inside _apply_jinja_template was both too late and bypassable.

Addressed in the latest commit:

  • Moved the resolve-and-persist block to the top of _process_messages, before any consumer (parser, xgrammar constraint, prompt encoder) reads the thinking decision.
  • Broadened the scope guard from the hardcoded ("dsv4", "dsv32") to chat_encoding_spec is not None, so every custom-encoder path is covered.
  • Added a regression test for the input_ids bypass and one asserting unrelated chat_template_kwargs keys (e.g. reasoning_effort) are preserved.

Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
…4600 — reasoning leak, effort mapping, tool-call streaming

Three upstream fixes ported to b300-glm52 (v0.5.15 base):

1. sgl-project#28288 — SGLANG_DEFAULT_THINKING ignored by dsv4 reasoning parser
   Root cause: prompt encoder reads SGLANG_DEFAULT_THINKING but reasoning
   parser does not, so thinking prompt produces output that parser treats
   as non-thinking → reasoning text +  leaks into content.
   Fix: _process_messages persists thinking=envs.SGLANG_DEFAULT_THINKING
   onto chat_template_kwargs so both prompt encoder and parser agree.

2. sgl-project#33140 — reasoning_effort mapped one level off (high is no-op)
   Root cause: encoding_dsv4.py only supports max/None/high (preview
   profile). Official profile has 3 levels: low (empty), high, max.
   Fix: add _detect_dsv4_reasoning_effort_profile() that reads
   encoding/encoding_dsv4.py from model path to detect official vs
   preview. Official profile accepts low/high/max; preview accepts
   high/max. Override via SGLANG_DSV4_REASONING_EFFORT_PROFILE env.

3. sgl-project#34600 — Harden DeepSeek-V4 tool-call streaming (4 bugs)
   Bug 1: exception handler clears self._buffer → tool call permanently lost
   Bug 2: rstrip(token) truncates values ending with same chars
   Bug 3: bare '|DSML|' marker traps response text mentioning DSML tags
   Bug 4: finish() leaks partial DSML tags into normal_text
   Fix: _DSML_TOOL_TAGS (specific tags), removesuffix, targeted trap check,
   finish() strips partial tags.
lingcai.wl and others added 2 commits August 28, 2026 16:40
For the DeepSeek V4 / V3.2 custom encoder path, SGLANG_DEFAULT_THINKING
was only read on the prompt-encoding side (`_apply_jinja_template`). The
reasoning parser side (`_get_reasoning_from_request`) never consults the
env, so when an operator set SGLANG_DEFAULT_THINKING=1 and the client did
not pass `chat_template_kwargs={"thinking": true}`, the model was forced
into thinking mode in the prompt while the parser still treated the
request as non-thinking. The leading reasoning and the literal `</think>`
marker then leaked into `content` and `reasoning_content` came back empty.

Make the resolved thinking decision a single source of truth: persist it
back onto `request.chat_template_kwargs` so the parser agrees with the
prompt we actually built. Scoped to the dsv4/dsv32 custom encoder path,
the only path the env actually drives, so jinja-template models are
unaffected. An explicit `thinking` value in the request still wins.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…om encoders

Address review feedback: normalizing inside _apply_jinja_template was too
late and could be bypassed.

- _process_messages evaluates thinking_mode (for the xgrammar tool-call
  constraint) via _get_reasoning_from_request *before* _apply_jinja_template
  runs, so the constraint saw the un-normalized request.
- _apply_jinja_template is skipped entirely when request.input_ids is set or
  a conversation template is used, so the normalization never ran for those.

Move the resolve-and-persist block to the top of _process_messages, before
any consumer reads the thinking decision, and broaden the scope guard from
the hardcoded ("dsv4", "dsv32") to `chat_encoding_spec is not None` so every
custom encoder path is covered. Add a regression test for the input_ids
bypass and assert unrelated chat_template_kwargs keys are preserved.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@WeiLai5432
WeiLai5432 force-pushed the fix-dsv4-default-thinking-parser-mismatch branch from 8b6be18 to ade835b Compare August 28, 2026 08:52
@WeiLai5432

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main (ade835be8d) — conflicts from the recent chat_encoding refactor are resolved; the fix itself is unchanged.

Recap for reviewers:

  • Bug: with SGLANG_DEFAULT_THINKING=1 and no explicit chat_template_kwargs, the dsv4/dsv32 prompt is built in thinking mode while _get_reasoning_from_request still returns False (explicit_thinking only honors an explicit request kwarg), so the leading reasoning and the literal </think> marker leak into content and reasoning_content comes back empty.
  • Fix: resolve the thinking decision once at the top of _process_messages and persist it onto request.chat_template_kwargs, so the prompt encoder, the reasoning parser (request time + response time), and the xgrammar tool-call constraint all agree. setdefault keeps an explicit request value winning over the env; jinja/conversation-template models are unaffected.
  • Tests: +4 unit tests covering env on/off, explicit override, and the input_ids bypass.

Note: pr-gate is failing only because the run-ci label is missing (outside contributors can't add labels). Could a maintainer please add run-ci so CI can run?

cc @hnyls2002 for a look when convenient — happy to adjust if you'd rather resolve the env fallback inside the reasoning parser instead.

@gluttony-10

Copy link
Copy Markdown

Verified this failure mode is also live on the deepseek-v41 parser
(DeepSeek-V4.1-Flash on 8x RTX PRO 6000 Blackwell, sm120, dsv4.1 line):

  • With SGLANG_DEFAULT_THINKING=1 and --reasoning-parser deepseek-v41,
    thinking is enabled in the custom-encoder prompt but
    _get_reasoning_from_request still returns false → the full reasoning text
    leaks into content (reproduced: reasoning_content empty, content starts
    with reasoning prose, reasoning_tokens=None).
  • Deploying the same single-source-of-truth resolution you implemented here
    (we backported an equivalent 10-line toggle-alignment to the dsv4.1 branch)
    restores correct separation: default requests return reasoning_content
    (891-1141 chars) with clean content, and chat_template_kwargs {"thinking": false} still disables reasoning.
  • One thing worth checking in your PR: DeepSeekV4Detector is shared by both
    deepseek-v4 and deepseek-v41 parsers — please make sure the dsv41 spec
    is covered by the resolved-ctk path (our production evidence above covers
    the v41 case end-to-end, happy to provide more numbers).

Happy to send a dsv41 unit-test addition if useful.

@JohnZhao01

JohnZhao01 commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

We hit the same leak on DeepSeek-V4.1-Flash (deepseek-v41 reasoning parser), so we verified this PR end to end on current main. The fix works, but the new tests need two small updates to run on today's main.

Setup: DeepSeek-V4.1-Flash on 8×H200, TP8, image lmsysorg/sglang:nightly-dev-cu13-20261018-b234b5c3 (its serving_chat.py is byte-identical to main @ 5d9c956f), SGLANG_DEFAULT_THINKING=1, --reasoning-parser auto (resolves to deepseek-v41). The source change of this PR applies cleanly to that file. "Before" is the image as is; "after" is the image with this PR (that server also carried an unrelated fix for list-content assistant messages (#45152) in the same file, which does not touch the thinking decision). Requests are a single user turn, 10 per cell; the thinking: true / false rows combine stream and non-stream.

Request before: </think> in content before: reasoning_content set after: </think> in content after: reasoning_content set
no thinking flag, non-stream 10/10 0/10 0/10 10/10
no thinking flag, stream 10/10 0/10 0/10 10/10
thinking: true 0/20 20/20 0/20 20/20
thinking: false 0/20 0/20 0/20 0/20

So the env default now drives both the prompt and the parser, and an explicit flag still wins. No server errors in either run.

This also answers the question above about deepseek-v41 coverage: with --reasoning-parser auto the server resolves to deepseek-v41, and the fix takes effect there through the chat_encoding_spec is not None guard.

Tests on current main: the four new tests fail before reaching the code under test, for two reasons:

  1. TemplateManager moved to sglang.srt.parser.template_manager in Move template manager files under parser; update CODEOWNERS #26052, so the import in _make_dsv4_serving_chat raises ModuleNotFoundError.
  2. The helper's mock hf_config returns a Mock from to_dict().get(...), which is now read as a reasoning-effort profile override, so OpenAIServingChat.__init__ raises ValueError: Invalid dsv4_reasoning_effort_profile.

With this change to the test file only, the four new tests pass. Without the source change, three of them fail (test_dsv4_explicit_thinking_false_overrides_env_default passes on both, as expected). The existing 159 tests in test_serving_chat.py still pass.

-        from sglang.srt.managers.template_manager import TemplateManager
+        from sglang.srt.parser.template_manager import TemplateManager
@@
         mock_hf_config.architectures = ["DeepseekV4ForCausalLM"]
+        mock_hf_config.to_dict.return_value = {}

The test hunk also needs a rebase onto current main; the source hunk applies as is. We are happy to share the request scripts if that helps.

This branch has not been deployed

No deployments
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.

3 participants