step3_reasoning_parser.py 4.65 KB
Newer Older
Song's avatar
Song committed
1
2
3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

4
5
from collections.abc import Iterable, Sequence
from itertools import islice
6
from typing import TYPE_CHECKING
Song's avatar
Song committed
7
8
9
10

import regex as re
from transformers import PreTrainedTokenizerBase

11
from vllm.entrypoints.openai.engine.protocol import DeltaMessage
Song's avatar
Song committed
12
from vllm.logger import init_logger
13
from vllm.reasoning import ReasoningParser
Song's avatar
Song committed
14

15
16
17
18
if TYPE_CHECKING:
    from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
    from vllm.entrypoints.openai.responses.protocol import ResponsesRequest

Song's avatar
Song committed
19
20
21
22
23
24
25
logger = init_logger(__name__)


class Step3ReasoningParser(ReasoningParser):
    """
    Reasoning parser for Step3 model.

26
    The Step3 model uses </think> token to denote the end of reasoning
Song's avatar
Song committed
27
28
29
    text. This parser extracts all content before </think> as reasoning content.
    """

30
31
    def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
        super().__init__(tokenizer, *args, **kwargs)
32
        self.think_start_token = "<think>"
Song's avatar
Song committed
33
34
        self.think_end_token = "</think>"

35
        self.reasoning_regex = re.compile(rf"(.*?){self.think_end_token}", re.DOTALL)
Song's avatar
Song committed
36
37
38
39

        if not self.model_tokenizer:
            raise ValueError(
                "The model tokenizer must be passed to the ReasoningParser "
40
41
                "constructor during construction."
            )
Song's avatar
Song committed
42

43
44
        think_end_token_id = self.vocab.get(self.think_end_token)
        if think_end_token_id is None:
Song's avatar
Song committed
45
46
            raise RuntimeError(
                "Step3 reasoning parser could not locate think end "
47
48
                "token in the tokenizer!"
            )
49
        self.think_end_token_id: int = think_end_token_id
Song's avatar
Song committed
50

51
52
53
54
55
56
57
58
    @property
    def reasoning_start_str(self) -> str:
        return self.think_start_token

    @property
    def reasoning_end_str(self) -> str:
        return self.think_end_token

59
    def extract_reasoning_streaming(
Song's avatar
Song committed
60
61
62
63
64
65
66
        self,
        previous_text: str,
        current_text: str,
        delta_text: str,
        previous_token_ids: Sequence[int],
        current_token_ids: Sequence[int],
        delta_token_ids: Sequence[int],
67
    ) -> DeltaMessage | None:
Song's avatar
Song committed
68
69
70
71
72
        """
        Extract reasoning content from a delta message.
        Handles streaming output where previous + delta = current.
        Uses token IDs for faster processing.
        For text "abc</think>xyz":
73
        - 'abc' goes to reasoning
Song's avatar
Song committed
74
75
76
        - 'xyz' goes to content
        """
        # Skip single special token
77
        if len(delta_token_ids) == 1 and delta_token_ids[0] == self.think_end_token_id:
Song's avatar
Song committed
78
79
80
81
82
            return None

        if self.think_end_token_id in delta_token_ids:
            # </think> in delta, extract reasoning content and remaining content
            end_index = delta_text.find(self.think_end_token)
83
            reasoning = delta_text[:end_index]
84
85
            content = delta_text[end_index + len(self.think_end_token) :]
            return DeltaMessage(
86
                reasoning=reasoning,
87
88
                content=content if content else None,
            )
Song's avatar
Song committed
89
90
91
92
93
        elif self.think_end_token_id in previous_token_ids:
            # </think> already seen in previous text, everything is content
            return DeltaMessage(content=delta_text)
        else:
            # No </think> seen yet, everything is reasoning
94
            return DeltaMessage(reasoning=delta_text)
Song's avatar
Song committed
95

96
    def extract_reasoning(
97
        self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
98
    ) -> tuple[str | None, str | None]:
Song's avatar
Song committed
99
100
101
102
103
104
105
        # Check if the model output contains the </think> token
        if self.think_end_token not in model_output:
            # If no </think> token, everything is reasoning content
            return model_output, None
        else:
            # Find the first occurrence of </think>
            end_index = model_output.find(self.think_end_token)
106
            reasoning = model_output[:end_index]
Song's avatar
Song committed
107
108

            # Content after </think> token
109
            content = model_output[end_index + len(self.think_end_token) :] or None
Song's avatar
Song committed
110

111
            return reasoning, content
Song's avatar
Song committed
112

113
    def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
Song's avatar
Song committed
114
115
        return self.think_end_token_id in input_ids

116
    def is_reasoning_end_streaming(
117
        self, input_ids: Sequence[int], delta_ids: Iterable[int]
118
119
120
121
    ) -> bool:
        end_token_id = self.think_end_token_id
        return end_token_id in delta_ids

Song's avatar
Song committed
122
    def extract_content_ids(self, input_ids: list[int]) -> list[int]:
123
124
125
        if self.think_end_token_id not in islice(
            input_ids, 0, max(0, len(input_ids) - 1)
        ):
Song's avatar
Song committed
126
127
            return []
        else:
128
            return input_ids[input_ids.index(self.think_end_token_id) + 1 :]