|
1 | 1 | # Copyright (c) OpenMMLab. All rights reserved.
|
2 |
| -from .deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser |
3 |
| -from .reasoning_parser import ReasoningParserManager |
| 2 | +import re |
| 3 | +from typing import Optional, Sequence, Tuple, Union |
| 4 | + |
| 5 | +from lmdeploy.serve.openai.protocol import ChatCompletionRequest, DeltaMessage |
| 6 | + |
| 7 | +from .reasoning_parser import ReasoningParser, ReasoningParserManager |
4 | 8 |
|
5 | 9 |
|
6 | 10 | @ReasoningParserManager.register_module(name='qwen-qwq')
|
7 |
| -class QwenQwQReasoningParser(DeepSeekR1ReasoningParser): |
| 11 | +class QwenQwQReasoningParser(ReasoningParser): |
8 | 12 | """Reasoning parser for Qwen QwQ model.
|
9 | 13 |
|
10 | 14 | The Qwen QwQ model uses <think>...</think> tokens to denote reasoning text. This parser extracts the reasoning
|
11 | 15 | content from the model output.
|
12 | 16 | """
|
| 17 | + |
| 18 | + def __init__(self, tokenizer: object): |
| 19 | + super().__init__(tokenizer) |
| 20 | + self.think_start_token = '<think>' |
| 21 | + self.think_end_token = '</think>' |
| 22 | + |
| 23 | + self.reasoning_regex = re.compile(rf'{self.think_start_token}(.*?){self.think_end_token}', re.DOTALL) |
| 24 | + |
| 25 | + if not self.model_tokenizer: |
| 26 | + raise ValueError('The model tokenizer must be passed to the ReasoningParser ' |
| 27 | + 'constructor during construction.') |
| 28 | + |
| 29 | + def extract_reasoning_content_streaming( |
| 30 | + self, |
| 31 | + previous_text: str, |
| 32 | + current_text: str, |
| 33 | + delta_text: str, |
| 34 | + previous_token_ids: Sequence[int], |
| 35 | + current_token_ids: Sequence[int], |
| 36 | + delta_token_ids: Sequence[int], |
| 37 | + **kwargs, |
| 38 | + ) -> Union[DeltaMessage, None]: |
| 39 | + """Instance method that should be implemented for extracting reasoning |
| 40 | + from an incomplete response; for use when handling reasoning calls and |
| 41 | + streaming. |
| 42 | +
|
| 43 | + Has to be an instance method because it requires state - the current tokens/diffs, but also the information |
| 44 | + about what has previously been parsed and extracted (see constructor) |
| 45 | + """ |
| 46 | + # Skip single special tokens |
| 47 | + if delta_text == self.think_end_token or delta_text == self.think_start_token: |
| 48 | + return DeltaMessage(content='') |
| 49 | + |
| 50 | + # Check if <think> is present in previous or delta. |
| 51 | + # Keep compatibility with models that don't generate <think> tokens. |
| 52 | + if self.think_start_token in previous_text: |
| 53 | + if self.think_end_token in delta_text: |
| 54 | + # <think> in previous, </think> in delta, |
| 55 | + # extract reasoning content |
| 56 | + end_index = delta_text.find(self.think_end_token) |
| 57 | + reasoning_content = delta_text[:end_index] |
| 58 | + content = delta_text[end_index + len(self.think_end_token):] |
| 59 | + return DeltaMessage(reasoning_content=reasoning_content, content=content if content else None) |
| 60 | + elif self.think_end_token in previous_text: |
| 61 | + # <think> in previous, </think> in previous, |
| 62 | + return DeltaMessage(content=delta_text) |
| 63 | + else: |
| 64 | + # <think> in previous, no </think> in previous or delta, |
| 65 | + # reasoning content continues |
| 66 | + return DeltaMessage(reasoning_content=delta_text) |
| 67 | + elif self.think_start_token in delta_text: |
| 68 | + if self.think_end_token in delta_text: |
| 69 | + # <think> in delta, </think> in delta, extract reasoning content |
| 70 | + start_index = delta_text.find(self.think_start_token) |
| 71 | + end_index = delta_text.find(self.think_end_token) |
| 72 | + reasoning_content = delta_text[start_index + len(self.think_start_token):end_index] |
| 73 | + content = delta_text[end_index + len(self.think_end_token):] |
| 74 | + return DeltaMessage(reasoning_content=reasoning_content, content=content if content else None) |
| 75 | + else: |
| 76 | + # <think> in delta, no </think> in delta, |
| 77 | + # reasoning content continues |
| 78 | + return DeltaMessage(reasoning_content=delta_text) |
| 79 | + else: |
| 80 | + # No <think> in previous or delta, also need to check for </think>. |
| 81 | + # Because the model may have generated </think> without <think> |
| 82 | + # Ref https://huggingface.co/deepseek-ai/DeepSeek-R1/commit/8a58a132790c9935686eb97f042afa8013451c9f |
| 83 | + if self.think_end_token in delta_text: |
| 84 | + # </think> in delta with more tokens, |
| 85 | + # extract reasoning content and content |
| 86 | + end_index = delta_text.find(self.think_end_token) |
| 87 | + reasoning_content = delta_text[:end_index] |
| 88 | + content = delta_text[end_index + len(self.think_end_token):] |
| 89 | + return DeltaMessage(reasoning_content=reasoning_content, content=content if content else None) |
| 90 | + elif self.think_end_token in previous_text: |
| 91 | + # </think> in previous, thinking content ends |
| 92 | + return DeltaMessage(content=delta_text) |
| 93 | + else: |
| 94 | + # no </think> in previous or delta, reasoning content continues |
| 95 | + return DeltaMessage(reasoning_content=delta_text) |
| 96 | + |
| 97 | + def extract_reasoning_content(self, model_output: str, request: ChatCompletionRequest, |
| 98 | + **kwargs) -> Tuple[Optional[str], Optional[str]]: |
| 99 | + """Extract reasoning content from a complete model-generated string. |
| 100 | +
|
| 101 | + Used for non-streaming responses where we have the entire model response |
| 102 | + available before sending to the client. |
| 103 | +
|
| 104 | + Args: |
| 105 | + model_output (str): The model-generated string to extract reasoning content from. |
| 106 | + request (ChatCompletionRequest): he request object that was used to generate the model_output. |
| 107 | +
|
| 108 | + Returns: |
| 109 | + reasoning_content (str | None): The reasoning content. |
| 110 | + final_output (str | None): The content. |
| 111 | + """ |
| 112 | + # DeepSeek R1 doesn't generate <think> now. |
| 113 | + # Thus we assume the reasoning content is always at the start. |
| 114 | + # Ref https://huggingface.co/deepseek-ai/DeepSeek-R1/commit/8a58a132790c9935686eb97f042afa8013451c9f |
| 115 | + if self.think_end_token not in model_output: |
| 116 | + # for qwen3 model, the reasoning content is wrapped by <think> </think> xml tags |
| 117 | + return None, model_output |
| 118 | + # Add a start token if it's missing to keep compatibility. |
| 119 | + if self.think_start_token not in model_output: |
| 120 | + model_output = f'{self.think_start_token}{model_output}' |
| 121 | + # Use a regex to find the reasoning content |
| 122 | + reasoning_content = self.reasoning_regex.findall(model_output)[0] |
| 123 | + |
| 124 | + end_index = len(f'{self.think_start_token}{reasoning_content}{self.think_end_token}') |
| 125 | + final_output = model_output[end_index:] |
| 126 | + if reasoning_content.startswith('\n'): |
| 127 | + reasoning_content = reasoning_content[1:] |
| 128 | + if reasoning_content.endswith('\n'): |
| 129 | + reasoning_content = reasoning_content[:-1] |
| 130 | + |
| 131 | + if len(final_output) == 0: |
| 132 | + return reasoning_content, None |
| 133 | + |
| 134 | + return reasoning_content, final_output |
0 commit comments