[Mini-VLLM] Cut dead subsystems across serving, connectors, parsers

- Remove P/D transfer connectors: nixl, nixl_chat, mooncake x2, hf3fs,
  moriio, hisparse, example and hidden-states connectors
- Reduce weight_transfer to the base API used by model loading
- Remove kv_offload tiering, simple_kv_offload, ec cpu/example,
  snapshot command, engine snapshot server
- Remove transformers model fallback, dsv4 tokenizers, dead platforms
  cpu/tpu/xpu, flashmla third_party, dsa, megamoe/flydsl, dead attn
  ops, dead layers (short_conv, fused_embed_norm, indexer_topk,
  relu2 gemma_ar, lightning_attn, minimax_rms_norm), gemm_rs_ar
- Keep MoE LoRA op (imported eagerly by punica_gpu); drop fp8 variant
- Rebuild parser hubs around Qwen3 adapters only (36 dead adapters)
- Remove dead tests with the code they covered

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-19 02:19:03 +07:00
co-authored by Hinata
parent 54a396586e
commit 2b544b7ba0
353 changed files with 29 additions and 121269 deletions
-54
View File
@@ -1,54 +0,0 @@
# vllm/reasoning
Every `--reasoning-parser` name resolves here. The parser has two consumers:
`ParserManager.get_parser` composes it with the tool parser into the unified
`Parser` the serving layer uses, and the structured-output manager
(`vllm/v1/structured_output/__init__.py`) instantiates it directly and calls
`is_reasoning_end` / `is_reasoning_end_streaming` every decode step to decide
when the grammar bitmask starts applying. The `ReasoningParser` interface
itself is legacy: it is kept so existing in-tree parsers and out-of-tree
plugins keep working, not as the base for new ones.
## Layout
- `abs_reasoning_parsers.py` — `ReasoningParser` (`extract_reasoning`,
`extract_reasoning_streaming`, `is_reasoning_end`,
`is_reasoning_end_streaming`, `extract_content_ids`, `adjust_request`) and
`ReasoningParserManager`.
- `__init__.py` — `_REASONING_PARSERS_TO_REGISTER`, the name → (file, class)
table that lazily registers every built-in parser.
- `basic_parsers.py` — `BaseThinkingReasoningParser`, the base for parsers
that only need a start/end token pair.
- `<model>_reasoning_parser.py` — one file per family. Either a subclass of a
`ParserReasoningAdapter` generated from a `vllm/parser/<model>.py` engine
grammar (`mistral_reasoning_parser.py`, `kimi_k2_reasoning_parser.py`; the
`_engine_` suffix is not applied consistently), or a self-contained
`ReasoningParser` subclass.
## Guidelines
- Do not change the `ReasoningParser` interface in `abs_reasoning_parsers.py`.
Out-of-tree plugins loaded through
`ReasoningParserManager.import_reasoning_parser` subclass it. New
capabilities go on `Parser` in `vllm/parser/`; if a legacy parser needs the
same capability, `DelegatingParser` supplies the default.
- For a new model, implement a unified `Parser` in `vllm/parser/` first, then
expose it here as a thin adapter subclass plus an entry in
`_REASONING_PARSERS_TO_REGISTER`.
- The `_REASONING_PARSERS_TO_REGISTER` key is what users pass on the command
line; treat renames as breaking.
- Keep adapters thin: registration, `adjust_request` tweaks, and class
attributes. Parsing logic belongs in `vllm/parser/`.
- Keep a model-specific fix inside that model's `<model>_reasoning_parser.py`,
or its grammar in `vllm/parser/<model>.py`, where possible. Touch
`abs_reasoning_parsers.py` or `basic_parsers.py` only for behavior every
parser needs, and say so in the PR.
- `is_reasoning_end_streaming` runs on the engine core for every decode step
of every structured-output request. Work on `delta_ids`; re-scanning the
full sequence makes the step cost grow with sequence length.
- The structured-output gate and the frontend's extraction must agree on
where reasoning ends, whether the turn continues with content or a tool
call. Test the end-detection methods with the same inputs as extraction.
- Comment only where the code alone would leave a reader with a question —
a request tweak in `adjust_request`, a marker handled unusually, a model
quirk being worked around. Keep it minimal and concise.
-196
View File
@@ -1,196 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import abstractmethod
from collections.abc import Iterable, Sequence
from itertools import islice
from typing import TYPE_CHECKING
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning.abs_reasoning_parsers import ReasoningParser
from vllm.tokenizers import TokenizerLike
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class BaseThinkingReasoningParser(ReasoningParser):
"""Base class for reasoning parsers that use thinking tokens.
This class provides common functionality for parsers that use start and end
tokens to delimit reasoning content (
e.g., <think>...</think>, <seed:think>...</seed:think>).
Subclasses must implement the start and end tokens via abstract
properties.
"""
@property
@abstractmethod
def start_token(self) -> str:
"""The token that starts reasoning content."""
raise NotImplementedError
@property
@abstractmethod
def end_token(self) -> str:
"""The token that ends reasoning content."""
raise NotImplementedError
@property
def reasoning_start_str(self) -> str:
return self.start_token
@property
def reasoning_end_str(self) -> str:
return self.end_token
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
if not self.model_tokenizer:
raise ValueError(
"The model tokenizer must be passed to the ReasoningParser "
"constructor during construction."
)
if not self.start_token or not self.end_token:
raise ValueError("start_token and end_token must be defined in subclasses")
start_token_id = self.vocab.get(self.start_token)
end_token_id = self.vocab.get(self.end_token)
if start_token_id is None or end_token_id is None:
raise RuntimeError(
f"{self.__class__.__name__} reasoning parser could not locate "
"think start/end tokens in the tokenizer!"
)
self.start_token_id: int = start_token_id
self.end_token_id: int = end_token_id
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
start_token_id = self.start_token_id
end_token_id = self.end_token_id
for i in range(len(input_ids) - 1, -1, -1):
if input_ids[i] == start_token_id:
return False
if input_ids[i] == end_token_id:
return True
return False
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
end_token_id = self.end_token_id
return end_token_id in delta_ids
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
"""Extract the content after the end tokens."""
if self.end_token_id not in islice(input_ids, 0, max(0, len(input_ids) - 1)):
return []
else:
return input_ids[input_ids.index(self.end_token_id) + 1 :]
def extract_reasoning_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],
) -> DeltaMessage | None:
"""Extract reasoning content from a delta message.
Handles streaming output where previous + delta = current.
Uses token IDs for faster processing.
"""
# Skip single special tokens
if len(delta_token_ids) == 1 and (
delta_token_ids[0] in [self.start_token_id, self.end_token_id]
):
return None
# Check if start token is present in previous or delta.
# Keep compatibility with models that don't generate start tokens.
if self.start_token_id in previous_token_ids:
if self.end_token_id in delta_token_ids:
# start token in previous, end token in delta,
# extract reasoning content
end_index = delta_text.find(self.end_token)
reasoning = delta_text[:end_index]
content = delta_text[end_index + len(self.end_token) :]
return DeltaMessage(
reasoning=reasoning, content=content if content else None
)
elif self.end_token_id in previous_token_ids:
# start token in previous, end token in previous,
# reasoning content continues
return DeltaMessage(content=delta_text)
else:
# start token in previous, no end token in previous or delta,
# reasoning content continues
return DeltaMessage(reasoning=delta_text)
elif self.start_token_id in delta_token_ids:
if self.end_token_id in delta_token_ids:
# start token in delta, end token in delta,
# extract reasoning content
start_index = delta_text.find(self.start_token)
end_index = delta_text.find(self.end_token)
reasoning = delta_text[start_index + len(self.start_token) : end_index]
content = delta_text[end_index + len(self.end_token) :]
return DeltaMessage(
reasoning=reasoning, content=content if content else None
)
else:
# start token in delta, no end token in delta,
# reasoning content continues
return DeltaMessage(reasoning=delta_text)
else:
# not find thinking start token
return DeltaMessage(content=delta_text)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
"""Extract reasoning content from the model output.
This is the base implementation that works for most models.
Subclasses can override this method for specific behavior.
"""
# Check if the start token is present in the model output, remove it
# if it is present.
model_output_parts = model_output.partition(self.start_token)
model_output = (
model_output_parts[2] if model_output_parts[1] else model_output_parts[0]
)
# For models that may not generate start token,
# assume the reasoning content is always at the start.
if self.end_token not in model_output:
return model_output, None
else:
reasoning, _, content = model_output.partition(self.end_token)
# If generation stops right after end-of-think, return null content
final_content = content or None
return reasoning, final_content
def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int:
"""Count tokens that fall within start/end thinking markers.
Uses a depth counter so nested spans are handled safely and stray end
tokens do not drive the counter negative.
"""
count = 0
depth = 0
for token_id in token_ids:
if token_id == self.start_token_id:
depth += 1
continue
if token_id == self.end_token_id:
if depth > 0:
depth -= 1
continue
if depth > 0:
count += 1
return count
-6
View File
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.beam import BeamReasoningParser
__all__ = ["BeamReasoningParser"]
@@ -1,60 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING, ClassVar
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.tokenizers import TokenizerLike
class BaseCohereCommandReasoningParser(ReasoningParser):
"""Expose is_reasoning_end for the structured-output engine.
Everything else runs in
:class:`vllm.parser.cohere_command.CohereCommandParser`.
"""
melody_preset: ClassVar[str]
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
self.start_token_id = tokenizer.convert_tokens_to_ids("<|START_THINKING|>")
self.end_token_id = tokenizer.convert_tokens_to_ids("<|END_THINKING|>")
self.chatbot_token_id = tokenizer.convert_tokens_to_ids("<|CHATBOT_TOKEN|>")
@property
def reasoning_start_str(self) -> str | None:
return "<|START_THINKING|>"
@property
def reasoning_end_str(self) -> str | None:
return "<|END_THINKING|>"
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
chatbot = self.chatbot_token_id
start = self.start_token_id
end = self.end_token_id
has_end_token = False
for i in reversed(range(len(input_ids))):
tid = input_ids[i]
if tid == start:
return has_end_token
if tid == chatbot:
return False
if tid == end:
has_end_token = True
return has_end_token
class CohereCommand3ReasoningParser(BaseCohereCommandReasoningParser):
melody_preset = "cmd3"
class CohereCommand4ReasoningParser(BaseCohereCommandReasoningParser):
melody_preset = "cmd4"
@@ -1,66 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
class DeepSeekR1ReasoningParser(BaseThinkingReasoningParser):
"""Reasoning parser for DeepSeek R1 model.
The DeepSeek R1 model uses <think>...</think> tokens to denote reasoning
text. This parser extracts the reasoning content from the model output.
"""
@property
def start_token(self) -> str:
"""The token that starts reasoning content."""
return "<think>"
@property
def end_token(self) -> str:
"""The token that ends reasoning content."""
return "</think>"
def extract_reasoning_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],
) -> DeltaMessage | None:
ret = super().extract_reasoning_streaming(
previous_text,
current_text,
delta_text,
previous_token_ids,
current_token_ids,
delta_token_ids,
)
if (
ret is not None
and self.start_token_id not in previous_token_ids
and self.start_token_id not in delta_token_ids
):
if self.end_token_id in delta_token_ids:
# end token in delta with more tokens,
# extract reasoning content and content
end_index = delta_text.find(self.end_token)
reasoning = delta_text[:end_index]
content = delta_text[end_index + len(self.end_token) :]
return DeltaMessage(
reasoning=reasoning,
content=content if content else None,
)
elif self.end_token_id in previous_token_ids:
# end token in previous, thinking content ends
return DeltaMessage(content=delta_text)
else:
# no end token in previous or delta, reasoning content continues
return DeltaMessage(reasoning=delta_text)
return ret
@@ -1,96 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING
from transformers import PreTrainedTokenizerBase
from vllm.reasoning import ReasoningParser
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
from .identity_reasoning_parser import IdentityReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class DeepSeekV3ReasoningParser(ReasoningParser):
"""V3 parser that delegates to either DeepSeekR1ReasoningParser or
IdentityReasoningParser based on `thinking` and `separate_reasoning`.
"""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
thinking = bool(chat_kwargs.get("thinking", False))
enable_thinking = bool(chat_kwargs.get("enable_thinking", False))
thinking = thinking or enable_thinking
self._parser: ReasoningParser
if thinking:
self._parser = DeepSeekR1ReasoningParser(tokenizer, *args, **kwargs)
else:
self._parser = IdentityReasoningParser(tokenizer, *args, **kwargs)
@property
def reasoning_start_str(self) -> str | None:
return self._parser.reasoning_start_str
@property
def reasoning_end_str(self) -> str | None:
return self._parser.reasoning_end_str
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
return self._parser.is_reasoning_end(input_ids)
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
return self._parser.is_reasoning_end_streaming(input_ids, delta_ids)
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
return self._parser.extract_content_ids(input_ids)
def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int:
return self._parser.count_reasoning_tokens(token_ids)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
return self._parser.extract_reasoning(model_output, request)
def extract_reasoning_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],
) -> "DeltaMessage | None":
return self._parser.extract_reasoning_streaming(
previous_text,
current_text,
delta_text,
previous_token_ids,
current_token_ids,
delta_token_ids,
)
class DeepSeekV3ReasoningWithThinkingParser(DeepSeekV3ReasoningParser):
"""DeepSeekV3ReasoningParser that defaults to thinking mode."""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
thinking = chat_kwargs.get("thinking", None)
enable_thinking = chat_kwargs.get("enable_thinking", None)
if thinking is None and enable_thinking is None:
chat_kwargs["thinking"] = True
chat_kwargs["enable_thinking"] = True
kwargs["chat_template_kwargs"] = chat_kwargs
super().__init__(tokenizer, *args, **kwargs)
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import DeepSeekV41ParserReasoningAdapter
__all__ = ["DeepSeekV41ParserReasoningAdapter"]
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import DeepSeekV4ParserReasoningAdapter
__all__ = ["DeepSeekV4ParserReasoningAdapter"]
-157
View File
@@ -1,157 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
from typing import TYPE_CHECKING
from transformers import PreTrainedTokenizerBase
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class Ernie45ReasoningParser(BaseThinkingReasoningParser):
"""Reasoning parser for Ernie45 thinking model.
The Ernie45 thinking model output format is
abc\n</think>\n\n<response>\ndef\n</response>\n
or abc\n</think>\ndef
"""
response_start_token: str = "<response>"
response_end_token: str = "</response>"
newline_token: str = "<0x0A>"
@property
def start_token(self) -> str:
"""The token that starts reasoning content."""
return "<think>"
@property
def end_token(self) -> str:
"""The token that ends reasoning content."""
return "</think>"
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
if not self.model_tokenizer:
raise ValueError(
"The model tokenizer must be passed to the ReasoningParser "
"constructor during construction."
)
self.response_start_token_id = self.vocab.get(self.response_start_token)
self.response_end_token_id = self.vocab.get(self.response_end_token)
self.newline_token_id = self.vocab.get(self.newline_token)
self.parser_token_ids = [self.end_token_id, self.response_end_token_id]
def extract_reasoning_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],
) -> DeltaMessage | None:
"""Extract reasoning content from a delta message.
Handles streaming output where previous + delta = current.
Uses token IDs for faster processing.
The Ernie45 thinking model output format is
abc\n</think>\n\n<response>\ndef\n</response>\n
or abc\n</think>\ndef
- 'abc' goes to reasoning
- 'def' goes to content
"""
# Skip single special tokens
if len(delta_token_ids) == 1 and (
delta_token_ids[0]
in [
self.start_token_id,
self.end_token_id,
self.response_start_token_id,
self.response_end_token_id,
]
):
return None
# No <think> in previous or delta, also need to check for </think>.
# Because the model may have generated </think> without <think>
if self.end_token_id in delta_token_ids:
# </think> in delta with more tokens,
# extract reasoning content and content
think_end_index = delta_text.find(self.end_token)
reasoning = delta_text[:think_end_index]
content = delta_text[think_end_index + len(self.end_token) :]
content = content.lstrip("\n")
response_start_idx = content.find(self.response_start_token)
response_end_idx = content.rfind(self.response_end_token)
if response_start_idx != -1:
content = content[response_start_idx + len(self.response_start_token) :]
if response_end_idx != -1:
content = content[:response_end_idx]
return DeltaMessage(
reasoning=reasoning,
content=content if content else None,
)
elif self.end_token_id in previous_token_ids:
# </think> in previous, thinking content ends
content = delta_text
if self.response_start_token_id in delta_token_ids:
content = content.lstrip("\n")
response_start_idx = content.find(self.response_start_token)
content = content[response_start_idx + len(self.response_start_token) :]
# if have </response>, remove it
response_end_idx = content.rfind(self.response_end_token)
if response_end_idx != -1:
content = content[:response_end_idx]
elif self.response_end_token_id in delta_token_ids:
response_end_idx = content.rfind(self.response_end_token)
if response_end_idx != -1:
content = content[:response_end_idx]
# remove \n after </think> or </response>
if previous_token_ids[-1] in self.parser_token_ids and (
len(delta_token_ids) > 0 and delta_token_ids[0] == self.newline_token_id
):
content = content.lstrip("\n")
# remove \n after </think>\n
if (
len(previous_token_ids) > 1
and previous_token_ids[-2] == self.end_token_id
) and (
len(delta_token_ids) > 0 and delta_token_ids[0] == self.newline_token_id
):
content = content.lstrip("\n")
return DeltaMessage(content=content if content else None)
else:
# no </think> in previous or delta, reasoning content continues
return DeltaMessage(reasoning=delta_text)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
"""Extract reasoning content from the model output.
The Ernie45 thinking model output format is
abc\n</think>\n\n\n<response>\ndef\n</response>\n
or abc\n</think>\ndef
- 'abc' goes to reasoning
- 'def' goes to content
Returns:
tuple[Optional[str], Optional[str]]: reasoning content and content
"""
reasoning, content = super().extract_reasoning(model_output, request)
if content:
start_idx = content.find(self.response_start_token)
end_idx = content.rfind(self.response_end_token)
# Simultaneously existing and in the correct order
if start_idx != -1 and end_idx != -1 and start_idx < end_idx:
content = content[start_idx + len(self.response_start_token) : end_idx]
final_content = content or None
return reasoning, final_content
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import Gemma4ParserReasoningAdapter
__all__ = ["Gemma4ParserReasoningAdapter"]
-131
View File
@@ -1,131 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.
"""Gemma4 thinking/reasoning output parsing utilities for offline inference.
Standalone functions that parse decoded model text to extract structured
thinking content from Gemma4 models. These are pure-Python utilities with
zero heavy dependencies — they work on raw decoded strings from any
inference backend (vLLM, HuggingFace, TGI, etc.).
For the OpenAI-compatible API reasoning parser (streaming +
non-streaming), see ``vllm.reasoning.gemma4_reasoning_parser``.
For tool call parsing, see ``vllm.tool_parsers.gemma4_utils``.
Usage with vLLM offline inference::
from vllm import LLM, SamplingParams
from vllm.reasoning.gemma4_utils import parse_thinking_output
llm = LLM(model="google/gemma-4-it")
outputs = llm.generate(prompt, SamplingParams(...))
text = tokenizer.decode(outputs[0].outputs[0].token_ids, skip_special_tokens=False)
# Extract thinking / answer (works with or without enable_thinking)
result = parse_thinking_output(text)
print(result["thinking"]) # chain-of-thought or None
print(result["answer"]) # final answer
Ported from ``transformers.models.gemma4.utils_gemma4`` so that vLLM users
do not need a transformers dependency for output parsing.
"""
# ---- Thinking Mode Utility ----
# Thinking delimiter tokens as they appear in decoded text.
# Gemma4 uses <|channel> (start) and <channel|> (end) as thinking delimiters.
_THINKING_START_TAG = "<|channel>"
_THINKING_END_TAG = "<channel|>"
# Sentinel tokens that may appear in decoded output.
_TURN_END_TAG = "<turn|>"
def parse_thinking_output(text: str) -> dict[str, str | None]:
"""Parse decoded Gemma4 model output.
Use this on **all** Gemma4 output regardless of whether thinking mode
was enabled. It handles three cases:
1. **Thinking enabled, tags present** — splits on ``<|channel>``/
``<channel|>`` to separate chain-of-thought from the answer and
strips the ``thought\\n`` role label.
2. **Thinking disabled, spurious label** — strips the bare
``thought\\n`` prefix that some Gemma4 models emit even
without thinking mode.
3. **Clean output** — returns the text unchanged.
The answer text is always cleaned of trailing sentinel tokens
(``<turn|>``, ``<eos>``, etc.).
Args:
text: Decoded model output text (from ``tokenizer.decode(...)``).
Returns:
A dict with keys:
- ``"thinking"``: The chain-of-thought text, or ``None`` if no
thinking delimiters were found.
- ``"answer"``: The final answer text.
Example::
>>> from vllm.reasoning.gemma4_utils import parse_thinking_output
>>> output_text = tokenizer.decode(outputs[0], skip_special_tokens=False)
>>> result = parse_thinking_output(output_text)
>>> print(result["thinking"]) # chain-of-thought reasoning or None
>>> print(result["answer"]) # final answer
"""
if _THINKING_END_TAG in text:
parts = text.split(_THINKING_END_TAG, 1)
thinking_block = parts[0]
answer = _clean_answer(parts[1])
# Extract thinking content: strip the start tag if present
if _THINKING_START_TAG in thinking_block:
thinking = thinking_block.split(_THINKING_START_TAG, 1)[1]
else:
thinking = thinking_block
# Strip the "thought\n" channel role label the model emits inside
# <|channel>thought\n...<channel|> (analogous to "user\n" in
# <|turn>user\n...<turn|>).
thinking = _strip_thought_label(thinking.strip())
thinking = thinking.strip()
return {"thinking": thinking, "answer": answer}
# No thinking delimiters found.
# Strip spurious "thought\n" role label that some Gemma4 models sometimes
# emit even without thinking mode enabled, then clean trailing tokens.
answer = _strip_thought_label(text)
answer = _clean_answer(answer)
return {"thinking": None, "answer": answer}
def _strip_thought_label(text: str) -> str:
"""Strip the spurious ``thought\\n`` label from the start of text.
Only strips when ``thought`` appears as the very first word followed by
a newline — preserving the word ``thought`` in any other context.
"""
if text.startswith("thought\n"):
return text[len("thought\n") :]
return text
def _clean_answer(text: str) -> str:
"""Clean trailing sentinel tokens from the answer text.
Strips ``<turn|>``, ``<eos>``, and surrounding whitespace that the
model appends at the end of its response.
"""
text = text.strip()
# Strip trailing <turn|> (Gemma4 turn-end marker)
if text.endswith(_TURN_END_TAG):
text = text[: -len(_TURN_END_TAG)].rstrip()
# Strip trailing <eos> if present
if text.endswith("<eos>"):
text = text[:-5].rstrip()
return text
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import Glm47MoeParserReasoningAdapter
__all__ = ["Glm47MoeParserReasoningAdapter"]
-372
View File
@@ -1,372 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
from typing import TYPE_CHECKING
import regex as re
from transformers import PreTrainedTokenizerBase
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class GraniteReasoningParser(ReasoningParser):
"""Reasoning parser for IBM Granite.
IBM granite models currently use "Here is my thought process:"
and "Here is my response:" to separate its thinking / response outputs.
"""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
# NOTE: There have been some observed occurrences of quantized
# instances of the current models using "Here's" instead of "Here is",
# so to be safe, we match on both.
self.think_start_expr = r"(?:Here's|Here is) my thought process:"
self.response_start_expr = r"(?:Here's|Here is) my response:"
self.reasoning_regex = re.compile(
rf"{self.think_start_expr}(.*?){self.response_start_expr}(.*)", re.DOTALL
)
self.valid_think_starts = [
"Here's my thought process:",
"Here is my thought process:",
]
self.valid_response_starts = ["Here's my response:", "Here is my response:"]
# Substrings to match for sequence boundaries on raw text
self.seq_boundary_end = ":"
self.seq_boundary_start = "Here"
# The longest any thinking / start of response message can be
self.longest_think_start = max(
len(think_start) for think_start in self.valid_think_starts
)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
"""Extract the reasoning content & content sections, respectively.
If the sequence doesn't match what we expect, i.e., the model generates
something else, all content is considered non-reasoning content.
Args:
model_output (str): Output of the model to be parsed.
request (ChatCompletionRequest): Request being processed.
Returns:
tuple[Optional[str], Optional[str]]: Tuple pair containing the
reasoning content and non-reasoning content.
"""
re_match = self.reasoning_regex.findall(model_output)
if not re_match:
return None, model_output
reasoning, response_content = re_match[0]
if not response_content:
return reasoning, None
return reasoning, response_content
def extract_reasoning_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],
) -> DeltaMessage | None:
"""Extract the reasoning content / content emitted by granite models;
If the sequence doesn't match what we expect, i.e., the model generates
something else, all content is considered non-reasoning content.
NOTE: Granite models do not use a special token to start their reasoning
and response sections; instead they have token sequences, e.g.,
Here is my thought process: Foo Here is my response: Bar
This increases the complexity of correctly handling streams, since we
need to watch for specific sequences and correctly parse them without
dropping content that is potentially overlapping & spanning multiple
delta messages.
Args:
previous_text (str): Previous text outside of this delta message.
current_text (str): Previous text + delta text.
delta_text (str): Text to consider and parse content from.
previous_token_ids (Sequence[int]): Token IDs of previous_text.
current_token_ids (Sequence[int]): Token IDs of current_text.
delta_token_ids (Sequence[int]): Token IDs of delta_text.
Returns:
Union[DeltaMessage, None]
DeltaMessage with either reasoning content or content, or None.
"""
reasoning, resp_seq_len, content = self._get_content_sections(current_text)
# Either we haven't finished the start of the reasoning sequence,
# or the model is generating something unexpected.
if not reasoning:
delta_message = self._get_delta_message_with_no_reasoning_bounds(
current_text, delta_text
)
# We have a start of reasoning message, but have not yet finished
# the start of response sequence.
elif not content:
delta_message = self._get_delta_message_with_no_response_bounds(
current_text, reasoning, delta_text
)
# We've finished both the start of reasoning and start of response seq.
else:
# This should never happen since we matched on the response
assert resp_seq_len is not None
delta_message = self._get_delta_message_with_both_bounds(
delta_text, reasoning, content, current_text, resp_seq_len
)
if not delta_message.content and not delta_message.reasoning:
return None
return delta_message
#### Implementation details of stream parsing for granite models
def _is_reasoning_start_substr(self, text: str) -> bool:
"""Check if a text matches one of the possible start reasoning seqs.
Args:
text (str): Text to check for leading substr.
Returns:
bool: True if any of the possible reasoning start seqs match.
"""
return any(
think_start.startswith(text) for think_start in self.valid_think_starts
)
def _is_response_start_substr(self, text: str) -> bool:
"""Check if a text matches one of the possible start response seqs.
Args:
text (str): Text to check for leading substr.
Returns:
bool: True if any of the possible response start seqs match.
"""
return any(
response_start.startswith(text)
for response_start in self.valid_response_starts
)
def _get_delta_message_with_no_reasoning_bounds(
self,
current_text: str,
delta_text: str,
) -> DeltaMessage:
"""Parse the delta message when the current text has not yet completed
its start of reasoning sequence.
Args:
current_text (str): The full previous + delta text.
delta_text (str): Text to consider and parse content from.
Returns:
DeltaMessage: Message containing the parsed content.
"""
prev_longest_length = len(current_text) - len(delta_text)
is_substr = self._is_reasoning_start_substr(current_text)
was_substr = self._is_reasoning_start_substr(current_text[:prev_longest_length])
# Check if we just generated something NOT in the special token seq;
# if so, add everything that we previously skipped with this delta
# message and append everything to content in the future.
if was_substr and not is_substr:
return DeltaMessage(
reasoning=None,
content=current_text,
)
if is_substr:
# Might still be in the special token sequence; return nothing
return DeltaMessage(reasoning=None, content=None)
# Otherwise the sequence has already been broken and we already
# corrected; just return the delta text as normal content.
return DeltaMessage(reasoning=None, content=delta_text)
def _get_delta_message_with_no_response_bounds(
self,
current_text: str,
reasoning: str,
delta_text: str,
) -> DeltaMessage:
"""Parse the delta message when the current text has both reasoning
content with no (response) content. NOTE that we may have overlapping
tokens with the start of reasoning / start of response sequences on
either side of the delta text.
Args:
current_text (str): The full previous + delta text.
reasoning (str): reasoning content from current_text.
delta_text (str): Text to consider and parse content from.
Returns:
DeltaMessage: Message containing the parsed content.
"""
# If we have no reasoning content or explicitly end with the start of
# response sequence, we are in transition to the response; need to be
# careful here, since the final token (:) will match the reasoning
# content and fully parse it out; we should not pass the : back.
ends_with_start_response_seq = any(
current_text.endswith(response_start)
for response_start in self.valid_response_starts
)
if reasoning is None or ends_with_start_response_seq:
return DeltaMessage(reasoning=None, content=None)
# Consider previous / current text only within context of the reasoning
previous_text = reasoning[: -len(delta_text)]
current_text = reasoning
# We need to be careful about adding unfinished response sequences;
# Find the place at which we MIGHT be starting a response sequence
prev_idx = previous_text.rfind(self.seq_boundary_start)
delta_idx = delta_text.rfind(self.seq_boundary_start)
# Check the state of potential start of response substring matches.
prev_was_substr = (
self._is_response_start_substr(previous_text[prev_idx:])
if prev_idx >= 0
else False
)
delta_continues_substr = (
self._is_response_start_substr(current_text[prev_idx:])
if prev_idx >= 0
else False
)
delta_new_substr = (
self._is_response_start_substr(delta_text[delta_idx:])
if delta_idx >= 0
else False
)
# Delta only contains potential continued response sequence text.
if delta_continues_substr:
return DeltaMessage(reasoning=None, content=None)
if not prev_was_substr:
# Delta may be starting a new response seq but has other text too.
if delta_new_substr:
return DeltaMessage(reasoning=delta_text[:delta_idx], content=None)
# Normal case for most reasoning text (no potential special seqs).
return DeltaMessage(reasoning=delta_text, content=None)
# The substring that previously seemed to be a potential response
# seq wasn't one; we need to add the content to the delta message,
# and also slice off the potential response sequence
elif delta_new_substr:
reasoning = previous_text[prev_idx:] + delta_text[:delta_idx]
return DeltaMessage(reasoning=reasoning, content=None)
# No new substring yet, and we broke our old one; take the whole delta
return DeltaMessage(
reasoning=previous_text[prev_idx:] + delta_text,
content=None,
)
def _get_delta_message_with_both_bounds(
self,
delta_text: str,
reasoning: str,
response_content: str,
current_text: str,
response_seq_len: int,
) -> DeltaMessage:
"""Parse the delta message when the current text has both reasoning
content and normal (response) content.
Args:
delta_text: Text to consider and parse content from.
reasoning: reasoning content from current_text.
response_content: response content from current_text.
current_text: The full previous + delta text.
response_seq_len: Len of the complete response sequence used.
Returns:
DeltaMessage: Message containing the parsed content.
"""
# Always have content; take length to the end
delta_content = delta_text[-len(response_content) :]
reasoning_end_idx = len(delta_text) - (len(response_content) + response_seq_len)
if reasoning_end_idx < 0:
delta_reasoning = None
else:
# Get the starting offset
start_reasoning_idx = (
len(reasoning) + response_seq_len + len(response_content) - 1
)
delta_offset = len(current_text) - len(delta_text)
start_offset = start_reasoning_idx - delta_offset
if start_offset < 0:
start_offset = 0
delta_reasoning = delta_text[start_offset:reasoning_end_idx]
return DeltaMessage(
reasoning=delta_reasoning,
content=delta_content,
)
def _get_content_sections(
self, current_text: str
) -> tuple[str | None, int | None, str | None]:
"""Parse the text to extract the reasoning content / content
if we have them.
Args:
current_text (str): The full previous + delta text.
Returns:
tuple[Optional[str], Optional[int], Optional[str]]: Tuple of len 3
containing the reasoning content, the length of the response seq
(if there is one) and the non-reasoning content.
"""
current_chunk_start = 0
start_reasoning = None
parsed_content = False
delimiter_idxs = [
idx
for idx, char in enumerate(current_text)
if char == self.seq_boundary_end
]
for current_chunk_end in delimiter_idxs:
current_chunk = current_text[current_chunk_start:current_chunk_end]
# Check to see if the start of reasoning seq if complete
if start_reasoning is None:
for think_start in self.valid_think_starts:
if current_chunk == think_start[:-1]:
start_reasoning = current_chunk_end + 1
current_chunk_start = current_chunk_end + 1
break
# Check to see if the start of response seq if complete
elif not parsed_content:
for response_start in self.valid_response_starts:
if current_chunk[-len(response_start) + 1 :] == response_start[:-1]:
# Mark end of reasoning and start response content
# after the start of response sequence.
end_reasoning = current_chunk_end - len(response_start)
reasoning = current_text[start_reasoning:end_reasoning]
response_content = current_text[current_chunk_end + 1 :]
return reasoning, len(response_start), response_content
if start_reasoning and not parsed_content:
return current_text[start_reasoning:], None, None
return None, None, None
@@ -1,8 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import (
GraniteThinkingParserReasoningAdapter,
)
__all__ = ["GraniteThinkingParserReasoningAdapter"]
@@ -1,226 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
from typing import TYPE_CHECKING
import regex as re
from transformers import PreTrainedTokenizerBase
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class HunyuanA13BReasoningParser(ReasoningParser):
"""Reasoning parser for Hunyuan A13B Model.
HunyuanReasoningParser
This class implements a reasoning parser specifically designed
for the Hunyuan A13B Model. It is responsible for parsing and
extracting structured reasoning and answer segments from model
outputs that follow a specific pattern.
Key Features:
- For non-stream output , Recognizes and extracts reasoning ("think")
and answer ("answer") sections from text using regular expressions.
- For stream process, it requires a token id sequences to change the
reasoning state and other state so it maintains internal state to
manage parsing across multiple token.
think start: "<think>\n": [14023, 771, 397]
think ends: "\n</think>\n<answer>\n": [198, 524, 27963, 397, 27, 9399, 397]
response ends: "\n</answer>": [524, 9399, 29]
"""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
self.think_start_expr = r"<think>\n"
self.think_end_expr = r"\n</think>\n"
self.response_start_expr = r"\n</think>\n<answer>\n"
self.response_end_expr = r"\n</answer>"
self.full_match_reasoning_regex = re.compile(
rf"(?:{self.think_start_expr}(.*?){self.response_start_expr})?(.*?){self.response_end_expr}",
re.DOTALL,
)
self.half_match_reasoning_regex = re.compile(
rf"{self.think_start_expr}(.*?){self.response_start_expr}(.*)", re.DOTALL
)
self.think_start_ids = [14023, 771, 397]
self.think_start_ids_fast = [14023, 771, 1363]
self.response_start_ids = [198, 524, 27963, 397, 27, 9399, 397]
self.response_start_ids_fast = [524, 27963, 397, 27, 9399, 397]
self.response_end_ids = [198, 524, 9399, 29]
self.fast_think_ids = [14023, 771, 1363, 524, 27963, 397, 27, 9399, 397]
# when state change, send out all the buffered text in last state
self.buffered_text: list[str] = []
self.buffered_ids: list[int] = []
self.current_state = "reasoning"
self.all_states = ["reasoning", "response"]
self.current_state = "idle"
self.expected_sequence = self.think_start_ids
# this sequence only for the think start, it has two way to start.
self.expected_sequence_side = self.think_start_ids_fast
self.sequence_index = 0
self.token_buffer: list[int] = []
self.text_buffer = ""
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
return self.current_state == "response"
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
# for hunyuan streaming reason parsing, the stream parse
# will call first, and the same token will be called in
# is_reasoning_end and extract_content_ids
# this id is not part of content, so just return [] here.
return []
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
"""Extract the reasoning content & content sections, respectively.
If the sequence doesn't match what we expect, i.e., the model generates
something else, all content is considered non-reasoning content.
Args:
model_output (str): Output of the model to be parsed.
request (ChatCompletionRequest): Request being processed.
Returns:
tuple[Optional[str], Optional[str]]: Tuple pair containing the
reasoning content and non-reasoning content.
"""
re_match = self.full_match_reasoning_regex.findall(model_output)
if re_match:
reasoning, response_content = re_match[0]
if len(reasoning) == 0:
reasoning = None
if len(response_content) == 0:
response_content = None
return reasoning, response_content
fallback_regex = self.half_match_reasoning_regex
fallback_match = fallback_regex.findall(model_output)
if fallback_match:
reasoning, response_content = fallback_match[0]
if response_content.endswith(self.response_end_expr):
response_content = response_content[: -len(self.response_end_expr)]
if len(reasoning) == 0:
reasoning = None
if len(response_content) == 0:
response_content = None
return reasoning, response_content
return None, model_output
def extract_reasoning_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],
) -> DeltaMessage | None:
"""Extract content using token ID sequence state machine."""
# Define sequences
think_start_sequence = self.think_start_ids
response_start_sequence = self.response_start_ids
response_end_sequence = self.response_end_ids
assert len(delta_token_ids) == 1
# Process each token in the delta
token = delta_token_ids[0]
def check_token_with_sequence(token):
if self.current_state == "idle" or self.current_state == "think":
return (
token == self.expected_sequence[self.sequence_index]
or token == self.expected_sequence_side[self.sequence_index]
)
else:
return token == self.expected_sequence[self.sequence_index]
def check_last_token(token):
if self.current_state == "idle" or self.current_state == "think":
# only return true if it's judge using a side sequence.
if (
self.sequence_index - 1 < len(self.expected_sequence_side)
and token == self.expected_sequence_side[self.sequence_index - 1]
):
return self.sequence_index == len(self.expected_sequence_side)
else:
return self.sequence_index == len(self.expected_sequence)
else:
return self.sequence_index == len(self.expected_sequence)
# Check if token matches expected sequence
token_in_state_seq = check_token_with_sequence(token)
if token_in_state_seq:
# Store matching token
self.token_buffer.append(token)
self.text_buffer += delta_text
self.sequence_index += 1
## state change from idle->think->response->idle
# Check if sequence fully matched
if check_last_token(token):
# State transition
if self.current_state == "idle":
self.current_state = "think"
self.expected_sequence = response_start_sequence
self.expected_sequence_side = self.response_start_ids_fast
elif self.current_state == "think":
self.current_state = "response"
self.expected_sequence = response_end_sequence
elif self.current_state == "response":
self.current_state = "idle"
self.expected_sequence = think_start_sequence
self.expected_sequence_side = self.think_start_ids_fast
# Reset matching state
self.sequence_index = 0
self.token_buffer = []
self.text_buffer = ""
# Do not send content for state transition texts.
else:
# Sequence broken - handle buffered content
if self.token_buffer and len(self.token_buffer) > 0:
# Send buffered tokens
buffered_content = self.text_buffer + delta_text
# Reset matching state
self.sequence_index = 0
self.token_buffer = []
self.text_buffer = ""
# Return content based on current state
if self.current_state == "think":
return DeltaMessage(reasoning=buffered_content, content=None)
else:
return DeltaMessage(reasoning=None, content=buffered_content)
else:
# No buffered content, send normally
if self.current_state == "think":
return DeltaMessage(reasoning=delta_text, content=None)
else:
return DeltaMessage(reasoning=None, content=delta_text)
# If no content to send in this delta
return None
-143
View File
@@ -1,143 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.logger import init_logger
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
from vllm.reasoning.identity_reasoning_parser import IdentityReasoningParser
from vllm.tokenizers import TokenizerLike
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
logger = init_logger(__name__)
class HYV3ReasoningParser(BaseThinkingReasoningParser):
"""HYV3 parser that delegates to either HYV3ReasoningParser or
IdentityReasoningParser based on `reasoning_effort`.
The HYV3 model uses <think>...</think> tokens to denote reasoning text.
This parser extracts the reasoning content from the model output.
"""
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
init_kwargs = getattr(tokenizer, "init_kwargs", None) or {}
self.suffix: str = init_kwargs.get("token_suffix") or ""
super().__init__(tokenizer, *args, **kwargs)
# First, If there is reasoning_effort in chat_kwargs,
# prioritize using chat_kwargs.reasoning_effort.
# If it's not present, use the "reasoning_effort" field
# at the outer level of the chat message.
# Otherwise, If both are empty, assign "no_think".
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
reasoning_effort = (
chat_kwargs.get("reasoning_effort")
or kwargs.get("reasoning_effort")
or "no_think"
)
logger.debug("reasoning_effort for choosing parser: %s", reasoning_effort)
self._identity_parser: IdentityReasoningParser | None
if reasoning_effort == "no_think":
self._identity_parser = IdentityReasoningParser(tokenizer, *args, **kwargs)
else:
self._identity_parser = None
@property
def start_token(self) -> str:
"""The token that starts reasoning content."""
return f"<think{self.suffix}>"
@property
def end_token(self) -> str:
"""The token that ends reasoning content."""
return f"</think{self.suffix}>"
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
if self._identity_parser is not None:
return self._identity_parser.is_reasoning_end(input_ids)
return super().is_reasoning_end(input_ids)
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
if self._identity_parser is not None:
return self._identity_parser.is_reasoning_end_streaming(
input_ids, delta_ids
)
return super().is_reasoning_end_streaming(input_ids, delta_ids)
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
if self._identity_parser is not None:
return self._identity_parser.extract_content_ids(input_ids)
return super().extract_content_ids(input_ids)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
if self._identity_parser is not None:
return self._identity_parser.extract_reasoning(model_output, request)
return super().extract_reasoning(model_output, request)
def extract_reasoning_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],
) -> DeltaMessage | None:
if self._identity_parser is not None:
return self._identity_parser.extract_reasoning_streaming(
previous_text,
current_text,
delta_text,
previous_token_ids,
current_token_ids,
delta_token_ids,
)
ret = super().extract_reasoning_streaming(
previous_text,
current_text,
delta_text,
previous_token_ids,
current_token_ids,
delta_token_ids,
)
if (
ret is not None
and self.start_token_id not in previous_token_ids
and self.start_token_id not in delta_token_ids
):
if self.end_token_id in delta_token_ids:
# end token in delta with more tokens,
# extract reasoning content and content
end_index = delta_text.find(self.end_token)
reasoning = delta_text[:end_index]
content = delta_text[end_index + len(self.end_token) :]
return DeltaMessage(
reasoning=reasoning,
content=content if content else None,
)
elif self.end_token_id in previous_token_ids:
# end token in previous, thinking content ends
return DeltaMessage(content=delta_text)
else:
# no end token in previous or delta, reasoning content continues
return DeltaMessage(reasoning=delta_text)
return ret
-323
View File
@@ -1,323 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING, TypedDict
import regex as re
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.logger import init_logger
from vllm.reasoning import ReasoningParser
from vllm.tokenizers import TokenizerLike
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
logger = init_logger(__name__)
# Must match the chat template's own default for ``reasoning_effort``.
DEFAULT_REASONING_EFFORT = "high"
class ReasoningDelta(TypedDict):
"""One streaming reasoning delta. Either/both fields may be None."""
reasoning: str | None
content: str | None
# NOTE: mirrored in ``vllm.tool_parsers.hy_v4_tool_parser`` (same pattern as
# ``gemma4_utils``) so neither package depends on the other.
def detect_token_suffix(tokenizer: TokenizerLike) -> str:
"""Detect the per-checkpoint suffix used by Hunyuan structural tokens.
Args:
tokenizer: Tokenizer of the served checkpoint.
Returns:
The suffix including its leading colon (e.g. ``":6124c78e"``), or ``""``
when the checkpoint uses unsuffixed tokens.
Raises:
RuntimeError: The tokenizer declares the structural tokens through
``model_specific_special_tokens``, which transformers 5 no longer
round-trips.
"""
init_kwargs = getattr(tokenizer, "init_kwargs", None) or {}
think_begin_as_special = init_kwargs.get("model_specific_special_tokens", {}).get(
"think_begin_token", ""
)
if think_begin_as_special:
raise RuntimeError(
"This checkpoint declares HYV4 structural tokens (think_begin_token"
"/toolcalls_begin_token/argkey_begin_token) in "
"tokenizer_config.json, which transformers 5 no longer supports. "
"Remove those fields and keep the tokens in the tokenizer's own "
"token definitions so the suffix can be read from the vocab."
)
structural_token_re = re.compile(
r"<(?:think|tool_calls|tool_call|arg_key|arg_value)(:[^\s>]+)?>"
)
for token in tokenizer.get_vocab():
match = structural_token_re.fullmatch(token)
if match:
return match.group(1) or ""
return ""
class HYV4ReasoningExtractor:
"""Reasoning extraction for HYV4, on plain data.
``thinking`` selects the mode:
- ``True``: parse ``<think>...</think>``; the start token is injected at the
end of the prompt and is therefore usually absent from the output.
- ``False``: ``no_think`` -- the whole output is content, no reasoning.
"""
def __init__(self, vocab: dict[str, int], token_suffix: str, thinking: bool = True):
self.thinking = thinking
self.start_token: str = f"<think{token_suffix}>"
self.end_token: str = f"</think{token_suffix}>"
start_token_id = vocab.get(self.start_token)
end_token_id = vocab.get(self.end_token)
if thinking and (start_token_id is None or end_token_id is None):
raise RuntimeError(
"HYV4 reasoning extractor could not locate think "
"start/end tokens in the tokenizer!"
)
# In no_think mode the ids are unused (kept for symmetry / debugging).
self.start_token_id: int | None = start_token_id
self.end_token_id: int | None = end_token_id
def has_reasoning_ended(self, token_ids: Sequence[int]) -> bool:
"""Idempotent STATE query: has ``</think>`` been emitted yet?
Monotonic -- once the end token is present this stays True. Use for
"has reasoning finished, given everything so far". (no_think is always
ended.) Contrast with ``reasoning_ended_in_delta`` (edge detector).
"""
if not self.thinking:
return True
for i in range(len(token_ids) - 1, -1, -1):
if token_ids[i] == self.start_token_id:
return False
if token_ids[i] == self.end_token_id:
return True
return False
def reasoning_ended_in_delta(
self, token_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
"""Edge detector (NOT idempotent): did reasoning end *in this* step?
True only on the step whose ``delta_ids`` contains ``</think>``. Callers
use it once behind their own "already ended" latch, so it need not be
monotonic; it only checks the new delta (cheaper than scanning the whole
sequence). Contrast with ``has_reasoning_ended`` (cumulative state).
"""
if not self.thinking:
return True
end_token_id = self.end_token_id
if end_token_id is None:
return False
return end_token_id in delta_ids
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
"""Return the token ids after ``</think>`` (all of them in no_think)."""
if not self.thinking:
return input_ids
head = input_ids[: max(0, len(input_ids) - 1)]
if self.end_token_id not in head:
return []
return input_ids[input_ids.index(self.end_token_id) + 1 :]
def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int:
"""Count reasoning tokens (0 in no_think).
The ``<think>`` start token is injected at the END of the prompt, so it
is normally absent from ``token_ids``. Only skip a leading start token
when it actually appears first (legacy / no prompt-injection); otherwise
count every token up to ``</think>``.
"""
if not self.thinking:
return 0
start = 1 if (token_ids and token_ids[0] == self.start_token_id) else 0
try:
return token_ids.index(self.end_token_id, start) - start
except ValueError:
# No end token -- reasoning was truncated; everything counts.
return len(token_ids) - start
def extract_reasoning(self, model_output: str) -> tuple[str | None, str | None]:
"""Split a complete output into ``(reasoning, content)``.
In no_think mode reasoning is None and the whole output is content. The
start token may be absent (injected in the prompt), so reasoning is
assumed to begin at the start of the output.
"""
if not self.thinking:
return None, model_output
parts = model_output.partition(self.start_token)
model_output = parts[2] if parts[1] else parts[0]
if self.end_token not in model_output:
return model_output, None
reasoning, _, content = model_output.partition(self.end_token)
return reasoning, content or None
def extract_reasoning_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],
) -> ReasoningDelta | None:
"""Classify a streaming delta as reasoning and/or content.
In no_think mode every delta is content. Otherwise: same logic as vLLM's
generic thinking parser, except the final branch (no start token seen
anywhere) treats output as reasoning-then-content, because HYV4 injects
``<think>`` in the prompt (absent from the output).
"""
if not self.thinking:
if not delta_text:
return None
return ReasoningDelta(reasoning=None, content=delta_text)
# Skip a delta that is a single lone start/end special token.
if len(delta_token_ids) == 1 and delta_token_ids[0] in (
self.start_token_id,
self.end_token_id,
):
return None
if self.start_token_id in previous_token_ids:
if self.end_token_id in delta_token_ids:
end_index = delta_text.find(self.end_token)
reasoning = delta_text[:end_index]
content = delta_text[end_index + len(self.end_token) :]
return ReasoningDelta(reasoning=reasoning, content=content or None)
elif self.end_token_id in previous_token_ids:
return ReasoningDelta(reasoning=None, content=delta_text)
else:
return ReasoningDelta(reasoning=delta_text, content=None)
elif self.start_token_id in delta_token_ids:
if self.end_token_id in delta_token_ids:
start_index = delta_text.find(self.start_token)
end_index = delta_text.find(self.end_token)
reasoning = delta_text[start_index + len(self.start_token) : end_index]
content = delta_text[end_index + len(self.end_token) :]
return ReasoningDelta(reasoning=reasoning, content=content or None)
else:
return ReasoningDelta(reasoning=delta_text, content=None)
else:
# HYV4: <think> was injected at the end of the prompt, so it never
# appears in the output. Treat the stream as reasoning until
# </think>, then content.
if self.end_token_id in delta_token_ids:
end_index = delta_text.find(self.end_token)
reasoning = delta_text[:end_index]
content = delta_text[end_index + len(self.end_token) :]
return ReasoningDelta(reasoning=reasoning, content=content or None)
elif self.end_token_id in previous_token_ids:
return ReasoningDelta(reasoning=None, content=delta_text)
else:
return ReasoningDelta(reasoning=delta_text, content=None)
def build_reasoning_extractor(
tokenizer: TokenizerLike, *, thinking: bool = True
) -> HYV4ReasoningExtractor:
return HYV4ReasoningExtractor(
tokenizer.get_vocab(), detect_token_suffix(tokenizer), thinking
)
class HYV4ReasoningParser(ReasoningParser):
"""vLLM adapter around :class:`HYV4ReasoningExtractor`.
Decides ``thinking`` from the request's ``reasoning_effort`` and converts
the extractor's ``ReasoningDelta`` to ``DeltaMessage``.
"""
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
# Decide thinking vs no_think from the request; the extractor handles
# both modes internally. Prefer chat_template_kwargs.reasoning_effort,
# then the top-level reasoning_effort. The default must match the chat
# template, which sets reasoning_effort='high' when the request omits
# it -- defaulting to no_think here would return the whole
# chain-of-thought (and a stray ``</think:SUF>``) as content.
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
reasoning_effort = chat_kwargs.get("reasoning_effort", None)
if not reasoning_effort:
reasoning_effort = (
kwargs.get("reasoning_effort") or DEFAULT_REASONING_EFFORT
)
logger.debug("reasoning_effort for choosing parser: %s", reasoning_effort)
thinking = reasoning_effort != "no_think"
self._extractor = build_reasoning_extractor(tokenizer, thinking=thinking)
# Reported regardless of the per-request thinking mode: ``ReasoningConfig``
# is engine-wide and needs the checkpoint's delimiters to derive the token
# ids used for thinking budget enforcement.
@property
def reasoning_start_str(self) -> str:
return self._extractor.start_token
@property
def reasoning_end_str(self) -> str:
return self._extractor.end_token
def is_reasoning_end(self, input_ids) -> bool:
return self._extractor.has_reasoning_ended(input_ids)
def is_reasoning_end_streaming(self, input_ids, delta_ids) -> bool:
return self._extractor.reasoning_ended_in_delta(input_ids, delta_ids)
def extract_content_ids(self, input_ids) -> list[int]:
return self._extractor.extract_content_ids(input_ids)
def count_reasoning_tokens(self, token_ids) -> int:
return self._extractor.count_reasoning_tokens(token_ids)
def extract_reasoning(
self,
model_output: str,
request: ChatCompletionRequest | ResponsesRequest,
) -> tuple[str | None, str | None]:
return self._extractor.extract_reasoning(model_output)
def extract_reasoning_streaming(
self,
previous_text: str,
current_text: str,
delta_text: str,
previous_token_ids,
current_token_ids,
delta_token_ids,
) -> DeltaMessage | None:
delta = self._extractor.extract_reasoning_streaming(
previous_text,
current_text,
delta_text,
previous_token_ids,
current_token_ids,
delta_token_ids,
)
if delta is None:
return None
return DeltaMessage(reasoning=delta["reasoning"], content=delta["content"])
@@ -1,72 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING
from transformers import PreTrainedTokenizerBase
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class IdentityReasoningParser(ReasoningParser):
"""Identity reasoning parser.
This parser does not attempt to parse or strip out reasoning tokens.
It treats the entire model output as content and ignores reasoning.
"""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
if not self.model_tokenizer:
raise ValueError(
"The model tokenizer must be passed to the ReasoningParser "
"constructor during construction."
)
@property
def reasoning_start_str(self) -> str | None:
return None
@property
def reasoning_end_str(self) -> str | None:
return None
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
# Always return True, since we never treat reasoning specially
return True
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
return True
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
# Identity: return all tokens as content
return input_ids
def extract_reasoning_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],
) -> DeltaMessage | None:
# Just wrap delta_text as content, ignore reasoning
if delta_text:
return DeltaMessage(content=delta_text)
return None
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
# No reasoning separation: return None for reasoning,
# and full model_output as content
return None, model_output
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import InklingParserReasoningAdapter
__all__ = ["InklingParserReasoningAdapter"]
@@ -1,159 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
from vllm.tokenizers import TokenizerLike
from vllm.tool_parsers.utils import partial_tag_overlap
class K2HorizonReasoningParser(DeepSeekR1ReasoningParser):
"""Reasoning parser for K2 Horizon."""
_TOOL_CALLS_START = "<ifm|tool_calls>"
_EFFORT_TOKENS: dict[str, tuple[str, str]] = {
"high": ("<ifm|think>", "</ifm|think>"),
"medium": ("<ifm|think_fast>", "</ifm|think_fast>"),
"low": ("<ifm|think_faster>", "</ifm|think_faster>"),
}
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs) -> None:
chat_template_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
effort = chat_template_kwargs.get("reasoning_effort", "high")
if not isinstance(effort, str) or effort not in self._EFFORT_TOKENS:
supported = ", ".join(self._EFFORT_TOKENS)
raise ValueError(
f"Unsupported reasoning_effort {effort!r}. "
f"Supported values: {supported}."
)
self._start_token, self._end_token = self._EFFORT_TOKENS[effort]
super().__init__(tokenizer, *args, **kwargs)
self._tool_calls_start_id = self.vocab.get(self._TOOL_CALLS_START)
self._stream_buffer = ""
self._stream_at_start = True
self._stream_finished = False
@property
def start_token(self) -> str:
return self._start_token
@property
def end_token(self) -> str:
return self._end_token
def _without_generated_start(self, model_output: str) -> str:
return model_output.removeprefix(self.start_token)
def _split_model_output(self, model_output: str) -> tuple[str, str | None]:
output = self._without_generated_start(model_output)
if self.end_token in output:
reasoning, _, content = output.partition(self.end_token)
return reasoning, content or None
tool_start = output.find(self._TOOL_CALLS_START)
if tool_start != -1:
return output[:tool_start], output[tool_start:]
return "", output or None
def extract_reasoning(
self,
model_output: str,
request: ChatCompletionRequest | ResponsesRequest,
) -> tuple[str, str | None]:
del request
return self._split_model_output(model_output)
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
for token_id in reversed(input_ids):
if token_id == self.start_token_id:
return False
if token_id == self.end_token_id or token_id == self._tool_calls_start_id:
return True
return False
def is_reasoning_end_streaming(
self,
input_ids: Sequence[int],
delta_ids: Iterable[int],
) -> bool:
del input_ids
return self._stream_finished or super().is_reasoning_end_streaming(
(), delta_ids
)
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
if self.end_token_id in input_ids:
return input_ids[input_ids.index(self.end_token_id) + 1 :]
if (
self._tool_calls_start_id is not None
and self._tool_calls_start_id in input_ids
):
return input_ids[input_ids.index(self._tool_calls_start_id) :]
return input_ids if self._stream_finished else []
def _strip_stream_start(self) -> bool:
if not self._stream_at_start:
return True
if self.start_token.startswith(self._stream_buffer):
if self._stream_buffer != self.start_token:
return False
self._stream_buffer = ""
elif self._stream_buffer.startswith(self.start_token):
self._stream_buffer = self._stream_buffer[len(self.start_token) :]
self._stream_at_start = False
return True
def extract_reasoning_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],
) -> DeltaMessage | None:
del (
previous_text,
current_text,
previous_token_ids,
current_token_ids,
delta_token_ids,
)
if self._stream_finished:
return DeltaMessage(content=delta_text) if delta_text else None
self._stream_buffer += delta_text
if not self._strip_stream_start():
return None
explicit_end = self._stream_buffer.find(self.end_token)
tool_start = self._stream_buffer.find(self._TOOL_CALLS_START)
if explicit_end != -1:
reasoning = self._stream_buffer[:explicit_end]
content = self._stream_buffer[explicit_end + len(self.end_token) :]
elif tool_start != -1:
reasoning = self._stream_buffer[:tool_start]
content = self._stream_buffer[tool_start:]
else:
overlap = max(
partial_tag_overlap(self._stream_buffer, self.end_token),
partial_tag_overlap(self._stream_buffer, self._TOOL_CALLS_START),
)
sendable_end = len(self._stream_buffer) - overlap
reasoning = self._stream_buffer[:sendable_end]
self._stream_buffer = self._stream_buffer[sendable_end:]
return DeltaMessage(reasoning=reasoning) if reasoning else None
self._stream_buffer = ""
self._stream_finished = True
return DeltaMessage(
reasoning=reasoning,
content=content or None,
)
@@ -1,8 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import KimiK2ParserReasoningAdapter
KimiK2ReasoningParser = KimiK2ParserReasoningAdapter
__all__ = ["KimiK2ReasoningParser"]
-468
View File
@@ -1,468 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Reasoning parser for the Kimi K3 (XTML) chat format.
This strips the ``think`` channel out of generated text and hands the remainder
(``response`` + ``tools`` channels) downstream. Kimi K3 wraps the thinking
channel as an XTML element built from special tokens::
<|open|>think<|sep|> <reasoning> <|close|>think<|sep|>
Two subtleties drive the implementation:
* Unlike Kimi-K2 (a single ``<think>`` token), each K3 marker is a 3-token
sequence, so the token-id helpers search for the marker *subsequence*
rather than a single id.
* In thinking mode the serving layer may feed ``<|open|>think<|sep|>`` as the
generation prefix, so the model's output can begin *inside* the think
channel with no open marker. The text paths therefore treat a missing open
marker as "reasoning starts at offset 0".
When thinking is disabled (``chat_template_kwargs={"thinking": False}`` or
``{"enable_thinking": False}``, i.e. instruct mode) the parser returns every
delta as normal content; there is simply no think channel to extract.
"""
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING
import regex as re
from transformers import PreTrainedTokenizerBase
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
def _match_at(haystack: Sequence[int], i: int, needle: Sequence[int]) -> bool:
"""Whether *needle* occurs in *haystack* starting at *i*.
Compares element by element rather than slicing: ``haystack`` is usually a
``ConstantList``, whose slices cost a Python ``__getitem__`` plus a list
allocation on every probe.
"""
return all(haystack[i + k] == needle[k] for k in range(len(needle)))
def _subseq_index(haystack: Sequence[int], needle: Sequence[int]) -> int:
"""Return start index of the last occurrence of needle in haystack, or -1."""
n = len(needle)
if n == 0:
return -1
first = needle[0]
for i in range(len(haystack) - n, -1, -1):
if haystack[i] == first and _match_at(haystack, i, needle):
return i
return -1
def _newest_marker(haystack: Sequence[int], a: Sequence[int], b: Sequence[int]) -> int:
"""Report which of *a* / *b* occurs last in *haystack*.
Returns 0 if *a* is the newest marker, 1 if *b* is, -1 if neither occurs.
Equivalent to comparing two ``_subseq_index`` results, but a single backward
pass that stops at the first hit instead of walking to index 0 twice.
"""
if not a or not b:
return -1
a0, b0 = a[0], b[0]
for i in range(len(haystack) - min(len(a), len(b)), -1, -1):
head = haystack[i]
if head == a0 and i + len(a) <= len(haystack) and _match_at(haystack, i, a):
return 0
if head == b0 and i + len(b) <= len(haystack) and _match_at(haystack, i, b):
return 1
return -1
class KimiK3ReasoningParser(ReasoningParser):
"""Reasoning parser for the Kimi K3 (XTML) think channel."""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer)
if not self.model_tokenizer:
raise ValueError(
"The model tokenizer must be passed to the ReasoningParser "
"constructor during construction."
)
# thinking can be disabled via chat_template_kwargs -> identity fallthrough
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
thinking = chat_kwargs.get("thinking", None)
if thinking is None:
thinking = chat_kwargs.get("enable_thinking", True)
self._thinking_enabled = bool(thinking)
# XTML markers as literal strings (skip_special_tokens=False at serve time)
self._think_open = "<|open|>think<|sep|>"
self._think_close = "<|close|>think<|sep|>"
# Content-channel markers that must be stripped from the final output.
# The tool parser handles these when active, but when tool_choice is
# "none" (the default for requests without tools) the tool parser is
# bypassed and the reasoning parser must strip them itself.
self._response_open = "<|open|>response<|sep|>"
self._response_close = "<|close|>response<|sep|>"
self._message_close = "<|close|>message<|sep|>"
# Tolerant matchers: defense-in-depth against vLLM's added-token spacing
# ("<|open|> think <|sep|>"). The `\s*` is a no-op on clean input, so the
# normal path stays byte-exact; it only helps if some serving path leaves
# spaces_between_special_tokens on. See adjust_request for the real fix.
open_marker = r"<\|open\|>"
close_marker = r"<\|close\|>"
sep_marker = r"<\|sep\|>"
self._think_open_re = re.compile(open_marker + r"\s*think\s*" + sep_marker)
self._think_close_re = re.compile(close_marker + r"\s*think\s*" + sep_marker)
self._response_open_re = re.compile(
open_marker + r"\s*response\s*" + sep_marker
)
self._response_close_re = re.compile(
close_marker + r"\s*response\s*" + sep_marker
)
self._message_close_re = re.compile(
close_marker + r"\s*message\s*" + sep_marker
)
# marker token-id subsequences (each marker is 3 tokens)
self._think_open_ids = tokenizer.encode(
self._think_open, add_special_tokens=False
)
self._think_close_ids = tokenizer.encode(
self._think_close, add_special_tokens=False
)
self._response_open_ids = tokenizer.encode(
self._response_open, add_special_tokens=False
)
self._last_streaming_delta_token_ids: tuple[int, ...] | None = None
self._last_streaming_content_token_ids: list[int] | None = None
@property
def reasoning_start_str(self) -> str | None:
return self._think_open
@property
def reasoning_end_str(self) -> str | None:
return self._think_close
def adjust_request(
self,
request: "ChatCompletionRequest | ResponsesRequest",
) -> "ChatCompletionRequest | ResponsesRequest":
request.skip_special_tokens = False
if hasattr(request, "spaces_between_special_tokens"):
request.spaces_between_special_tokens = False
return request
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
if not self._thinking_enabled:
return True
# Reasoning has ended only if the *most recent* think block is closed:
# the last close marker must come after the last open marker. A plain
# "a close marker exists anywhere" check false-positives in multi-turn /
# agent continuations, where the chat template keeps a prior turn's
# think channel (with its <|close|>think<|sep|>) in the prompt while the
# current turn is still reasoning (its <|open|>think<|sep|> is the newest
# marker). A missing open marker (e.g. it was consumed as the generation
# prefix) means a close marker alone ends reasoning, which is what
# "close is the newest marker" already encodes.
return (
_newest_marker(input_ids, self._think_close_ids, self._think_open_ids) == 0
)
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
"""Reasoning-end check for a single decode step.
The engine calls this once per structured-output request per decode step
while the request is still inside the think channel, so it only has to
look at the tokens generated this step, plus ``len(marker) - 1`` tokens
of context in case a marker straddles the step boundary.
The inherited default re-runs the full-sequence ``is_reasoning_end``,
which makes the scheduler O(context) per request per step and starves the
GPU on long agentic contexts.
"""
if not self._thinking_enabled:
return True
delta = list(delta_ids)
if not delta:
return False
carry = max(len(self._think_close_ids), len(self._think_open_ids)) - 1
head = len(input_ids) - len(delta)
window = list(input_ids[max(0, head - carry) : head]) + delta
return _newest_marker(window, self._think_close_ids, self._think_open_ids) == 0
def _extract_content_ids(self, input_ids: list[int]) -> list[int]:
if not self._thinking_enabled:
return input_ids
idx = _subseq_index(input_ids, self._think_close_ids)
if idx == -1:
return [] # still reasoning
return input_ids[idx + len(self._think_close_ids) :]
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
cached_delta_ids = self._last_streaming_delta_token_ids
cached_content_ids = self._last_streaming_content_token_ids
self._last_streaming_delta_token_ids = None
self._last_streaming_content_token_ids = None
if cached_delta_ids == tuple(input_ids) and cached_content_ids is not None:
return cached_content_ids
return self._extract_content_ids(input_ids)
def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int:
if not self._thinking_enabled:
return 0
think_open = self._think_open_ids
think_close = self._think_close_ids
response_open = self._response_open_ids
first_ids = {m[0] for m in (think_open, think_close, response_open) if m}
n = len(token_ids)
count = 0
in_reasoning = True
seen_open = False
i = 0
while i < n:
head = token_ids[i]
if head in first_ids:
if i + len(think_open) <= n and _match_at(token_ids, i, think_open):
in_reasoning = True
seen_open = True
i += len(think_open)
continue
if i + len(think_close) <= n and _match_at(token_ids, i, think_close):
in_reasoning = False
i += len(think_close)
continue
if (
not seen_open
and i + len(response_open) <= n
and _match_at(token_ids, i, response_open)
):
in_reasoning = False
i += len(response_open)
continue
if in_reasoning:
count += 1
i += 1
return count
def _strip_content_wrapper(self, text: str) -> str:
"""Strip ``<|open|>response<|sep|>…<|close|>response<|sep|>`` wrapper and
``<|close|>message<|sep|>`` from *text*.
When Kimi K3 tool parsing is active it needs the raw XTML
``response`` + ``tools`` channels. Otherwise the reasoning parser cleans
up the response wrapper itself so API users do not see XTML markers.
"""
# Try structured unwrap first: extract body of response channel
m_ro = self._response_open_re.search(text)
m_rc = self._response_close_re.search(text, m_ro.end() if m_ro else 0)
if m_ro is not None and m_rc is not None:
text = text[m_ro.end() : m_rc.start()]
elif m_ro is not None:
# response opened but not closed (truncated)
text = text[m_ro.end() :]
else:
# No response wrapper — strip stray markers if present
text = self._response_open_re.sub("", text)
text = self._response_close_re.sub("", text)
text = self._message_close_re.sub("", text)
return text
@staticmethod
def _should_preserve_tool_channels(
request: "ChatCompletionRequest | ResponsesRequest",
) -> bool:
return bool(getattr(request, "tools", None)) and (
getattr(request, "tool_choice", None) != "none"
)
def _content_after_reasoning(
self,
text: str,
request: "ChatCompletionRequest | ResponsesRequest",
) -> str | None:
if self._should_preserve_tool_channels(request):
return text or None
return self._strip_content_wrapper(text) or None
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
"""Split full text into ``(reasoning, rest)`` for the non-streaming path.
Handles four shapes:
* response opener without think markers -> no think channel; all content
* open marker present -> reasoning starts after ``<|open|>think<|sep|>``
* open marker absent but a close marker exists (gen-prefix consumed
the open) -> reasoning starts at offset 0
* neither marker present -> truncated reasoning after a consumed
generation prefix
``rest`` is whatever follows the close marker, fed on to the tool parser.
"""
if not self._thinking_enabled:
return None, self._content_after_reasoning(model_output, request)
m_open = self._think_open_re.search(model_output)
# reasoning content begins right after think-open (or at start if the
# open marker was already consumed as a generation prefix)
content_start = m_open.end() if m_open is not None else 0
m_close = self._think_close_re.search(model_output, content_start)
if (
m_open is None
and m_close is None
and self._response_open_re.search(model_output) is not None
):
return None, self._content_after_reasoning(model_output, request)
if m_close is not None:
reasoning = model_output[content_start : m_close.start()]
rest = model_output[m_close.end() :]
return (reasoning or None, self._content_after_reasoning(rest, request))
# think not closed -> still reasoning, no content yet
return (model_output[content_start:] or None, None)
def _reasoning_text_ready_to_emit(self, text: str) -> str:
"""Return the reasoning prefix that is safe to stream now.
Work from accumulated text, not from the current delta alone. That turns
split-open and split-close handling into the same prefix-diff problem.
Example 1: split think-open marker.
chunks: ``<|open|>`` / ``think`` / ``<|sep|>reasoning``
current text after chunk 1: ``<|open|>`` -> emit ``""``
current text after chunk 2: ``<|open|>think`` -> emit ``""``
current text after chunk 3: ``<|open|>think<|sep|>reasoning``
-> emit ``reasoning``
Example 2: split think-close marker.
chunks: ``reasoning`` / ``<|close|>`` / ``think<|sep|>...``
after ``<|close|>``, the suffix is only a partial close marker, so the
sendable reasoning is still ``reasoning`` and the delta is empty. Once
``think<|sep|>`` arrives, the close branch hands the following response
or tools text to the downstream parser.
"""
m_open = self._think_open_re.search(text)
if m_open is not None:
text = text[m_open.end() :]
overlap = 0
for marker in (self._think_open, self._think_close):
max_check = min(len(marker) - 1, len(text))
for n in range(max_check, 0, -1):
if text.endswith(marker[:n]):
overlap = max(overlap, n)
break
return text[:-overlap] if overlap else text
def _content_ready_to_emit(self, text: str) -> str:
"""Return the content prefix that is safe to stream now.
Mirrors ``_reasoning_text_ready_to_emit`` but for the post-reasoning
content phase. Strips the ``<|open|>response<|sep|>`` prefix, holds back
any partial marker suffix, and removes complete
``<|close|>response<|sep|>`` / ``<|close|>message<|sep|>`` markers.
"""
# Strip response-open prefix
m_open = self._response_open_re.search(text)
if m_open is not None:
text = text[m_open.end() :]
# Remove complete close/message markers
text = self._response_close_re.sub("", text)
text = self._message_close_re.sub("", text)
# Hold back partial markers at the end
overlap = 0
for marker in (
self._response_open,
self._response_close,
self._message_close,
):
max_check = min(len(marker) - 1, len(text))
for n in range(max_check, 0, -1):
if text.endswith(marker[:n]):
overlap = max(overlap, n)
break
return text[:-overlap] if overlap else text
def strip_content_streaming(
self,
previous_text: str,
current_text: str,
) -> DeltaMessage | None:
"""Strip XTML content wrappers from streaming deltas after reasoning.
Called by KimiK3Parser when no tool parser is configured, so the
reasoning parser handles ``<|open|>response<|sep|>`` /
``<|close|>response<|sep|>`` / ``<|close|>message<|sep|>`` stripping itself.
Works from accumulated text (``previous_text`` / ``current_text``
already contain only post-reasoning content).
"""
current_safe = self._content_ready_to_emit(current_text)
previous_safe = self._content_ready_to_emit(previous_text)
if current_safe.startswith(previous_safe):
delta = current_safe[len(previous_safe) :]
else:
delta = current_safe
return DeltaMessage(content=delta) if delta else None
def extract_reasoning_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],
) -> DeltaMessage | None:
self._last_streaming_delta_token_ids = None
self._last_streaming_content_token_ids = None
if not self._thinking_enabled:
return DeltaMessage(content=delta_text)
# reasoning already ended -> downstream content
if self._think_close_re.search(previous_text):
return DeltaMessage(content=delta_text)
# the close marker completes within this delta's accumulated text:
# split the buffer at the close marker into reasoning vs trailing content.
m_close = self._think_close_re.search(current_text)
if m_close is not None:
self._last_streaming_delta_token_ids = tuple(delta_token_ids)
self._last_streaming_content_token_ids = self._extract_content_ids(
list(current_token_ids)
)
m_open = self._think_open_re.search(current_text)
r_start = m_open.end() if m_open is not None else 0
reasoning = current_text[r_start : m_close.start()]
already_sent = self._reasoning_text_ready_to_emit(previous_text)
if reasoning.startswith(already_sent):
reasoning_delta = reasoning[len(already_sent) :]
else:
reasoning_delta = reasoning
content = current_text[m_close.end() :]
return DeltaMessage(
reasoning=reasoning_delta or None,
content=content or None,
)
current_reasoning = self._reasoning_text_ready_to_emit(current_text)
previous_reasoning = self._reasoning_text_ready_to_emit(previous_text)
if current_reasoning.startswith(previous_reasoning):
reasoning_delta = current_reasoning[len(previous_reasoning) :]
else:
reasoning_delta = current_reasoning
if not reasoning_delta:
return None
return DeltaMessage(reasoning=reasoning_delta)
# Backward-compatible aliases for existing unit tests and downstream users
# that still call the pre-split method names.
extract_reasoning_content = extract_reasoning
extract_reasoning_content_streaming = extract_reasoning_streaming
-6
View File
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.ling3 import Ling3ParserReasoningAdapter
__all__ = ["Ling3ParserReasoningAdapter"]
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import MiMoParserReasoningAdapter
__all__ = ["MiMoParserReasoningAdapter"]
@@ -1,16 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.adapters import ParserEngineReasoningAdapter
from vllm.parser.minicpmv import MiniCPMVParser
class MiniCPMVParserReasoningAdapter(ParserEngineReasoningAdapter):
# Reasoning-only on purpose: this family registers no tool parser, because
# MiniCPM-V emits the Qwen3-Coder XML syntax verbatim and `qwen3_coder`
# already covers it. ``make_adapters`` only builds reasoning/tool pairs, so
# the two halves are declared explicitly here.
_parser_engine_cls = MiniCPMVParser
__all__ = ["MiniCPMVParserReasoningAdapter"]
@@ -1,61 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Sequence
from typing import TYPE_CHECKING
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.parser.engine.registered_adapters import MinimaxM2ParserReasoningAdapter
from vllm.reasoning.abs_reasoning_parsers import ReasoningParser
from vllm.tokenizers import TokenizerLike
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class MiniMaxM2ReasoningParser(MinimaxM2ParserReasoningAdapter): # type: ignore[valid-type, misc]
"""Reasoning parser for MiniMax M2 model.
MiniMax M2 models don't generate <think> start token, only </think> end
token. All content before </think> is reasoning, content after is the
actual response.
"""
class MiniMaxM2AppendThinkReasoningParser(ReasoningParser):
"""Reasoning parser for MiniMax M2 model."""
def __init__(self, tokenizer: TokenizerLike, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
self.end_token_id = self.vocab.get("</think>")
self.start_token_id = self.vocab.get("<think>")
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
end_token_id = self.end_token_id
start_token_id = self.start_token_id
for input_id in reversed(input_ids):
if input_id in (end_token_id, start_token_id):
return input_id == end_token_id
return False
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
return input_ids
def extract_reasoning_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],
) -> DeltaMessage | None:
if len(previous_token_ids) == 0:
delta_text = "<think>" + delta_text
return DeltaMessage(content=delta_text)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
return None, "<think>" + model_output
@@ -1,320 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class MiniMaxM3ReasoningParser(BaseThinkingReasoningParser):
"""Reasoning parser for MiniMax M3 explicit thinking blocks.
MiniMax M3 emits reasoning as:
<mm:think>reasoning text</mm:think>assistant content
The M3 tokenizer exposes both markers as complete vocabulary entries, but
generated marker text may be tokenized into smaller pieces. The streaming
parser therefore uses text markers for extraction instead of relying on the
single vocabulary IDs. The chat template may also prefill the start marker
when ``thinking_mode="enabled"``, so generated text can begin directly
inside a reasoning block without emitting ``<mm:think>`` again.
"""
@property
def start_token(self) -> str:
return "<mm:think>"
@property
def end_token(self) -> str:
return "</mm:think>"
def __init__(self, tokenizer, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
self._start_token_ids = self._encode_marker(self.start_token)
self._end_token_ids = self._encode_marker(self.end_token)
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
self._initial_in_reasoning = chat_kwargs.get("thinking_mode") == "enabled"
self._reasoning_ended_streaming = False
self._reasoning_active_streaming = self._initial_in_reasoning
self._pending_marker_streaming = False
self._last_streaming_delta_token_ids: tuple[int, ...] | None = None
self._last_streaming_content_token_ids: list[int] | None = None
def _encode_text(self, text: str) -> list[int]:
try:
return list(self.model_tokenizer.encode(text, add_special_tokens=False))
except TypeError:
return list(self.model_tokenizer.encode(text))
def _encode_marker(self, marker: str) -> tuple[int, ...]:
return tuple(self._encode_text(marker))
def _decode_text(self, token_ids: Sequence[int]) -> str:
try:
return self.model_tokenizer.decode(
list(token_ids), skip_special_tokens=False
)
except TypeError:
return self.model_tokenizer.decode(list(token_ids))
def _content_suffix_token_ids(
self,
delta_text: str,
delta_token_ids: Sequence[int],
content: str | None,
) -> list[int]:
if content is None:
return []
if content == delta_text:
return list(delta_token_ids)
if delta_text.endswith(content):
prefix_text = delta_text[: len(delta_text) - len(content)]
for index in range(len(delta_token_ids) + 1):
if self._decode_text(delta_token_ids[:index]) == prefix_text:
return list(delta_token_ids[index:])
return self._encode_text(content)
@staticmethod
def _contains_token_sequence(
token_ids: Sequence[int], marker_ids: Sequence[int]
) -> bool:
if not marker_ids or len(marker_ids) > len(token_ids):
return False
marker_len = len(marker_ids)
return any(
tuple(token_ids[i : i + marker_len]) == tuple(marker_ids)
for i in range(len(token_ids) - marker_len + 1)
)
@staticmethod
def _rfind_token_sequence(
token_ids: Sequence[int], marker_ids: Sequence[int]
) -> int:
if not marker_ids or len(marker_ids) > len(token_ids):
return -1
marker_len = len(marker_ids)
for i in range(len(token_ids) - marker_len, -1, -1):
if tuple(token_ids[i : i + marker_len]) == tuple(marker_ids):
return i
return -1
@staticmethod
def _ends_with_token_sequence_prefix(
token_ids: Sequence[int], marker_ids: Sequence[int]
) -> bool:
if not marker_ids:
return False
max_len = min(len(token_ids), len(marker_ids) - 1)
for prefix_len in range(max_len, 0, -1):
if tuple(token_ids[-prefix_len:]) == tuple(marker_ids[:prefix_len]):
return True
return False
@staticmethod
def _strip_partial_marker_suffix(text: str, marker: str) -> str:
max_len = min(len(text), len(marker) - 1)
for suffix_len in range(max_len, 0, -1):
if marker.startswith(text[-suffix_len:]):
return text[:-suffix_len]
return text
@staticmethod
def _visible_delta(previous: str | None, current: str | None) -> str | None:
if not current:
return None
if not previous:
return current
if current.startswith(previous):
delta = current[len(previous) :]
return delta or None
return current
def _visible_segments(self, text: str) -> tuple[str | None, str | None]:
if not text:
return None, None
if not self._initial_in_reasoning:
if self.end_token.startswith(text) and len(text) < len(self.end_token):
return None, None
if text.startswith(self.end_token):
text = text[len(self.end_token) :]
if not text:
return None, None
if self._initial_in_reasoning and self.start_token not in text:
reasoning, end, content = text.partition(self.end_token)
if end:
return reasoning or None, content or None
reasoning = self._strip_partial_marker_suffix(reasoning, self.end_token)
return reasoning or None, None
if self.start_token not in text:
content = self._strip_partial_marker_suffix(text, self.start_token)
return None, content or None
content_before, _, after_start = text.partition(self.start_token)
reasoning, end, content_after = after_start.partition(self.end_token)
if end:
return reasoning or None, (content_before + content_after) or None
reasoning = self._strip_partial_marker_suffix(reasoning, self.end_token)
return reasoning or None, content_before or None
def extract_reasoning(
self,
model_output: str,
request: "ChatCompletionRequest | ResponsesRequest",
) -> tuple[str | None, str | None]:
# MiniMax M3 can start a response with a stray closer. Drop that first
# token only; later unmatched closers stay visible as content.
if not self._initial_in_reasoning and model_output.startswith(self.end_token):
content = model_output[len(self.end_token) :]
return None, content or None
if self._initial_in_reasoning and self.start_token not in model_output:
reasoning, end, content = model_output.partition(self.end_token)
if not end:
return model_output, None
return reasoning, content or None
if self.start_token not in model_output:
return None, model_output
content_before, _, after_start = model_output.partition(self.start_token)
reasoning, end, content_after = after_start.partition(self.end_token)
if not end:
return reasoning, content_before or None
return reasoning, (content_before + content_after) or None
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
if self._reasoning_ended_streaming:
return True
if self._reasoning_active_streaming or self._pending_marker_streaming:
return False
delta_ids = tuple(delta_ids)
if self._contains_token_sequence(delta_ids, self._end_token_ids):
return True
if self._contains_token_sequence(input_ids, self._end_token_ids):
return True
if self._initial_in_reasoning:
return False
if self._ends_with_token_sequence_prefix(input_ids, self._start_token_ids):
return False
if self._ends_with_token_sequence_prefix(input_ids, self._end_token_ids):
return False
if not self._contains_token_sequence(input_ids, self._start_token_ids):
return bool(input_ids)
return False
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
if (
self._last_streaming_delta_token_ids == tuple(input_ids)
and self._last_streaming_content_token_ids is not None
):
content_ids = self._last_streaming_content_token_ids
self._last_streaming_delta_token_ids = None
self._last_streaming_content_token_ids = None
return list(content_ids)
end_index = self._rfind_token_sequence(input_ids, self._end_token_ids)
if end_index >= 0:
return input_ids[end_index + len(self._end_token_ids) :]
has_start = self._contains_token_sequence(input_ids, self._start_token_ids)
if self._initial_in_reasoning and not has_start:
return []
if not has_start:
return input_ids
return []
def extract_reasoning_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],
) -> DeltaMessage | None:
if not delta_text:
return None
if not previous_text:
self._reasoning_ended_streaming = False
self._reasoning_active_streaming = self._initial_in_reasoning
self._pending_marker_streaming = False
self._last_streaming_delta_token_ids = None
self._last_streaming_content_token_ids = None
previous_reasoning, previous_content = self._visible_segments(previous_text)
current_reasoning, current_content = self._visible_segments(current_text)
if self.end_token in current_text or current_content is not None:
self._reasoning_ended_streaming = True
self._reasoning_active_streaming = False
self._pending_marker_streaming = False
else:
self._last_streaming_delta_token_ids = None
self._last_streaming_content_token_ids = None
self._reasoning_active_streaming = (
self._initial_in_reasoning
or self.start_token in current_text
or current_reasoning is not None
)
self._pending_marker_streaming = not self._reasoning_active_streaming and (
self.start_token.startswith(current_text)
or self.end_token.startswith(current_text)
)
reasoning = self._visible_delta(previous_reasoning, current_reasoning)
content = self._visible_delta(previous_content, current_content)
if self._reasoning_ended_streaming:
self._last_streaming_delta_token_ids = tuple(delta_token_ids)
self._last_streaming_content_token_ids = self._content_suffix_token_ids(
delta_text, delta_token_ids, content
)
if reasoning is None and content is None:
return None
return DeltaMessage(reasoning=reasoning, content=content)
def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int:
count = 0
depth = 1 if self._initial_in_reasoning else 0
i = 0
while i < len(token_ids):
if tuple(token_ids[i : i + len(self._start_token_ids)]) == (
self._start_token_ids
):
depth += 1
i += len(self._start_token_ids)
continue
if tuple(token_ids[i : i + len(self._end_token_ids)]) == (
self._end_token_ids
):
if depth > 0:
depth -= 1
i += len(self._end_token_ids)
continue
if depth > 0:
count += 1
i += 1
return count
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
start_index = self._rfind_token_sequence(input_ids, self._start_token_ids)
end_index = self._rfind_token_sequence(input_ids, self._end_token_ids)
if end_index < 0:
return False
if start_index < 0:
return True
return end_index > start_index
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import MistralParserReasoningAdapter
__all__ = ["MistralParserReasoningAdapter"]
@@ -1,327 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Reasoning-content parser for MuseGlimmer.
Port of the ``reasoning_content`` rule from the HuggingFace MuseGlimmer
``MUSE_GLIMMER_RESPONSE_SCHEMA`` (synced with internal master). MuseGlimmer emits
chain-of-thought in ``to=self`` channels delimited by ``<|message|>`` ... ``<|eom|>``:
to=self<|message|>...reasoning...<|eom|>
A turn may contain several ``to=self`` blocks interleaved with tool calls, and a
tool call or final answer follows in its own channel.
Because MuseGlimmer's framing markers (``<|message|>``, ``<|eom|>``) are not guaranteed
to be single vocab tokens across every checkpoint's tokenizer, this parser works
on the decoded text with regexes rather than the single start/end-token base class.
Usage: ``--reasoning-parser muse_glimmer``
"""
from __future__ import annotations
from collections.abc import Iterable, Sequence
import regex as re
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
from vllm.reasoning.abs_reasoning_parsers import ReasoningParser
_EOM = "<|eom|>"
_EOT = "<|eot|>"
_FUNCTION_CALLS_OPEN = "<atem:function_calls>"
_REASONING_OPEN = "to=self<|message|>"
_ASSISTANT_TURN_OPEN = "<|start|>assistant"
# A channel header: ``to=<recipient><|message|>`` where recipient is ``self``
# (reasoning), ``user`` (final answer) or ``<tool>[.<fn>]`` (tool call).
_CHANNEL_HEADER_RE = re.compile(r"to=(?P<recipient>[^\s<]+)<\|message\|>")
_HEADER_PAT = r"to=[^\s<]+<\|message\|>"
# Collapse the gap between reasoning blocks so multiple to=self spans join.
_COLLAPSE_RE = re.compile(
r"<\|eom\|>(?:(?!to=self<\|message\|>).)*?to=self<\|message\|>", re.DOTALL
)
_REASONING_RE = re.compile(r"to=self<\|message\|>(.*?)<\|eom\|>", re.DOTALL)
_CONTENT_RE = re.compile(
r"to=user<\|message\|>(.*?)(?=<\|eot\|>|<\|eom\|>|$)", re.DOTALL
)
# Strip a CLOSED reasoning span (header .. <|eom|>).
_STRIP_REASONING_RE = re.compile(
r"(?:<\|start\|>assistant\s*)?to=self<\|message\|>.*?<\|eom\|>", re.DOTALL
)
# An UNTERMINATED trailing reasoning span. The model sometimes leaves the
# analysis channel WITHOUT emitting <|eom|>, writing a bare
# ``to=<tool><|message|>`` header instead (observed deterministically for a call
# with EMPTY arguments on a tool that has optional parameters; reproduced on
# other engines too, so it is a model-side defect, not engine-specific).
#
# These two patterns MUST therefore stop at the next channel header rather than
# running to end-of-text. An unbounded ``...$`` version consumes the real tool
# call along with the reasoning: `is_reasoning_end` then never fires, the parser
# never leaves the reasoning phase, the tool parser is never invoked, and the
# entire generation is dropped (empty reasoning, empty content, no tool call).
_STRIP_OPEN_REASONING_RE = re.compile(
r"(?:<\|start\|>assistant\s*)?to=self<\|message\|>"
r"(?:(?!<\|eom\|>)(?!" + _HEADER_PAT + r").)*"
r"(?=" + _HEADER_PAT + r"|$)",
re.DOTALL,
)
_OPEN_REASONING_RE = re.compile(
r"to=self<\|message\|>((?:(?!<\|eom\|>)(?!" + _HEADER_PAT + r").)*)"
r"(?=" + _HEADER_PAT + r"|$)",
re.DOTALL,
)
# Markers whose PREFIX could appear at the tail of an OPEN (still-streaming) body.
_HOLDBACK_MARKERS = (_EOM, _EOT, "<|start|>", "<|message|>")
# A trailing fragment that could still grow into a channel header (" t", " to",
# " to=", " to=skill"). Without this the recipient name leaks into reasoning and
# then has to be un-emitted once ``<|message|>`` arrives.
_OPEN_TAIL_HEADER_RE = re.compile(r"[\s](?:t|to|to=[^\s<]*)$")
def _current_assistant_turn(text: str) -> str:
"""Return only the text generated in the current assistant turn.
``is_reasoning_end`` is evaluated on the PROMPT token-ids at stream start,
and an MuseGlimmer prompt legitimately contains ATEM markers (``render_tool_defs``
writes a literal ``<atem:function_calls>`` example into the system message,
and prior assistant turns may carry real tool calls). Anchoring on the last
channel-open keeps prompt text from deciding the phase.
"""
idx = text.rfind(_ASSISTANT_TURN_OPEN)
return text[idx + len(_ASSISTANT_TURN_OPEN) :] if idx != -1 else text
def _trim_open_body(body: str) -> str:
"""Hold back any tail of a still-growing body that could still be framing.
Iterated to a fixpoint because the two cases compose: `" to=skill<"` needs
the partial-marker trim (``<``) before the partial-header trim can see
`" to=skill"`. Trimming only once leaks the recipient name as reasoning.
"""
while True:
trimmed = body
for marker in _HOLDBACK_MARKERS:
for k in range(min(len(marker) - 1, len(trimmed)), 0, -1):
if trimmed.endswith(marker[:k]):
trimmed = trimmed[:-k]
break
else:
continue
break
header_tail = _OPEN_TAIL_HEADER_RE.search(trimmed)
if header_tail is not None:
trimmed = trimmed[: header_tail.start()]
if trimmed == body:
return body
body = trimmed
class MuseGlimmerReasoningParser(ReasoningParser):
def __init__(self, tokenizer, *args, **kwargs) -> None:
super().__init__(tokenizer, *args, **kwargs)
# Cursors over what was ACTUALLY emitted. Diffing a freshly reclassified
# `previous_text` is unsafe: a classified body legitimately shrinks when
# a partial header becomes recognisable, and diffing against the shrunken
# value re-emits text that already went out.
self._emitted_reasoning: str = ""
self._emitted_content: str = ""
self._tool_handoff_done: bool = False
def adjust_request(
self, request: ChatCompletionRequest | ResponsesRequest
) -> ChatCompletionRequest | ResponsesRequest:
"""Preserve MuseGlimmer's ATEM framing tokens in the decoded output.
vLLM's serving default is ``skip_special_tokens=True``, which strips
``<|start|>`` / ``<|message|>`` / ``<|eom|>`` / ``<|eot|>`` before the
parsers run, collapsing reasoning into content and breaking channel
scoping. Unlike the base tool-parser hook we do NOT touch
``structured_outputs`` -- MuseGlimmer emits native ATEM, not JSON.
"""
request.skip_special_tokens = False
return request
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
"""Whether the model has left reasoning and opened a TOOL channel.
A ``to=user`` answer is NOT a reason to leave the reasoning phase -- this
parser surfaces that content itself. Only a real tool channel switches
the ``DelegatingParser`` phase machine over to the tool parser.
Both closed and unterminated reasoning spans are stripped before the
check, so an ``<atem:invoke>`` the model merely echoes inside its CoT
never flips the phase.
"""
try:
text = self.model_tokenizer.decode(input_ids)
except Exception:
return False
remainder = self._tool_channel_remainder(text)
return _FUNCTION_CALLS_OPEN in remainder or "<atem:invoke" in remainder
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
return self.is_reasoning_end(list(input_ids))
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
# Content-id slicing is unreliable for multi-token markers; the serving
# path uses extract_reasoning() for the final split.
return []
@classmethod
def _scoped_turn(cls, text: str) -> str:
"""Current assistant turn with reasoning spans removed."""
scoped = _current_assistant_turn(text)
scoped = _STRIP_REASONING_RE.sub("", scoped)
return _STRIP_OPEN_REASONING_RE.sub("", scoped)
@classmethod
def _tool_channel_remainder(cls, text: str) -> str:
"""Text from the first tool-channel header onward, framing INCLUDED.
``DelegatingParser.parse_delta`` rebuilds ``current_text`` from whatever
this parser returns as ``.content`` on the transition delta and commits
it; anything not returned is destroyed. It must start AT the
``to=<name><|message|>`` header -- handing over the text after the header
loses the recipient, and the tool parser then sees a bare ``<|message|>``,
classifies it as the content channel, and leaks the ATEM markup.
"""
scoped = cls._scoped_turn(text)
for match in _CHANNEL_HEADER_RE.finditer(scoped):
if match.group("recipient") not in ("self", "user"):
return scoped[match.start() :]
return ""
@staticmethod
def _classify_bodies(text: str) -> tuple[str, str]:
"""Split ``text`` into (reasoning_body, content_body), channel-aware.
Framing markers and tool channels contribute nothing -- the tool parser
owns those. A body ends at ``<|eom|>`` / ``<|eot|>``, at the next channel
header, or at end-of-text (an OPEN body, which is held back).
"""
reasoning_parts: list[str] = []
content_parts: list[str] = []
pos = 0
n = len(text)
while pos < n:
match = _CHANNEL_HEADER_RE.search(text, pos)
if not match:
break
recipient = match.group("recipient")
body_start = match.end()
eom = text.find(_EOM, body_start)
eot = text.find(_EOT, body_start)
terminators = [p for p in (eom, eot) if p != -1]
next_header = _CHANNEL_HEADER_RE.search(text, body_start)
if next_header is not None:
terminators.append(next_header.start())
body_end = min(terminators) if terminators else n
body = text[body_start:body_end]
if not terminators:
body = _trim_open_body(body)
if recipient == "self":
reasoning_parts.append(body)
elif (
# Never surface tool XML echoed into a user channel.
recipient == "user"
and _FUNCTION_CALLS_OPEN not in body
and "<atem:invoke" not in body
):
content_parts.append(body)
if terminators and body_end in (eom, eot):
pos = body_end + len(_EOM if body_end == eom else _EOT)
else:
pos = body_end
return "".join(reasoning_parts), "".join(content_parts)
def get_streaming_fallback_content(
self,
previous_text: str,
request: ChatCompletionRequest | ResponsesRequest,
) -> str | None:
"""Promote un-surfaced content when the stream ends mid-reasoning.
``DelegatingParser.finalize_generation`` calls this when
``reasoning_ended`` is still False. Returns only the channel-classified
``to=user`` body, and only the portion not already streamed.
"""
_, content_body = self._classify_bodies(previous_text)
remainder = content_body[len(self._emitted_content) :]
return remainder or None
def extract_reasoning(
self,
model_output: str,
request: ChatCompletionRequest | ResponsesRequest,
) -> tuple[str | None, str | None]:
collapsed = _COLLAPSE_RE.sub("\n", model_output)
matches = _REASONING_RE.findall(collapsed)
reasoning = "\n".join(matches) if matches else None
# Truncation fallback: generation stopped inside a to=self block, so
# there is no closing <|eom|>. Bounded at the next channel header so a
# real tool call that follows a header-less channel switch is not
# absorbed into the reasoning field.
open_match = _OPEN_REASONING_RE.search(model_output)
if open_match and open_match.group(1):
partial = open_match.group(1)
reasoning = f"{reasoning}\n{partial}" if reasoning else partial
# Content is everything that is not a reasoning block. In a
# reasoning+tool-call turn there is no to=user answer, but the tool
# channels MUST be forwarded -- the unified parser runs the tool parser
# on this returned `content`, not on the original model_output.
remainder = _STRIP_REASONING_RE.sub("", model_output)
remainder = _STRIP_OPEN_REASONING_RE.sub("", remainder)
if "<atem:invoke" in remainder or _FUNCTION_CALLS_OPEN in remainder:
return reasoning, (remainder or None)
content_match = _CONTENT_RE.search(model_output)
if content_match:
content = content_match.group(1) or None
elif _REASONING_OPEN in model_output:
content = None
else:
content = model_output or None
reasoning = None
return reasoning, content
def extract_reasoning_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],
) -> DeltaMessage | None:
"""Channel-aware streaming split of reasoning vs content.
Classifies the full ``current_text`` and emits only what has not been
emitted yet, so no framing token is ever surfaced and a delta straddling
a channel boundary only contributes the portion inside a real body.
"""
curr_reason, curr_content = self._classify_bodies(current_text)
reasoning_delta = ""
if curr_reason.startswith(self._emitted_reasoning) and len(curr_reason) > len(
self._emitted_reasoning
):
reasoning_delta = curr_reason[len(self._emitted_reasoning) :]
self._emitted_reasoning = curr_reason
content_delta = ""
if curr_content.startswith(self._emitted_content) and len(curr_content) > len(
self._emitted_content
):
content_delta = curr_content[len(self._emitted_content) :]
self._emitted_content = curr_content
# Hand the tool channel to the tool parser exactly once, starting at its
# header. parse_delta discards anything not returned here.
#
# This MUST fire on the same delta where is_reasoning_end() flips, i.e.
# only once the tool channel actually contains ATEM. Emitting it earlier
# -- when only the bare `to=<name><|message|>` header has arrived -- keeps
# the parser in the reasoning phase, so parse_delta never replaces this
# DeltaMessage with the tool parser's and the header is delivered to the
# client as visible content.
handoff = ""
if not self._tool_handoff_done:
remainder = self._tool_channel_remainder(current_text)
if _FUNCTION_CALLS_OPEN in remainder or "<atem:invoke" in remainder:
handoff = remainder
self._tool_handoff_done = True
if handoff:
return DeltaMessage(reasoning=reasoning_delta or None, content=handoff)
if reasoning_delta and content_delta:
return DeltaMessage(reasoning=reasoning_delta, content=content_delta)
if reasoning_delta:
return DeltaMessage(reasoning=reasoning_delta)
if content_delta:
return DeltaMessage(content=content_delta)
return None
@@ -1,8 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import (
NemotronV3ParserReasoningAdapter,
)
__all__ = ["NemotronV3ParserReasoningAdapter"]
-317
View File
@@ -1,317 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import dataclasses as dt
import enum
from collections.abc import Sequence
from typing import TYPE_CHECKING
import regex as re
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
from vllm.tokenizers import TokenizerLike
class Olmo3ReasoningState(enum.Enum):
REASONING = 1
CONTENT = 2
@dt.dataclass(frozen=True)
class Indices:
start: int
end: int
def __len__(self):
return self.end - self.start
def string_overlap(a: str, b: str) -> tuple[Indices | None, Indices | None]:
"""Find the longest overlap where the end of string a matches the start
of string b.
Args:
a: First string
b: Second string
Returns:
Tuple of IndicesTuples representing the overlapping portions in each
string, or a tuple of None if no overlap exists
"""
# swap so a is always the shorter string
a, b, swap = (a, b, False) if len(a) < len(b) else (b, a, True)
# first check: is a fully contained in b?
if a in b:
ind_a = Indices(0, len(a))
ind_b = Indices(b.index(a), b.index(a) + len(a))
return (ind_b, ind_a) if swap else (ind_a, ind_b)
# second check: does the end of a overlap with the
# beginning of b?
for i in range(len(a) - 1, 0, -1):
if a[-i:] == b[:i]:
ind_a = Indices(len(a) - i, len(a))
ind_b = Indices(0, i)
return (ind_b, ind_a) if swap else (ind_a, ind_b)
# third check: does the beginning of a overlap with
# the end of b?
for i in range(len(a) - 1, 0, -1):
if b[-i:] == a[:i]:
ind_a = Indices(0, i)
ind_b = Indices(len(b) - i, len(b))
return (ind_b, ind_a) if swap else (ind_a, ind_b)
return None, None
@dt.dataclass
class Olmo3ReasoningBuffer:
think_start: str = "<think>"
think_end: str = "</think>"
buffer: str = ""
# we start in reasoning state to support cases where we hardcode
# <think> as the start of the reasoning block.
# In those cases, the only token we will see is </think>, which
# is when we switch to content state.
state: Olmo3ReasoningState = Olmo3ReasoningState.REASONING
def process_buffer(self) -> DeltaMessage | None:
start_think_idx = self.buffer.find(self.think_start)
if start_think_idx >= 0:
self.state = Olmo3ReasoningState.REASONING
pretext, self.buffer = (
self.buffer[:start_think_idx],
self.buffer[start_think_idx + len(self.think_start) :],
)
if start_think_idx > 0:
# this covers the case there's content before
# the start of the reasoning block
return DeltaMessage(content=pretext)
end_think_idx = self.buffer.rfind(self.think_end)
if end_think_idx >= 0:
self.state = Olmo3ReasoningState.CONTENT
pretext, self.buffer = (
self.buffer[:end_think_idx],
self.buffer[end_think_idx + len(self.think_end) :],
)
if end_think_idx > 0:
# this covers the case there's content before
# the end of the reasoning block
return DeltaMessage(reasoning=pretext)
if self.state == Olmo3ReasoningState.REASONING:
# we are inside reasoning block, return and empty
# the text buffer
(
text_buffer,
self.buffer,
) = self.buffer, ""
return DeltaMessage(reasoning=text_buffer)
if self.state == Olmo3ReasoningState.CONTENT:
# we are outside reasoning block, return and empty
# the text buffer
(
text_buffer,
self.buffer,
) = self.buffer, ""
return DeltaMessage(content=text_buffer)
# nothing to return unless we are in reasoning or content state
return None
def __len__(self):
# is the length of the text buffer
return len(self.buffer)
def add_text(self, delta_text: str) -> DeltaMessage | None:
# we start by adding the delta text to the buffer
self.buffer += delta_text
# setting this to empty before starting
delta_message: DeltaMessage | None = None
# we start by computing the overlap between the delta_text
# and start/end of think tokens.
_, overlap_think_start = string_overlap(delta_text, self.think_start)
_, overlap_think_end = string_overlap(delta_text, self.think_end)
partial_overlap_start = overlap_think_start is not None and len(
overlap_think_start
) < len(self.think_start)
partial_overlap_end = overlap_think_end is not None and len(
overlap_think_end
) < len(self.think_end)
if (
partial_overlap_start
and self.think_start in self.buffer
and not partial_overlap_end
):
# we can only process the buffer if partial overlap
# is the last part of think token (thus causing
# text_buffer to contain the start of think token)
# and there are no partial overlaps with end think
delta_message = self.process_buffer()
elif partial_overlap_end and self.think_end in self.buffer:
# same as before (partial overlap only allowed)
# if the buffer contains the end think token,
# but we don't have to check for partial overlap
# with start think token because they are handled
# by the previous condition
delta_message = self.process_buffer()
elif partial_overlap_start or partial_overlap_end:
# in general, if there are overlaps, we don't
# process the buffer because we want to wait until
# the think token is fully completed.
return None
else:
# we process the buffer as normal
delta_message = self.process_buffer()
return delta_message
class Olmo3ReasoningParser(ReasoningParser):
"""Reasoning parser for Olmo 3 model.
Olmo3ReasoningParser
This class implements a reasoning parser specifically designed for the
Olmo 3 family of models. Olmo 3 models do not use special tokens to
indicate reasoning; rather, reasoning trace is wrapped in `<think>` and
`</think>`, which are tokenized using standard vocabulary entries.
Because of this, the parser operates in string space, accumulating the
characters in a buffer until it sees `<think>` or `</think>`. tokens
to switch modes.
Key Features:
- For non-stream output, Recognizes and extracts reasoning (text
bracketed by `<think>` and `</think>`) and content (everything
after the first `</think>`).
- For stream process, it uses a buffer to accumulate delta text,
and output progressive delta messages as soon as thinking starts
or ends.
- For reliability, some Olmo 3 models may hardcode the first
`<think>` token is the input text (similar to Deepseek R1,
or reasoning-only Qwen models). To support such variants, the
parser can optionally work in cases where the first `<think>`
token is missing from generation.
"""
think_start: str = r"<think>"
think_end: str = r"</think>"
# </think> is split in 3 by the pre-tokenizer, first split can be tokenized
# with an optional leading space, so there are 2 possible tokenizations
think_end_first_split: list[str] = [r"Ġ</", r"</"]
think_end_rest_split: list[str] = [r"think", r">"]
# notice that the first think is optional; this allows template to
# work in cases when we hardcode a <think> at the beginning of the
# reasoning template.
reasoning_regex: re.Pattern = re.compile(
rf"^(?:{think_start})?(?P<reasoning>.*?)"
rf"{think_end}(?P<content>.*)$",
re.DOTALL,
)
def __init__(self, tokenizer: "TokenizerLike", *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
self.buffer = Olmo3ReasoningBuffer(
think_start=self.think_start, think_end=self.think_end
)
self.think_end_first_token_ids: list[int] = [
self.vocab[token] for token in self.think_end_first_split
]
self.think_end_rest_token_ids: list[int] = [
self.vocab[token] for token in self.think_end_rest_split
]
@property
def reasoning_start_str(self) -> str:
return self.think_start
@property
def reasoning_end_str(self) -> str:
return self.think_end
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
rest_ids = self.think_end_rest_token_ids
rest_len = len(rest_ids)
for i in range(len(input_ids) - rest_len, -1, -1):
if (
list(input_ids[i + 1 : i + 1 + rest_len]) == rest_ids
and input_ids[i] in self.think_end_first_token_ids
):
return True
return False
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
# for Olmo 3 streaming reason parsing, the stream parse
# will call first, and the same token will be called in
# is_reasoning_end and extract_content_ids
# this id is not part of content, so just return [] here.
return []
def extract_reasoning(
self,
model_output: str,
request: "ChatCompletionRequest | ResponsesRequest",
) -> tuple[str | None, str | None]:
"""Extract the reasoning content & content sections, respectively.
If the sequence doesn't match what we expect, i.e., the model generates
something else, all content is considered non-reasoning content.
Args:
model_output: Output of the model to be parsed.
request: Request being
processed.
Returns:
tuple[Optional[str], Optional[str]]: Tuple pair containing the
reasoning content and non-reasoning content.
"""
re_match = self.reasoning_regex.match(model_output)
if re_match:
reasoning = re_match.group("reasoning") or None
content = re_match.group("content") or None
return reasoning, content
# no reasoning content
return None, model_output
def extract_reasoning_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],
) -> DeltaMessage | None:
"""Extract content using token ID sequence state machine."""
delta_message = self.buffer.add_text(delta_text)
if delta_message is None and self.buffer.think_end in self.buffer.buffer:
# this is a bit hacky, but, because of how the buffer is
# constructed, if the last delta_text contains characters that
# marks the end of thinking tokens, then messages in the buffer
# would never be processed because we get no other turn. To get
# around that, we check if the text buffer contains the end of
# thinking tokens, and, if so, we reprocess the buffer again.
delta_message = self.buffer.process_buffer()
return delta_message
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import Plamo3ParserReasoningAdapter
__all__ = ["Plamo3ParserReasoningAdapter"]
@@ -1,71 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Laguna reasoning parser.
``DeepSeekV3ReasoningParser.is_reasoning_end`` walks the entire
token sequence backwards and returns ``True`` on the first ``</think>`` it
sees. When called on ``prompt_token_ids`` that mistakes any stray
``</think>`` in conversation history, few-shot examples or tool descriptions
for a template-injected "thinking already ended" marker. In the streaming
path (see ``vllm/entrypoints/openai/chat_completion/serving.py``,
``prompt_is_reasoning_end_arr``) that false positive short-circuits the
reasoning parser for the whole response, so any ``<think>...</think>`` the
model emits itself ends up in the content field instead of the reasoning
field.
As we have more flexible templates, we instead scope
the backward search to the current assistant turn: the
walk terminates as soon as we hit the ``<assistant>`` start-of-message
token. A ``</think>`` in a prior user turn or few-shot example is no longer
visible.
"""
from collections.abc import Sequence
from transformers import PreTrainedTokenizerBase
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
from vllm.reasoning.deepseek_v3_reasoning_parser import DeepSeekV3ReasoningParser
from vllm.reasoning.identity_reasoning_parser import IdentityReasoningParser
class PoolsideV1ReasoningParser(DeepSeekV3ReasoningParser):
"""Drop-in replacement for ``deepseek_v3`` that tolerates ``</think>``
tokens appearing anywhere in the prompt other than the generation prefix.
"""
_start_of_assistant_message = "<assistant>"
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
if self._start_of_assistant_message not in self.vocab:
raise ValueError(
f"Tokenizer must contain {self._start_of_assistant_message!r} token"
)
self._start_of_assistant_message_token_id = self.vocab[
self._start_of_assistant_message
]
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
# IdentityReasoningParser always returns True: no reasoning to parse.
if isinstance(self._parser, IdentityReasoningParser):
return True
assert isinstance(self._parser, DeepSeekR1ReasoningParser)
for tok_id in reversed(input_ids):
# <think>: reasoning is not yet ended.
if tok_id == self._parser.start_token_id:
return False
# </think>: reasoning has ended.
if tok_id == self._parser.end_token_id:
return True
# <assistant>: reached the start of the current assistant turn
# without seeing either marker. Anything further back belongs to
# the prior conversation and should be ignored.
if tok_id == self._start_of_assistant_message_token_id:
return False
return False
__all__ = ["PoolsideV1ReasoningParser"]
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.response_template import ResponseTemplateReasoningParser
__all__ = ["ResponseTemplateReasoningParser"]
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import SeedOssParserReasoningAdapter
__all__ = ["SeedOssParserReasoningAdapter"]
-128
View File
@@ -1,128 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from itertools import islice
from typing import TYPE_CHECKING
import regex as re
from transformers import PreTrainedTokenizerBase
from vllm.entrypoints.generate.base.protocol import DeltaMessage
from vllm.reasoning import ReasoningParser
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
class Step3ReasoningParser(ReasoningParser):
"""Reasoning parser for Step3 model.
The Step3 model uses </think> token to denote the end of reasoning
text. This parser extracts all content before </think> as reasoning content.
"""
def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs):
super().__init__(tokenizer, *args, **kwargs)
self.think_start_token = "<think>"
self.think_end_token = "</think>"
self.reasoning_regex = re.compile(rf"(.*?){self.think_end_token}", re.DOTALL)
if not self.model_tokenizer:
raise ValueError(
"The model tokenizer must be passed to the ReasoningParser "
"constructor during construction."
)
think_end_token_id = self.vocab.get(self.think_end_token)
if think_end_token_id is None:
raise RuntimeError(
"Step3 reasoning parser could not locate think end "
"token in the tokenizer!"
)
self.think_end_token_id: int = think_end_token_id
@property
def reasoning_start_str(self) -> str:
return self.think_start_token
@property
def reasoning_end_str(self) -> str:
return self.think_end_token
def extract_reasoning_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],
) -> DeltaMessage | None:
"""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":
- 'abc' goes to reasoning
- 'xyz' goes to content
"""
# Skip single special token
if len(delta_token_ids) == 1 and delta_token_ids[0] == self.think_end_token_id:
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)
reasoning = delta_text[:end_index]
content = delta_text[end_index + len(self.think_end_token) :]
return DeltaMessage(
reasoning=reasoning,
content=content if content else None,
)
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
return DeltaMessage(reasoning=delta_text)
def extract_reasoning(
self, model_output: str, request: "ChatCompletionRequest | ResponsesRequest"
) -> tuple[str | None, str | None]:
# 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)
reasoning = model_output[:end_index]
# Content after </think> token
content = model_output[end_index + len(self.think_end_token) :] or None
return reasoning, content
def is_reasoning_end(self, input_ids: Sequence[int]) -> bool:
return self.think_end_token_id in input_ids
def is_reasoning_end_streaming(
self, input_ids: Sequence[int], delta_ids: Iterable[int]
) -> bool:
end_token_id = self.think_end_token_id
return end_token_id in delta_ids
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
if self.think_end_token_id not in islice(
input_ids, 0, max(0, len(input_ids) - 1)
):
return []
else:
return input_ids[input_ids.index(self.think_end_token_id) + 1 :]
def count_reasoning_tokens(self, token_ids: Sequence[int]) -> int:
if self.think_end_token_id not in token_ids:
return len(token_ids)
return list(token_ids).index(self.think_end_token_id)
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import Step3p5ParserReasoningAdapter
__all__ = ["Step3p5ParserReasoningAdapter"]