deepseek_r1_reasoning_parser.py 6.93 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
import re
4
5
from collections.abc import Sequence
from typing import Optional, Union
6
7
8
9
10
11

from transformers import PreTrainedTokenizerBase

from vllm.entrypoints.openai.protocol import (ChatCompletionRequest,
                                              DeltaMessage)
from vllm.logger import init_logger
12
from vllm.reasoning import ReasoningParser, ReasoningParserManager
13
14
15
16
17
18
19
20
21

logger = init_logger(__name__)


@ReasoningParserManager.register_module("deepseek_r1")
class DeepSeekR1ReasoningParser(ReasoningParser):
    """
    Reasoning parser for DeepSeek R1 model.

22
    The DeepSeek R1 model uses <think>...</think> tokens to denote reasoning
23
24
25
    text. This parser extracts the reasoning content from the model output.
    """

26
27
28
29
30
31
    start_token_id: int
    end_token_id: int

    start_token: str = "<think>"
    end_token: str = "</think>"

32
33
34
35
    def __init__(self, tokenizer: PreTrainedTokenizerBase):
        super().__init__(tokenizer)

        self.reasoning_regex = re.compile(
36
            rf"{self.start_token}(.*?){self.end_token}", re.DOTALL)
37
38
39
40
41
42

        if not self.model_tokenizer:
            raise ValueError(
                "The model tokenizer must be passed to the ReasoningParser "
                "constructor during construction.")

43
44
45
        self.start_token_id = self.vocab.get(self.start_token)
        self.end_token_id = self.vocab.get(self.end_token)
        if self.start_token_id is None or self.end_token_id is None:
46
47
48
49
            raise RuntimeError(
                "DeepSeek R1 reasoning parser could not locate think start/end "
                "tokens in the tokenizer!")

50
    def is_reasoning_end(self, input_ids: list[int]) -> bool:
51
        return self.end_token_id in input_ids
52
53
54
55
56

    def extract_content_ids(self, input_ids: list[int]) -> list[int]:
        """
        Extract the content after the end tokens
        """
57
        if self.end_token_id not in input_ids[:-1]:
58
59
            return []
        else:
60
            return input_ids[input_ids.index(self.end_token_id) + 1:]
61

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    def extract_reasoning_content_streaming(
        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],
    ) -> Union[DeltaMessage, None]:
        """
        Extract reasoning content from a delta message.
        Handles streaming output where previous + delta = current.
        Uses token IDs for faster processing.
        For text <think>abc</think>xyz:
        - 'abc' goes to reasoning_content
        - 'xyz' goes to content
        """
        # Skip single special tokens
        if len(delta_token_ids) == 1 and (delta_token_ids[0] in [
81
                self.start_token_id, self.end_token_id
82
83
84
        ]):
            return None

85
86
        # Check if <think> is present in previous or delta.
        # Keep compatibility with models that don't generate <think> tokens.
87
88
        if self.start_token_id in previous_token_ids:
            if self.end_token_id in delta_token_ids:
89
90
                # <think> in previous, </think> in delta,
                # extract reasoning content
91
                end_index = delta_text.find(self.end_token)
92
                reasoning_content = delta_text[:end_index]
93
94
95
96
97
98
                content = delta_text[end_index + len(self.end_token):]
                return DeltaMessage(
                    reasoning_content=reasoning_content,
                    content=content if content else None,
                )
            elif self.end_token_id in previous_token_ids:
99
100
101
102
103
104
105
                # <think> in previous, </think> in previous,
                # reasoning content continues
                return DeltaMessage(content=delta_text)
            else:
                # <think> in previous, no </think> in previous or delta,
                # reasoning content continues
                return DeltaMessage(reasoning_content=delta_text)
106
107
        elif self.start_token_id in delta_token_ids:
            if self.end_token_id in delta_token_ids:
108
                # <think> in delta, </think> in delta, extract reasoning content
109
110
                start_index = delta_text.find(self.start_token)
                end_index = delta_text.find(self.end_token)
111
                reasoning_content = delta_text[start_index +
112
113
114
115
116
117
                                               len(self.start_token):end_index]
                content = delta_text[end_index + len(self.end_token):]
                return DeltaMessage(
                    reasoning_content=reasoning_content,
                    content=content if content else None,
                )
118
119
120
121
122
            else:
                # <think> in delta, no </think> in delta,
                # reasoning content continues
                return DeltaMessage(reasoning_content=delta_text)
        else:
123
124
125
            # No <think> in previous or delta, also need to check for </think>.
            # Because the model may have generated </think> without <think>
            # Ref https://huggingface.co/deepseek-ai/DeepSeek-R1/commit/8a58a132790c9935686eb97f042afa8013451c9f
126
            if self.end_token_id in delta_token_ids:
127
128
                # </think> in delta with more tokens,
                # extract reasoning content and content
129
                end_index = delta_text.find(self.end_token)
130
                reasoning_content = delta_text[:end_index]
131
132
133
134
135
136
                content = delta_text[end_index + len(self.end_token):]
                return DeltaMessage(
                    reasoning_content=reasoning_content,
                    content=content if content else None,
                )
            elif self.end_token_id in previous_token_ids:
137
138
139
140
141
                # </think> in previous, thinking content ends
                return DeltaMessage(content=delta_text)
            else:
                # no </think> in previous or delta, reasoning content continues
                return DeltaMessage(reasoning_content=delta_text)
142
143
144

    def extract_reasoning_content(
            self, model_output: str, request: ChatCompletionRequest
145
    ) -> tuple[Optional[str], Optional[str]]:
146
147
148
        # DeepSeek R1 doesn't generate <think> now.
        # Thus we assume the reasoning content is always at the start.
        # Ref https://huggingface.co/deepseek-ai/DeepSeek-R1/commit/8a58a132790c9935686eb97f042afa8013451c9f
149
        if self.end_token not in model_output:
150
            return model_output, None
151
        else:
152
            # Add a start token if it's missing to keep compatibility.
153
154
            if self.start_token not in model_output:
                model_output = f"{self.start_token}{model_output}"
155
156
157
            # Use a regex to find the reasoning content
            reasoning_content = self.reasoning_regex.findall(model_output)[0]

158
            end_index = len(
159
                f"{self.start_token}{reasoning_content}{self.end_token}")
160
161
162
163
164
165
            final_output = model_output[end_index:]

            if len(final_output) == 0:
                return reasoning_content, None

            return reasoning_content, final_output