verl icon indicating copy to clipboard operation
verl copied to clipboard

[rollout] feat: add reasoning parser to strip think blocks before tool extraction (fixes #6424)

Open abinggo opened this issue 6 months ago • 6 comments

Summary

Closes #6424 (and the three sibling issues #4757 / #6223 / #6252 that share the same root cause).

The agent loop's token-in-token-out pipeline has been apply chat template → generate() → decode → tool parser with no reasoning-parser step in between. Reasoning models (Qwen3 thinking, DeepSeek-R1, GLM-4 thinking) often emit <tool_call> patterns inside <think>...</think> blocks as part of their chain of thought. The regex-based ToolParser then treats those think-block tool calls as real invocations and executes them during training — polluting the conversation history (#4757), teaching the model that loose tool-call placement is acceptable, and triggering benchmark regression once eval harnesses use stricter parsing (#6223 / #6252).

This PR adds an opt-in reasoning-parser step that mirrors what vLLM and SGLang already apply on the chat-completion serving path:

generate() → decode → reasoning_parser → tool_parser → execute

reasoning_parser=None (the default) keeps the legacy behavior, so existing pipelines are unchanged.

What changed

  • verl/experimental/agent_loop/reasoning_parser.py (new): ReasoningParser ABC with a registry, mirroring the existing ToolParser design. ThinkBlockReasoningParser strips both fully-bracketed <think>...</think> (regex.DOTALL) and unclosed <think> truncations to end-of-text. Registered as qwen3 and deepseek_r1 aliases. Users register custom parsers with @ReasoningParser.register("your-format").
  • verl/workers/config/rollout.py: MultiTurnConfig.reasoning_parser: Optional[str] = None.
  • verl/trainer/config/rollout/rollout.yaml + generated PPO yamls: surface the new field so reasoning_parser=qwen3 Hydra overrides work without + and config dumps include it.
  • verl/experimental/agent_loop/tool_agent_loop.py: ToolAgentLoop.__init__ instantiates the parser when configured. _handle_generating_state decodes once, strips reasoning, re-encodes with add_special_tokens=False only when stripping actually changed the text, then hands the filtered ids to tool_parser.extract_tool_calls unchanged.
  • tests/experimental/agent_loop/test_reasoning_parser_on_cpu.py (new):
    • 8 unit tests on ReasoningParser.extract_content (single block, newlines, plain-text passthrough, multi-block, unclosed truncation, idempotence, registry alias, unknown-name error, custom register decorator).
    • 2 integration tests with a byte-level mock tokenizer (perfect roundtrip) and a real HermesToolParser:
      • The think-block fake call is dropped and only the post-</think> real call surfaces — the exact regression #6424 / #4757 / #6223 / #6252 report.
      • With reasoning_parser=None (the default) the legacy behavior is preserved byte-for-byte; spurious think-block calls still execute, so the off-by-default contract is locked in.
    • All 12 tests pass locally.

Why a tokenizer roundtrip is safe (Qwen3 / DeepSeek-R1)

decode (skip_special_tokens=True) → strip → encode (add_special_tokens=False) only mutates response_ids when the stripped text actually differs. For the target tokenizers, <think> and </think> are added tokens with special: false in the upstream HF configs, so skip_special_tokens=True does not erase them and the decode side carries the markers. The integration test uses a byte-level mock tokenizer with perfect roundtrip to lock the pipeline contract independently of any specific HF tokenizer.

ToolParser implementations whose decode policy is skip_special_tokens=False (gpt-oss, gemma4) are not the intended target — those models have their own COT handling inside the parser. The new feature is documented as targeting the XML / Hermes / Qwen-style parsers.

Test plan

KMP_DUPLICATE_LIB_OK=TRUE PYTHONPATH=. \
    python3 -m pytest tests/experimental/agent_loop/test_reasoning_parser_on_cpu.py -v
# 12 passed

pre-commit run
# ruff / ruff-format / mypy / autogen-trainer-cfg / docstring coverage / license /
# device API / DataProto / structure / naming / example naming / compile
# -> all Passed

Out of scope (intentional)

  • Refactoring ToolParser.extract_tool_calls to take text directly (avoiding the small re-encode roundtrip this PR adds).
  • Migrating GptOssToolParser's in-parser COT strip to a registered ReasoningParser.

Both are reasonable follow-ups but neither is load-bearing for #6424; happy to follow up with either if maintainers prefer.

Duplicate-work check

gh pr list --repo verl-project/verl --search "6424 in:body"           # 0
gh pr list --repo verl-project/verl --search "reasoning_parser agent_loop"  # 0
gh pr list --repo verl-project/verl --search "agent loop think block"      # 0

abinggo avatar May 21 '26 09:05 abinggo

@wzhgba Could you help to review?

wuxibin89 avatar May 22 '26 14:05 wuxibin89

Thanks for this PR — the problem is real (#4757, #6223, #6252, #6424) and the implementation is clean: solid ABC + registry design, 12 well-structured tests, and a safe opt-in default. A few suggestions:

1. enable_thinking parameter awareness

Qwen3.5's chat template supports enable_thinking=False, which injects <think>\n\n</think>\n\n into the prompt so model output contains no think tags. With enable_thinking=True and a truncated output missing </think>, all output should be treated as reasoning. The current parser doesn't distinguish these cases — unclosed <think> always strips to end-of-text, which would incorrectly discard valid content in the disabled-thinking case. vLLM and SGLang handle this via enable_thinking from chat template kwargs. Consider adding this parameter (could be a follow-up).

2. Performance: str.partition vs regex

For the common single-block case, str.partition("</think>") stops at the first occurrence (C-level, early-terminating), whereas re.sub(r"<think>.*?</think>", ...) scans the full text. The difference is noticeable for long reasoning outputs (e.g., 32K tokens). vLLM and SGLang both use partition/split with maxsplit=1 for this reason.

3. Design note for future contributors

It would be helpful to add a brief comment in reasoning_parser.py noting that future contributors should cross-reference vLLM/SGLang reasoning parser implementations for model-specific behaviors, and that this parser intentionally omits serving-side leniency (e.g., implicit reasoning-end via <tool_call>) to maintain strict formatting expectations suitable for RL training.

None of these are blockers — happy to see this land.


感谢这个 PR —— 解决的问题是真实存在的(#4757, #6223, #6252, #6424),实现也很干净:ABC + registry 设计合理,12 个测试覆盖充分,opt-in 默认值保证了向后兼容。几点建议:

1. enable_thinking 参数感知

Qwen3.5 的 chat template 支持 enable_thinking=False,会在 prompt 中注入 <think>\n\n</think>\n\n,使模型输出不含 think 标签;而 enable_thinking=True 时输出被截断后缺失 </think>,所有输出应视为 reasoning。当前 parser 不区分这两种情况 —— 未闭合的 <think> 总是剥离到文本末尾,在禁用思考的场景下会错误丢弃正常内容。vLLM 和 SGLang 通过 chat_template_kwargs 的 enable_thinking 参数来处理。建议加入此参数(可作 follow-up)。

2. 性能:用 str.partition 替代整文 regex

对常见的单 think block 场景,str.partition("</think>") 找到第一个匹配即停止(C 级实现),而 re.sub(r"<think>.*?</think>", ...) 需要扫描全文。对长推理输出(如 32K tokens)有可感知的差异。vLLM 和 SGLang 为此都用了 partition/split + maxsplit=1。

3. 给后续开发者的设计注释

建议在 reasoning_parser.py 中加一段注释,说明后续扩展时应参考 vLLM/SGLang 的推理 parser 实现,以及本 parser 有意省略了 serving 端的宽容处理(如 <tool_call> 隐式推理结束),以保持 RL 训练所需的严格格式要求。

以上都不是阻塞项,期待合入。

wzhgba avatar May 25 '26 06:05 wzhgba

Thanks @wzhgba for the careful read — folded all three suggestions into 68d798de.

1. enable_thinking parameter awareness

Added enable_thinking: bool = True keyword-only param on ReasoningParser.extract_content (mirroring chat_template_kwargs). When False, the parser short-circuits and returns text unchanged, so a literal <think> substring in code or quoted content can't trigger the unclosed-tag fallback. Default True preserves the legacy behavior, so existing callers (including tool_agent_loop._handle_generating_state) are byte-for-byte unchanged.

Threading the kwarg through tool_agent_loop from chat_template_kwargs is left as a follow-up as you suggested — happy to send a separate PR once this lands.

2. str.partition replacing regex

Rewrote ThinkBlockReasoningParser.extract_content as an iterative str.partition loop. Each iteration partitions on the next <think> opener and on the matching </think> closer; an unclosed opener breaks the loop and drops to end-of-text. Matches the partition+maxsplit=1 idiom you mentioned, and removes the import regex since it's no longer used. The previous non-greedy .*? regex still scans the full text per call — partition is C-level and early-terminating per opener, lower constant factor on 32K-token traces, same semantics.

3. Design note for future contributors

Added a "Design notes" section to the module docstring covering (a) cross-reference to vllm/reasoning/ and sglang/srt/reasoning_parser/ for model-specific behavior, (b) the intentional omission of serving-side leniency (e.g. vLLM's Qwen3 parser closes unclosed <think> implicitly when <tool_call> arrives) — RL training needs the strict surface here, (c) the enable_thinking short-circuit semantics.

Tests added (3 new, on top of the existing 12)

  • test_qwen3_short_circuits_when_thinking_disabled — pins the new short-circuit
  • test_qwen3_disabled_thinking_preserves_unclosed_think_substring — pins the bug you flagged: literal <think> substring without closer must not collapse to end-of-text when thinking is disabled
  • test_qwen3_nested_looking_tags_keep_legacy_non_overlapping_semantics — pins the inherited non-overlapping behavior on degenerate a<think>1<think>2</think>b</think>c → ab</think>c so a future contributor doesn't accidentally "fix" it

15 tests pass locally; pre-commit clean. Force-pushed (32704428 → 68d798de).

abinggo avatar May 25 '26 08:05 abinggo

Thanks for the quick update — all three points are addressed cleanly. One more small suggestion on the API design:

enable_thinking is Qwen3-specific (chat_template_kwargs); other models may use different parameter shapes (e.g. think_effort). Consider using **kwargs at the abstract ReasoningParser.extract_content level, and letting each implementation pull its own keys:

# abstract
def extract_content(self, text: str, **kwargs) -> str: ...

# ThinkBlockReasoningParser
def extract_content(self, text: str, **kwargs) -> str:
    if not kwargs.get("enable_thinking", True):
        return text
    ...

This keeps the base interface model-agnostic and allows future parsers to add their own parameters without touching the abstraction.

Again, thanks for the thorough work.


感谢快速更新,三条建议都落实得很干净。补充一个小建议:

enable_thinking 是 Qwen3 特有的参数(来自 chat_template_kwargs),其他模型可能用不同形态的参数(如 think_effort 等)。建议抽象接口用 **kwargs,让各实现层自己解包:

# 抽象层
def extract_content(self, text: str, **kwargs) -> str: ...

# ThinkBlockReasoningParser
def extract_content(self, text: str, **kwargs) -> str:
    if not kwargs.get("enable_thinking", True):
        return text
    ...

这样基类接口保持模型无关,后续 parser 扩展时不需改动抽象层。

再次感谢细致的工作。

wzhgba avatar May 25 '26 08:05 wzhgba

Thanks @wzhgba — fully agreed on keeping the abstract layer model-agnostic. Folded the kwargs design into 32ae4c67:

ABC signature

  • ReasoningParser.extract_content now takes text: str, **kwargs so any future model can surface its own knobs (think_effort, reasoning_budget, etc.) without touching the abstract layer.
  • Docstring spells out the contract: implementations pull only the keys they understand and silently ignore unknown ones, so callers can forward chat_template_kwargs verbatim without per-parser conditioning.

ThinkBlockReasoningParser

  • Reads kwargs.get("enable_thinking", True) at the start; default-True path unchanged for byte-for-byte legacy compatibility.

Tests

  • Updated _CustomParser test fixture signature to **kwargs.
  • Added test_qwen3_ignores_unknown_kwargs pinning three contracts: (a) lone unknown kwarg (think_effort="low") is no-op, (b) unknown kwargs mixed with enable_thinking=True still strip correctly, (c) unknown kwargs don't subvert the enable_thinking=False short-circuit.

16 tests pass locally; pre-commit clean. Force-pushed (68d798de → 32ae4c67).

abinggo avatar May 25 '26 09:05 abinggo

Thanks @wuxibin89 — folded the design change into 60b7e15a.

Layer move (V5)

Rebuilt ToolParser as a template-method base: extract_tool_calls is now the public concrete entry point that calls _maybe_strip_reasoning (when a reasoning_parser was configured) and delegates to _extract_tool_calls for the parser-specific logic. The four in-tree parsers (hermes / gpt-oss / qwen3_coder / gemma4) renamed extract_tool_calls → _extract_tool_calls, and ToolAgentLoop._handle_generating_state now just calls self.tool_parser.extract_tool_calls(response_ids, tools, **self.apply_chat_template_kwargs) — the decode/strip/re-encode plumbing is gone. Custom AgentLoop subclasses (SWEAgentLoop / GUIAgentLoop) inherit reasoning-aware extraction by virtue of constructing the parser via ToolParser.get_tool_parser(name, tokenizer, reasoning_parser=...).

Backward compatibility

Two paths preserved after a codex CR pass flagged the original draft as a real extension API break:

  • _extract_tool_calls is not @abstractmethod. It defaults to raising NotImplementedError. External subclasses that only override the legacy extract_tool_calls directly remain valid concrete classes — they just bypass the reasoning-strip layer until they opt in.
  • ToolParser.get_tool_parser keeps the legacy two-arg constructor path when reasoning_parser is None, so externally-registered parsers whose __init__ predates the new kwarg keep working.

chat_template_kwargs threading

ToolParser.extract_tool_calls now accepts **kwargs and forwards them through _maybe_strip_reasoning into ReasoningParser.extract_content, so the enable_thinking short-circuit you flagged earlier reaches the strip layer end-to-end. The agent loop already had self.apply_chat_template_kwargs from the base class — wiring it into extract_tool_calls was a one-line change at the call site.

Tests added (4 new, on top of the existing 15)

  • Updated the two integration tests to construct HermesToolParser(tokenizer, reasoning_parser=...) and call extract_tool_calls directly — they now exercise the new layer end-to-end (think-block tool call dropped vs. legacy reasoning_parser=None keeps spurious call).
  • test_tool_parser_skips_strip_when_no_reasoning_markers pins the identity fast-path: when the decoded text has no <think> markers, _maybe_strip_reasoning returns the original responses_ids (avoiding the encode round-trip).
  • test_all_registered_tool_parsers_override_extract_tool_calls reflection-checks that every registered parser overrides _extract_tool_calls or extract_tool_calls, so a future contributor can't silently register a parser that inherits the NotImplementedError default.

19 tests pass locally; pre-commit clean (ruff, mypy, autogen-trainer-cfg, etc.). Force-pushed (32ae4c67 → 60b7e15a).

abinggo avatar May 26 '26 11:05 abinggo