test_qwen3_reasoning_parser.py 10.5 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6

import pytest
from transformers import AutoTokenizer

7
8
9
10
11
from tests.reasoning.utils import (
    StreamingReasoningReconstructor,
    run_reasoning_extraction,
    run_reasoning_extraction_streaming,
)
12
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
13
14
15
16
17
18
from vllm.reasoning import ReasoningParser, ReasoningParserManager

parser_name = "qwen3"
start_token = "<think>"
end_token = "</think>"

19
20
21
22
23
24
25
26
27
28
29
REASONING_MODEL_NAMES = [
    "Qwen/Qwen3-0.6B",
    "Qwen/Qwen3.5-397B-A17B",
    "Qwen/Qwen3-4B-Thinking-2507",
]


@pytest.fixture(scope="module", params=REASONING_MODEL_NAMES)
def qwen3_tokenizer(request):
    return AutoTokenizer.from_pretrained(request.param)

30

31
# --- <think> in prompt, only </think> in output (typical) ---
32

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
WITHOUT_START_TOKEN = {
    "output": "This is a reasoning section</think>This is the rest",
    "reasoning": "This is a reasoning section",
    "content": "This is the rest",
}
WITHOUT_START_TOKEN_STREAM = {
    "output": "This is a reasoning section</think>This is the rest",
    "reasoning": "This is a reasoning section",
    "content": "This is the rest",
}
WITHOUT_START_TOKEN_COMPLETE_REASONING = {
    "output": "This is a reasoning section</think>",
    "reasoning": "This is a reasoning section",
    "content": None,
}
48

49
# --- <think> present in output (old template / edge case) ---
50
51
52

WITH_THINK = {
    "output": "<think>This is a reasoning section</think>This is the rest",
53
    "reasoning": "This is a reasoning section",
54
55
56
57
    "content": "This is the rest",
}
WITH_THINK_STREAM = {
    "output": "<think>This is a reasoning section</think>This is the rest",
58
    "reasoning": "This is a reasoning section",
59
60
    "content": "This is the rest",
}
61

62
# --- No think tokens at all (thinking enabled, truncated) ---
63

64
65
# With thinking enabled (default), no think tokens means the output was
# truncated before </think> could be generated. All output is reasoning.
66
67
WITHOUT_THINK = {
    "output": "This is the rest",
68
69
    "reasoning": "This is the rest",
    "content": None,
70
}
71
72
73
74
# In streaming, the parser cannot distinguish "thinking disabled" from
# "reasoning in progress" when no think tokens have appeared yet.
# It assumes reasoning. The serving layer handles the "thinking disabled"
# case by checking prompt_is_reasoning_end_arr before calling the parser.
75
76
WITHOUT_THINK_STREAM = {
    "output": "This is the rest",
77
78
    "reasoning": "This is the rest",
    "content": None,
79
80
}

81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# --- <tool_call> without </think> (implicit reasoning end) ---

TOOL_CALL_BODY = (
    "<tool_call>\n<function=bash>\n<parameter=command>"
    "\ncat /etc/hosts\n</parameter>\n</function>\n</tool_call>"
)

TOOL_CALL_NO_THINK_END = {
    "output": "I need to read the file.\n\n" + TOOL_CALL_BODY,
    "reasoning": "I need to read the file.\n\n",
    "content": TOOL_CALL_BODY,
}

TOOL_CALL_WITH_THINK_NO_END = {
    "output": "<think>I need to read the file.\n\n" + TOOL_CALL_BODY,
    "reasoning": "I need to read the file.\n\n",
    "content": TOOL_CALL_BODY,
}

100
101
# --- Edge cases ---

102
103
COMPLETE_REASONING = {
    "output": "<think>This is a reasoning section</think>",
104
    "reasoning": "This is a reasoning section",
105
106
107
    "content": None,
}
MULTILINE_REASONING = {
108
    "output": "<think>This is a reasoning\nsection</think>This is the rest\nThat",
109
    "reasoning": "This is a reasoning\nsection",
110
111
    "content": "This is the rest\nThat",
}
112
113
# Truncated output: <think> present but no </think> (thinking enabled).
# Everything is reasoning because the output was cut off mid-thought.
114
115
ONLY_OPEN_TAG = {
    "output": "<think>This is a reasoning section",
116
117
    "reasoning": "This is a reasoning section",
    "content": None,
118
119
120
121
}

ONLY_OPEN_TAG_STREAM = {
    "output": "<think>This is a reasoning section",
122
    "reasoning": "This is a reasoning section",
123
124
125
    "content": None,
}

126
127
128
129
130
131
132
133
134
135
136
137
138
139
# Truncated output without <think> prefix (Qwen3.5 style where <think>
# is in the prompt). No </think> means truncation — all is reasoning.
TRUNCATED_NO_START_TOKEN = {
    "output": "This is a reasoning section",
    "reasoning": "This is a reasoning section",
    "content": None,
}

TRUNCATED_NO_START_TOKEN_STREAM = {
    "output": "This is a reasoning section",
    "reasoning": "This is a reasoning section",
    "content": None,
}

140
TEST_CASES = [
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    pytest.param(
        False,
        WITHOUT_START_TOKEN,
        id="without_start_token",
    ),
    pytest.param(
        True,
        WITHOUT_START_TOKEN_STREAM,
        id="without_start_token_stream",
    ),
    pytest.param(
        False,
        WITHOUT_START_TOKEN_COMPLETE_REASONING,
        id="without_start_token_complete_reasoning",
    ),
    pytest.param(
        True,
        WITHOUT_START_TOKEN_COMPLETE_REASONING,
        id="without_start_token_complete_reasoning_stream",
    ),
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    pytest.param(
        False,
        WITH_THINK,
        id="with_think",
    ),
    pytest.param(
        True,
        WITH_THINK_STREAM,
        id="with_think_stream",
    ),
    pytest.param(
        False,
        WITHOUT_THINK,
        id="without_think",
    ),
    pytest.param(
        True,
        WITHOUT_THINK_STREAM,
        id="without_think_stream",
    ),
    pytest.param(
        False,
        COMPLETE_REASONING,
        id="complete_reasoning",
    ),
    pytest.param(
        True,
        COMPLETE_REASONING,
        id="complete_reasoning_stream",
    ),
    pytest.param(
        False,
        MULTILINE_REASONING,
        id="multiline_reasoning",
    ),
    pytest.param(
        True,
        MULTILINE_REASONING,
        id="multiline_reasoning_stream",
    ),
    pytest.param(
        False,
        ONLY_OPEN_TAG,
        id="only_open_tag",
    ),
    pytest.param(
        True,
        ONLY_OPEN_TAG_STREAM,
        id="only_open_tag_stream",
    ),
211
212
213
214
215
216
217
218
219
220
    pytest.param(
        False,
        TRUNCATED_NO_START_TOKEN,
        id="truncated_no_start_token",
    ),
    pytest.param(
        True,
        TRUNCATED_NO_START_TOKEN_STREAM,
        id="truncated_no_start_token_stream",
    ),
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    pytest.param(
        False,
        TOOL_CALL_NO_THINK_END,
        id="tool_call_no_think_end",
    ),
    pytest.param(
        True,
        TOOL_CALL_NO_THINK_END,
        id="tool_call_no_think_end_stream",
    ),
    pytest.param(
        False,
        TOOL_CALL_WITH_THINK_NO_END,
        id="tool_call_with_think_no_end",
    ),
    pytest.param(
        True,
        TOOL_CALL_WITH_THINK_NO_END,
        id="tool_call_with_think_no_end_stream",
    ),
241
242
243
244
245
246
247
248
249
250
251
252
253
]


@pytest.mark.parametrize("streaming, param_dict", TEST_CASES)
def test_reasoning(
    streaming: bool,
    param_dict: dict,
    qwen3_tokenizer,
):
    output = qwen3_tokenizer.tokenize(param_dict["output"])
    output_tokens: list[str] = [
        qwen3_tokenizer.convert_tokens_to_string([token]) for token in output
    ]
254
255
256
    parser: ReasoningParser = ReasoningParserManager.get_reasoning_parser(parser_name)(
        qwen3_tokenizer
    )
257

258
259
260
    reasoning, content = run_reasoning_extraction(
        parser, output_tokens, streaming=streaming
    )
261

262
    assert reasoning == param_dict["reasoning"]
263
    assert content == param_dict["content"]
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296


# Multi-token delta tests: simulate real-world streaming where a single
# delta can contain multiple tokens (e.g., speculative decoding).
MULTI_TOKEN_DELTA_CASES = [
    pytest.param(
        # <think> grouped with following text in one delta
        ["<think>This is a reasoning section", "</think>", "This is the rest"],
        "This is a reasoning section",
        "This is the rest",
        id="start_token_grouped_with_text",
    ),
    pytest.param(
        # </think> grouped with following content in one delta
        ["reasoning section", "</think>This is the rest"],
        "reasoning section",
        "This is the rest",
        id="end_token_grouped_with_content",
    ),
    pytest.param(
        # <think> and </think> in the same delta, no content after
        ["<think>reasoning</think>"],
        "reasoning",
        None,
        id="start_and_end_in_one_delta_no_content",
    ),
    pytest.param(
        # No start token, end grouped with content (Qwen3.5 style)
        ["reasoning section", "</think>content"],
        "reasoning section",
        "content",
        id="no_start_end_grouped_with_content",
    ),
297
298
299
300
301
302
303
    pytest.param(
        # <tool_call> arrives in a separate delta after reasoning text
        ["I need to read the file.\n\n", "<tool_call>\n<function=bash>"],
        "I need to read the file.\n\n",
        "<tool_call>\n<function=bash>",
        id="tool_call_implicit_reasoning_end",
    ),
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
]


@pytest.mark.parametrize(
    "deltas, expected_reasoning, expected_content", MULTI_TOKEN_DELTA_CASES
)
def test_reasoning_streaming_multi_token_deltas(
    deltas: list[str],
    expected_reasoning: str | None,
    expected_content: str | None,
    qwen3_tokenizer,
):
    """Test that multi-token deltas don't leak <think> into reasoning."""
    parser: ReasoningParser = ReasoningParserManager.get_reasoning_parser(parser_name)(
        qwen3_tokenizer
    )

    reconstructor: StreamingReasoningReconstructor = run_reasoning_extraction_streaming(
        parser, deltas
    )

    assert reconstructor.reasoning == expected_reasoning
    assert (reconstructor.other_content or None) == expected_content
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344


# --- Tests for enable_thinking=False (thinking explicitly disabled) ---


THINKING_DISABLED_CASES = [
    pytest.param(
        "This is plain content",
        None,
        "This is plain content",
        id="thinking_disabled_plain_content",
    ),
    pytest.param(
        "Some output without think tokens",
        None,
        "Some output without think tokens",
        id="thinking_disabled_no_think_tokens",
    ),
345
346
347
348
349
350
    pytest.param(
        "I need to read the file.\n\n" + TOOL_CALL_BODY,
        None,
        "I need to read the file.\n\n" + TOOL_CALL_BODY,
        id="thinking_disabled_with_tool_call",
    ),
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
]


@pytest.mark.parametrize(
    "output, expected_reasoning, expected_content", THINKING_DISABLED_CASES
)
def test_reasoning_thinking_disabled(
    output: str,
    expected_reasoning: str | None,
    expected_content: str | None,
    qwen3_tokenizer,
):
    """When enable_thinking=False, output without </think> is all content."""
    parser: ReasoningParser = ReasoningParserManager.get_reasoning_parser(parser_name)(
        qwen3_tokenizer,
        chat_template_kwargs={"enable_thinking": False},
    )

    reasoning, content = parser.extract_reasoning(
        model_output=output,
        request=ChatCompletionRequest(messages=[], model="test-model"),
    )

    assert reasoning == expected_reasoning
    assert content == expected_content