[Model][Frontend] Support DeepSeek-V4.1-Flash in Rust and Python frontends (#56208)

Signed-off-by: Bugen Zhao <i@bugenzhao.com>
Co-authored-by: Isotr0py <Isotr0py@outlook.com>
This commit is contained in:
Bugen Zhao
2026-09-10 01:15:06 -07:00
committed by GitHub
co-authored by Isotr0py
parent 9521c60bdc
commit b47b01cf33
52 changed files with 2986 additions and 113 deletions
+3
View File
@@ -152,6 +152,7 @@ class ModelConfig:
- "mistral" will always use the tokenizer from `mistral_common`.
- "deepseek_v32" will always use the tokenizer from `deepseek_v32`.
- "deepseek_v4" will always use the tokenizer from `deepseek_v4`.
- "deepseek_v41" will use the DeepSeek V4.1 prompt encoder.
- "kimi_k3" will always use the "hf" tokenizer but render chat prompts
with Kimi K3's Python XTML encoding instead of a Jinja template.
- "cohere" uses the standard HF tokenizer but renders the chat template
@@ -705,6 +706,8 @@ class ModelConfig:
"DeepseekV4ForConditionalGeneration",
):
self.tokenizer_mode = "deepseek_v4"
elif arch == "DeepseekV41ForCausalLM":
self.tokenizer_mode = "deepseek_v41"
elif arch in ("InklingForCausalLM", "InklingForConditionalGeneration"):
self.tokenizer_mode = "inkling"
@@ -0,0 +1,463 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Multimodal preprocessing for the DeepSeek-V4.1 vision variant.
The image transform and image-span construction are ported from the
official repository's ``image_processor.py`` so that token counts bit-match
the reference. Each ``<|deepseek_image|>`` placeholder in the prompt expands
to ``[IMAGE_START] + ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h +
[IMAGE_END]``; every span position carries ``image_token_id`` (129264) in
``input_ids`` and the roles ride along in a per-image ``types`` tensor
(the reference's out-of-band ``token_types``). IMAGE slots receive aligner
rows in reading order; the delimiters take the learned ``image_start`` /
``image_newline`` / ``image_end`` vectors.
One vLLM-side deviation from the reference token stream: a leading
compressor-alignment pad (``COMPRESS_PAD_TO - 1 - start % COMPRESS_PAD_TO``
positions, so the span always starts at the same compressor phase) is
prepended when the block is spliced into the final prompt. Pad positions
borrow the reserved in-vocab token ``<|place_holder_mm_span_0436|>`` so
they stay distinguishable from real span positions; they embed as the
plain image token (v4.1 has no ``image_pad`` vector) and are routed and
engram-deadened like image tokens.
"""
import math
from collections.abc import Mapping, Sequence
from typing import Any, cast
import numpy as np
import torch
from PIL import Image, ImageOps
from transformers import BatchFeature
from typing_extensions import assert_never
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.multimodal.inputs import MultiModalFieldConfig, MultiModalKwargsItems
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
from vllm.multimodal.processing import (
BaseDummyInputsBuilder,
BaseMultiModalProcessor,
BaseProcessingInfo,
PromptReplacement,
PromptUpdate,
PromptUpdateDetails,
)
from vllm.multimodal.processing.processor import (
MultiModalPromptUpdates,
MultiModalPromptUpdatesApplyResult,
PlaceholderFeaturesInfo,
UpdateMode,
_plan_prompt_updates,
)
from vllm.transformers_utils.configs.deepseek_v41 import DeepseekV41Config
IMAGE_START, IMAGE, IMAGE_NEW_LINE, IMAGE_END = range(4)
# Image spans are padded so they always start at the same compressor group
# phase; v4.1 uses ratio-2 compressors (v4.0 used 4).
COMPRESS_PAD_TO = 2
IMAGE_PLACEHOLDER = "<|deepseek_image|>"
# The checkpoint tokenizer's id for IMAGE_PLACEHOLDER (the config's
# ``image_token_id``). Every image-span position carries this id, exactly
# like the reference; the MoE router detects image tokens as the range
# [IMAGE_SENTINEL_BASE_ID, IMAGE_SENTINEL_BASE_ID + 5), which also covers
# IMAGE_PAD_ID below.
IMAGE_SENTINEL_BASE_ID = 129264
# Leading compressor-alignment pads borrow this reserved in-vocab token
# (``<|place_holder_mm_span_0436|>``) so they can be told apart from real
# span positions when the per-position role is decided from token ids.
IMAGE_PAD_ID = 129265
IMAGE_PAD_TOKEN_NAME = "<|place_holder_mm_span_0436|>"
def image_sentinel_mask(token_ids: torch.Tensor) -> torch.Tensor:
"""Boolean mask for image-span positions (span tokens and align pads)."""
return (token_ids == IMAGE_SENTINEL_BASE_ID) | (token_ids == IMAGE_PAD_ID)
def validate_image_sentinel_ids(tokenizer) -> None:
"""Check the image/pad token ids against the tokenizer."""
image_id = tokenizer.convert_tokens_to_ids(IMAGE_PLACEHOLDER)
if image_id != IMAGE_SENTINEL_BASE_ID:
raise ValueError(
f"Image placeholder {IMAGE_PLACEHOLDER!r} has id {image_id}, "
f"expected {IMAGE_SENTINEL_BASE_ID} (the config's "
"image_token_id); the DeepSeek-V4.1 vision path keys image "
"routing and engram masking off this id."
)
pad_id = tokenizer.convert_tokens_to_ids(IMAGE_PAD_TOKEN_NAME)
if pad_id != IMAGE_PAD_ID:
raise ValueError(
f"Image pad token {IMAGE_PAD_TOKEN_NAME!r} has id {pad_id}, "
f"expected {IMAGE_PAD_ID}; the DeepSeek-V4.1 vision path "
"borrows this reserved id for compressor-alignment pads."
)
def llm_grid(best_height, best_width, patch_size, downsample_ratio):
"""Token grid the aligner produces from a patch grid of this pixel size."""
return (
math.ceil((best_height // patch_size) / downsample_ratio),
math.ceil((best_width // patch_size) / downsample_ratio),
)
def num_image_tokens(n_llm_h: int, n_llm_w: int) -> int:
return n_llm_h * (n_llm_w + 1) + 2
def solve_resize_ratio(height, width, patch_size, downsample_ratio, max_n_token):
"""Largest aspect-preserving pixel size whose token grid still fits in
max_n_token. Returns (best_height, best_width)."""
r = height / width
max_w_float = math.sqrt((max_n_token - 2) / r + 0.25) - 0.5
max_h_float = max_w_float * r
cell = patch_size * downsample_ratio
if max_w_float < 1.0: # very tall: collapse to a single column
return (max_n_token - 2) // 2 * cell, cell
if max_h_float < 1.0: # very wide: collapse to a single row
return cell, (max_n_token - 3) * cell
beta = min(
math.floor(max_w_float) * cell / width,
math.floor(max_h_float) * cell / height,
)
return (
math.floor(height * beta / patch_size) * patch_size,
math.floor(width * beta / patch_size) * patch_size,
)
def safe_resize(
height, width, best_height, best_width, patch_size, downsample_ratio, max_n_token
):
"""Shrink the pixel size until the image costs at most max_n_token LLM
tokens (minus the reservation for the compressor-alignment pad)."""
max_n_token -= COMPRESS_PAD_TO - 1
n_llm_h, n_llm_w = llm_grid(best_height, best_width, patch_size, downsample_ratio)
if num_image_tokens(n_llm_h, n_llm_w) > max_n_token:
best_height, best_width = solve_resize_ratio(
height, width, patch_size, downsample_ratio, max_n_token
)
n_llm_h, n_llm_w = llm_grid(
best_height, best_width, patch_size, downsample_ratio
)
assert num_image_tokens(n_llm_h, n_llm_w) <= max_n_token
return n_llm_h, n_llm_w, best_height, best_width
def load_image(
image: Image.Image,
*,
patch_size: int,
downsample_ratio: int,
max_n_token: int,
min_pixels: int,
max_wh_ratio: float | None,
):
"""Transform one PIL image into ViT patches.
Same math as the reference ``load_image``, except the image is already
decoded (vLLM supplies PIL images instead of a record dict).
"""
p = patch_size
image = image.convert("RGB")
width, height = image.size
if max_wh_ratio is not None and width > height * max_wh_ratio:
width = height * max_wh_ratio
if 0 < width * height < min_pixels:
ratio = (min_pixels / (width * height)) ** 0.5
width = int(width * ratio)
height = int(height * ratio)
best_width = math.ceil(width / p) * p
best_height = math.ceil(height / p) * p
n_llm_h, n_llm_w, best_height, best_width = safe_resize(
height, width, best_height, best_width, p, downsample_ratio, max_n_token
)
n_vit_h, n_vit_w = best_height // p, best_width // p
if max_wh_ratio is not None and image.width >= max_wh_ratio * image.height:
image = image.resize((best_width, best_height))
else:
image = ImageOps.pad(image, (best_width, best_height), color=(127, 127, 127))
x = torch.from_numpy(np.asarray(image, dtype=np.float32)).permute(2, 0, 1) / 255
x = ((x - 0.5) / 0.5).to(torch.bfloat16)
patches = (
x.reshape(3, n_vit_h, p, n_vit_w, p)
.permute(1, 3, 0, 2, 4)
.reshape(n_vit_h * n_vit_w, 3, p, p)
)
return patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w
def image_token_types(n_llm_h: int, n_llm_w: int) -> torch.Tensor:
"""Reading-order span layout: one IMAGE_NEW_LINE per row."""
types = [IMAGE_START]
types += ([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h
types.append(IMAGE_END)
return torch.tensor(types, dtype=torch.int64)
class DeepseekV4VLImageProcessor:
"""Per-image transform (the PIL-input equivalent of the reference
``load_image``)."""
def __init__(self, config: DeepseekV41Config) -> None:
super().__init__()
self.patch_size = config.vision_patch_size
self.downsample_ratio = config.vision_downsample_ratio
self.max_n_token = config.vision_max_n_token
self.min_pixels = config.vision_min_pixels
self.max_wh_ratio = config.vision_max_wh_ratio
def __call__(self, image: Image.Image):
return load_image(
image,
patch_size=self.patch_size,
downsample_ratio=self.downsample_ratio,
max_n_token=self.max_n_token,
min_pixels=self.min_pixels,
max_wh_ratio=self.max_wh_ratio,
)
class DeepseekV4VLProcessor:
"""Minimal stand-in for the HF processor of DeepSeek-V4.1 vision models.
The official repository ships image preprocessing as plain functions in
``image_processor.py`` (no ``auto_map`` processor), so this class wraps
their ports directly and the model loads without ``--trust-remote-code``.
``__call__`` returns a ``BatchFeature`` with one entry per image
(flattened across images):
- ``patches``: ``(sum(n_vit_h * n_vit_w), 3, p, p)`` bf16 ViT patches.
- ``vit_grid``: ``(num_images, 2)`` int64 ``[n_vit_h, n_vit_w]``.
- ``llm_grid``: ``(num_images, 2)`` int64 ``[n_llm_h, n_llm_w]``.
- ``types``: concatenated per-image pad-free span roles
(IMAGE_START/IMAGE/IMAGE_NEW_LINE/IMAGE_END); every span position
carries ``image_token_id`` in the prompt's token ids.
"""
def __init__(self, config: DeepseekV41Config) -> None:
super().__init__()
self.config = config
self.image_processor = DeepseekV4VLImageProcessor(config)
def __call__(
self,
text: str | None = None,
images: Sequence[Image.Image] | None = None,
return_tensors: str | None = None,
**kwargs: Any,
) -> BatchFeature:
patches_list = []
vit_grid = []
llm_grid_list = []
types_list = []
for image in images or []:
patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w = self.image_processor(image)
patches_list.append(patches)
vit_grid.append((n_vit_h, n_vit_w))
llm_grid_list.append((n_llm_h, n_llm_w))
types_list.append(image_token_types(n_llm_h, n_llm_w))
if not patches_list:
return BatchFeature({})
return BatchFeature(
{
"patches": torch.cat(patches_list),
"vit_grid": torch.tensor(vit_grid, dtype=torch.int64),
"llm_grid": torch.tensor(llm_grid_list, dtype=torch.int64),
"types": torch.cat(types_list),
}
)
class DeepseekV4VLProcessingInfo(BaseProcessingInfo):
def get_hf_config(self) -> DeepseekV41Config:
return self.ctx.get_hf_config(DeepseekV41Config)
def get_hf_processor(self, **kwargs: object) -> DeepseekV4VLProcessor:
if kwargs:
raise ValueError(f"Unexpected processor kwargs: {sorted(kwargs)}")
return DeepseekV4VLProcessor(self.get_hf_config())
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
return {"image": None}
def get_mm_max_tokens_per_item(
self,
seq_len: int,
mm_counts: Mapping[str, int],
) -> Mapping[str, int]:
# ``safe_resize`` reserves COMPRESS_PAD_TO - 1 tokens of
# vision_max_n_token for the compressor-alignment pad, so the full
# image span is bounded by vision_max_n_token; the margin is kept
# in case that reservation changes.
return {
"image": self.get_hf_config().vision_max_n_token + COMPRESS_PAD_TO - 1,
}
def get_image_placeholder_token_id(self) -> int:
token_id = self.get_tokenizer().convert_tokens_to_ids(IMAGE_PLACEHOLDER)
if token_id is None:
raise ValueError(f"Token not found in tokenizer: {IMAGE_PLACEHOLDER}")
return token_id
def get_image_size_with_most_features(self) -> ImageSize:
hf_config = self.get_hf_config()
patch_size = hf_config.vision_patch_size
downsample_ratio = hf_config.vision_downsample_ratio
# A square maximizes the ViT patch count (area) within the token
# budget; solve the budget-derived size directly to keep the dummy
# image small.
budget = hf_config.vision_max_n_token - (COMPRESS_PAD_TO - 1)
side = budget * patch_size * downsample_ratio
best_h, best_w = solve_resize_ratio(
side, side, patch_size, downsample_ratio, budget
)
return ImageSize(width=best_w, height=best_h)
class DeepseekV4VLDummyInputsBuilder(
BaseDummyInputsBuilder[DeepseekV4VLProcessingInfo]
):
def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
return IMAGE_PLACEHOLDER * mm_counts.get("image", 0)
def get_dummy_mm_data(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
) -> MultiModalDataDict:
size = self.info.get_image_size_with_most_features()
return {
"image": self._get_dummy_images(
width=size.width,
height=size.height,
num_images=mm_counts.get("image", 0),
overrides=cast(ImageDummyOptions | None, mm_options.get("image")),
),
}
class DeepseekV4VLMultiModalProcessor(
BaseMultiModalProcessor[DeepseekV4VLProcessingInfo]
):
def _get_mm_fields_config(
self,
hf_inputs: BatchFeature,
hf_processor_mm_kwargs: Mapping[str, object],
) -> Mapping[str, MultiModalFieldConfig]:
vit_grid = hf_inputs.get("vit_grid")
llm_grid = hf_inputs.get("llm_grid")
if vit_grid is None or llm_grid is None:
empty = torch.empty(0, dtype=torch.long)
patch_sizes = types_sizes = empty
else:
patch_sizes = vit_grid.prod(-1)
n_llm_h, n_llm_w = llm_grid[:, 0], llm_grid[:, 1]
types_sizes = n_llm_h * (n_llm_w + 1) + 2
return {
"patches": MultiModalFieldConfig.flat_from_sizes("image", patch_sizes),
"vit_grid": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
"llm_grid": MultiModalFieldConfig.batched("image", keep_on_cpu=True),
"types": MultiModalFieldConfig.flat_from_sizes(
"image", types_sizes, keep_on_cpu=True
),
}
def _get_prompt_updates(
self,
mm_items: MultiModalDataItems,
hf_processor_mm_kwargs: Mapping[str, object],
out_mm_kwargs: MultiModalKwargsItems,
) -> Sequence[PromptUpdate]:
image_token_id = self.info.get_image_placeholder_token_id()
validate_image_sentinel_ids(self.info.get_tokenizer())
def get_image_replacement(item_idx: int) -> PromptUpdateDetails:
types: torch.Tensor = out_mm_kwargs["image"][item_idx]["types"].data
# Every span position carries image_token_id; the roles live in
# ``types``. All of them are embed positions (delimiters get the
# learned vectors from embed_multimodal, not the embed table).
full = [image_token_id] * types.numel()
return PromptUpdateDetails.select_token_id(full, image_token_id)
return [
PromptReplacement(
modality="image",
target=[image_token_id],
replacement=get_image_replacement,
),
]
def _apply_token_matches_with_placeholders(
self,
token_ids: list[int],
mm_prompt_updates: MultiModalPromptUpdates,
) -> tuple[
list[int],
MultiModalPromptUpdatesApplyResult,
Mapping[str, list[PlaceholderFeaturesInfo]],
]:
# Same as the base implementation, except that each image block gets
# its compressor-alignment pad (``COMPRESS_PAD_TO - 1 - start %
# COMPRESS_PAD_TO`` IMAGE_PAD_ID tokens) prepended while splicing:
# the pad depends on the block's final position in the prompt, which
# is unknown when the (cacheable) prompt updates are built. Pad
# positions are not embed positions (their id differs from
# image_token_id), so ``is_embed`` stays aligned with the pad-free
# replacement content.
matched_updates, result = _plan_prompt_updates(token_ids, mm_prompt_updates)
placeholders: dict[str, list[PlaceholderFeaturesInfo]] = {
modality: [] for modality in mm_prompt_updates
}
new_token_ids = list[int]()
prev_end_idx = 0
for matched_update in matched_updates:
update = matched_update.update
match = matched_update.match
if update.mode == UpdateMode.INSERT:
end_idx_to_insert = match.end_idx
elif update.mode == UpdateMode.REPLACE:
end_idx_to_insert = match.start_idx
else:
assert_never(update.mode)
new_token_ids.extend(token_ids[prev_end_idx:end_idx_to_insert])
start_idx = len(new_token_ids)
tokens = list(update.content.full)
if tokens and update.modality == "image":
compress_pad = COMPRESS_PAD_TO - 1 - start_idx % COMPRESS_PAD_TO
tokens = [IMAGE_PAD_ID] * compress_pad + tokens
if tokens:
content_is_embed = update.content.is_embed
is_embed = (
content_is_embed(tokens) if content_is_embed is not None else None
)
placeholders[update.modality].append(
PlaceholderFeaturesInfo(
modality=update.modality,
item_idx=update.item_idx,
start_idx=start_idx,
tokens=tokens,
is_embed=is_embed,
)
)
new_token_ids.extend(tokens)
prev_end_idx = match.end_idx
new_token_ids.extend(token_ids[prev_end_idx:])
return new_token_ids, result, placeholders
+15 -5
View File
@@ -70,11 +70,17 @@ _PARTIAL_PARAM_RE = re.compile(
)
def _dsml_arg_converter(raw_args: str, partial: bool) -> str:
def _dsml_arg_converter(
raw_args: str,
partial: bool,
*,
param_re: re.Pattern = _PARAM_RE,
partial_param_re: re.Pattern = _PARTIAL_PARAM_RE,
) -> str:
params: dict[str, object] = {}
last_end = 0
for m in _PARAM_RE.finditer(raw_args):
for m in param_re.finditer(raw_args):
name, is_str, value = m.group(1), m.group(2), m.group(3)
if is_str == "true":
params[name] = value
@@ -86,7 +92,7 @@ def _dsml_arg_converter(raw_args: str, partial: bool) -> str:
last_end = m.end()
if partial:
pm = _PARTIAL_PARAM_RE.search(raw_args, last_end)
pm = partial_param_re.search(raw_args, last_end)
if pm:
name, is_str, value = pm.group(1), pm.group(2), pm.group(3)
if is_str == "true":
@@ -229,6 +235,8 @@ def deepseek_v4_config(thinking: bool = False) -> ParserEngineConfig:
class DeepSeekV4Parser(ParserEngine):
parser_config = staticmethod(deepseek_v4_config)
def __init__(
self,
tokenizer: TokenizerLike,
@@ -245,13 +253,15 @@ class DeepSeekV4Parser(ParserEngine):
super().__init__(
tokenizer,
tools,
parser_engine_config=deepseek_v4_config(thinking=thinking),
parser_engine_config=self.parser_config(thinking=thinking),
**kwargs,
)
self._arg_converter = self._convert_args
def _convert_args(self, raw_args: str, partial: bool) -> str:
result = _dsml_arg_converter(raw_args, partial)
converter = self.parser_engine_config.arg_converter
assert converter is not None
result = converter(raw_args, partial)
if not self._tools:
return result
func_name = next((s.name for s in self._tool_slots if s.args == raw_args), None)
+65
View File
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DeepSeek V4.1 reasoning and spaced DSML tool calls."""
import functools
from dataclasses import replace
import regex as re
from vllm.parser.deepseek_v4 import (
DeepSeekV4Parser,
_dsml_arg_converter,
deepseek_v4_config,
)
from vllm.parser.engine.parser_engine_config import ParserEngineConfig
DSML_TOOL_START = "<|DSML| calls>"
DSML_TOOL_END = "</|DSML| calls>"
DSML_INVOKE_PREFIX = '<|DSML| invoke name="'
DSML_INVOKE_END = "</|DSML| invoke>"
DSML_PARAM_START = "<|DSML| parameter"
DSML_PARAM_CLOSE = "</|DSML| parameter>"
_PARAM_RE = re.compile(
r'<|DSML| parameter\s+name="([^"]+)"\s+string="(true|false)">'
r"(.*?)"
r"(?:</|DSML| parameter>|(?=<|DSML| parameter\s+name=))",
re.DOTALL,
)
_PARTIAL_PARAM_RE = re.compile(
r'<|DSML| parameter\s+name="([^"]+)"\s+string="(true|false)">'
r"(.*)$",
re.DOTALL,
)
@functools.cache
def deepseek_v41_config(thinking: bool = False) -> ParserEngineConfig:
config = deepseek_v4_config(thinking=thinking)
terminal_overrides = {
"TOOL_START": DSML_TOOL_START,
"TOOL_END": DSML_TOOL_END,
"INVOKE_PREFIX": DSML_INVOKE_PREFIX,
"INVOKE_END": DSML_INVOKE_END,
"PARAM_START": DSML_PARAM_START,
"PARAM_CLOSE": DSML_PARAM_CLOSE,
}
return replace(
config,
name="deepseek_v41",
terminals={**config.terminals, **terminal_overrides},
token_id_terminals={
key: terminal_overrides.get(key, value)
for key, value in config.token_id_terminals.items()
},
arg_converter=functools.partial(
_dsml_arg_converter,
param_re=_PARAM_RE,
partial_param_re=_PARTIAL_PARAM_RE,
),
)
class DeepSeekV41Parser(DeepSeekV4Parser):
parser_config = staticmethod(deepseek_v41_config)
@@ -9,6 +9,7 @@ names so that :class:`ReasoningParserManager` and
from vllm.parser.deepseek_v4 import DeepSeekV4Parser
from vllm.parser.deepseek_v32 import DeepSeekV32Parser
from vllm.parser.deepseek_v41 import DeepSeekV41Parser
from vllm.parser.engine.adapters import make_adapters
from vllm.parser.gemma4 import Gemma4Parser
from vllm.parser.glm47_moe import Glm47MoeParser
@@ -30,6 +31,11 @@ from vllm.parser.seed_oss import SeedOssParser
DeepSeekV4ParserToolAdapter,
) = make_adapters(DeepSeekV4Parser)
(
DeepSeekV41ParserReasoningAdapter,
DeepSeekV41ParserToolAdapter,
) = make_adapters(DeepSeekV41Parser)
(
MinimaxM2ParserReasoningAdapter,
MinimaxM2ParserToolAdapter,
+4
View File
@@ -32,6 +32,10 @@ _REASONING_PARSERS_TO_REGISTER = {
"deepseek_v4_engine_reasoning_parser",
"DeepSeekV4ParserReasoningAdapter",
),
"deepseek_v41": (
"deepseek_v41_engine_reasoning_parser",
"DeepSeekV41ParserReasoningAdapter",
),
"poolside_v1": (
"poolside_v1_reasoning_parser",
"PoolsideV1ReasoningParser",
@@ -0,0 +1,6 @@
# 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
View File
@@ -23,6 +23,7 @@ _VLLM_RENDERERS = {
"cohere": ("cohere", "CohereRenderer"),
"deepseek_v32": ("deepseek_v32", "DeepseekV32Renderer"),
"deepseek_v4": ("deepseek_v4", "DeepseekV4Renderer"),
"deepseek_v41": ("deepseek_v4", "DeepseekV4Renderer"),
"hf": ("hf", "HfRenderer"),
"kimi_audio": ("hf", "HfRenderer"),
"kimi_k3": ("kimi_k3", "KimiK3Renderer"),
+121
View File
@@ -0,0 +1,121 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import copy
from typing import Any
from transformers import TokenizersBackend
from vllm.entrypoints.chat_utils import ChatCompletionMessageParam
from .deepseek_v41_encoding import (
IMAGE_PLACEHOLDER,
REASONING_EFFORT_MAPPINGS,
encode_messages,
)
from .hf import HfTokenizer, get_cached_tokenizer
from .protocol import TokenizerLike
def _normalize_messages(
messages: list[ChatCompletionMessageParam],
) -> list[dict[str, Any]]:
result = [dict(message) for message in copy.deepcopy(messages)]
for message in result:
role = message.get("role")
if role not in ("system", "developer", "user", "assistant", "tool"):
raise ValueError(f"Invalid role: {role}")
if "reasoning" in message:
message["reasoning_content"] = message["reasoning"]
content = message.get("content")
if isinstance(content, list):
parts = []
for block in content:
part_type = block.get("type")
if part_type == "text":
parts.append(block.get("text", ""))
elif part_type in ("image_url", "input_image", "image_pil"):
parts.append(IMAGE_PLACEHOLDER)
else:
raise ValueError(
"DeepSeek V4.1 supports text and image content only; "
f"got {part_type!r}"
)
message["content"] = "\n\n".join(parts)
return result
def get_deepseek_v41_tokenizer(tokenizer: HfTokenizer) -> HfTokenizer:
"""Wrap an HF tokenizer with the V4.1 prompt encoder."""
wrapped = copy.copy(tokenizer)
added_vocab = tokenizer.get_added_vocab()
class _DeepseekV41Tokenizer(tokenizer.__class__): # type: ignore
def apply_chat_template(
self,
messages: list[ChatCompletionMessageParam],
tools: list[dict[str, Any]] | None = None,
**kwargs,
) -> str | list[int]:
# The generic renderer's conversation has already flattened text
# parts with '\n'. V4.1 encodes the original messages with '\n\n'.
conversation = _normalize_messages(messages)
if tools:
system = next((m for m in conversation if m["role"] == "system"), None)
if system is None:
system = {"role": "system", "content": ""}
conversation.insert(0, system)
system["tools"] = tools
thinking = bool(kwargs.get("thinking") or kwargs.get("enable_thinking"))
if "thinking" not in kwargs and "enable_thinking" not in kwargs:
thinking = True
effort = kwargs.get("reasoning_effort")
if effort == "none":
thinking = False
effort = None
if effort is None:
effort = "high"
if not (
(type(effort) is int and 1 <= effort <= 100)
or (isinstance(effort, str) and effort in REASONING_EFFORT_MAPPINGS)
):
raise ValueError(
"DeepSeek V4.1 reasoning_effort must be low, high, xhigh, max, "
"or an integer within [1, 100] in chat_template_kwargs"
)
prompt = encode_messages(
conversation,
thinking_mode="thinking" if thinking else "chat",
drop_thinking=kwargs.get("drop_thinking", True),
reasoning_effort=effort,
)
if kwargs.get("tokenize", True):
tokenizer_kwargs = {
key: kwargs[key]
for key in ("truncation", "max_length")
if key in kwargs
}
return self.encode(prompt, add_special_tokens=False, **tokenizer_kwargs)
return prompt
def num_special_tokens_to_add(self) -> int:
return len(self.encode(""))
def get_added_vocab(self) -> dict[str, int]:
return added_vocab.copy()
def __reduce__(self):
return get_deepseek_v41_tokenizer, (tokenizer,)
_DeepseekV41Tokenizer.__name__ = f"DSV41{tokenizer.__class__.__name__}"
wrapped.__class__ = _DeepseekV41Tokenizer
return wrapped
class DeepseekV41Tokenizer(TokenizerLike):
@classmethod
def from_pretrained(cls, *args, **kwargs) -> HfTokenizer:
tokenizer = TokenizersBackend.from_pretrained(*args, **kwargs)
return get_cached_tokenizer(get_deepseek_v41_tokenizer(tokenizer))
+577
View File
@@ -0,0 +1,577 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa
"""Text encoding adapted from the DeepSeek V4.1 reference encoder.
Message normalization and serving controls live in deepseek_v41.py.
"""
import copy
import json
from typing import Any, Dict, List, Optional, Union
bos_token: str = "<|begin▁of▁sentence|>"
eos_token: str = "<|end▁of▁sentence|>"
thinking_start_token: str = "<think>"
thinking_end_token: str = "</think>"
dsml_token: str = "|DSML|"
USER_SP_TOKEN = "<|User|>"
ASSISTANT_SP_TOKEN = "<|Assistant|>"
LATEST_REMINDER_SP_TOKEN = "<|latest_reminder|>"
IMAGE_PLACEHOLDER = "<|deepseek_image|>"
DS_TASK_SP_TOKENS = {
"action": "<|action|>",
"query": "<|query|>",
"authority": "<|authority|>",
"domain": "<|domain|>",
"title": "<|title|>",
"read_url": "<|read_url|>",
}
VALID_TASKS = set(DS_TASK_SP_TOKENS.keys())
system_msg_template: str = "{content}"
user_msg_template: str = "{content}"
latest_reminder_msg_template: str = "{content}"
assistant_msg_template: str = "{reasoning}{content}{tool_calls}" + eos_token
assistant_msg_wo_eos_template: str = "{reasoning}{content}{tool_calls}"
thinking_template: str = "{reasoning_content}"
response_format_template: str = (
"## Response Format:\n\n"
"You MUST strictly adhere to the following schema to reply:\n{schema}"
)
tool_output_template: str = "<tool_result>{content}</tool_result>"
def to_json(value: Any) -> str:
"""Serialize a value to JSON string."""
try:
return json.dumps(value, ensure_ascii=False)
except:
return json.dumps(value, ensure_ascii=True)
def tools_from_openai_format(tools):
"""Extract function definitions from OpenAI-format tool list."""
return [tool["function"] for tool in tools]
def tool_calls_from_openai_format(tool_calls):
"""Convert OpenAI-format tool calls to internal format."""
return [
{
"name": tool_call["function"]["name"],
"arguments": tool_call["function"]["arguments"],
}
for tool_call in tool_calls
]
def merge_tool_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Merge tool messages into the preceding user message using content_blocks format.
DeepSeek-V4.1 does not have a standalone "tool" role; instead, tool results
are encoded as <tool_result> blocks within user messages.
"""
merged: List[Dict[str, Any]] = []
for msg in messages:
msg = copy.deepcopy(msg)
role = msg.get("role")
if role == "tool":
# Convert tool message to a user message with tool_result block
tool_block = {
"type": "tool_result",
"tool_use_id": msg.get("tool_call_id", ""),
"content": msg.get("content", ""),
}
# Merge into previous message if it's already a user (merged tool)
if (
merged
and merged[-1].get("role") == "user"
and "content_blocks" in merged[-1]
):
merged[-1]["content_blocks"].append(tool_block)
else:
merged.append(
{
"role": "user",
"content_blocks": [tool_block],
}
)
elif role == "user":
content_blocks = msg.get("content_blocks")
if content_blocks is None:
content_blocks = [{"type": "text", "text": msg.get("content", "")}]
if (
merged
and merged[-1].get("role") == "user"
and "content_blocks" in merged[-1]
and merged[-1].get("task") is None
):
merged[-1]["content_blocks"].extend(content_blocks)
else:
# Preserve structured content and all message-level metadata.
new_msg = msg
new_msg["content_blocks"] = content_blocks
merged.append(new_msg)
else:
merged.append(msg)
return merged
def sort_tool_results_by_call_order(
messages: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""
Sort tool_result blocks within user messages by the order of tool_calls
in the preceding assistant message.
"""
last_tool_call_order: Dict[str, int] = {}
for msg in messages:
role = msg.get("role")
if role == "assistant" and msg.get("tool_calls"):
last_tool_call_order = {}
for idx, tc in enumerate(msg["tool_calls"]):
tc_id = tc.get("id") or tc.get("function", {}).get("id", "")
if tc_id:
last_tool_call_order[tc_id] = idx
elif role == "user" and msg.get("content_blocks"):
tool_blocks = [
b for b in msg["content_blocks"] if b.get("type") == "tool_result"
]
if len(tool_blocks) > 1 and last_tool_call_order:
sorted_blocks = sorted(
tool_blocks,
key=lambda b: last_tool_call_order.get(b.get("tool_use_id", ""), 0),
)
sorted_idx = 0
new_blocks = []
for block in msg["content_blocks"]:
if block.get("type") == "tool_result":
new_blocks.append(sorted_blocks[sorted_idx])
sorted_idx += 1
else:
new_blocks.append(block)
msg["content_blocks"] = new_blocks
return messages
SYSTEM_SP_TOKEN = "<|System|>"
tool_calls_block_name: str = " calls"
tool_call_tag_name: str = " invoke"
tool_parameter_tag_name: str = " parameter"
tool_call_template: str = '<{dsml_token}{tool_call_tag_name} name="{name}">\n{arguments}\n</{dsml_token}{tool_call_tag_name}>'
tool_calls_template = (
"<{dsml_token}{tc_block_name}>\n{tool_calls}\n</{dsml_token}{tc_block_name}>"
)
REASONING_EFFORT_TEMPLATE = (
"Reasoning Effort: {budget} "
"(range 1-100, the higher the value, the more thorough the reasoning)\n\n"
)
REASONING_EFFORT_MAPPINGS: Dict[str, int] = {
"low": 25,
"high": 50,
"xhigh": 75,
"max": 100,
}
DEFAULT_REASONING_EFFORT = "high"
def render_reasoning_effort(
index: int,
thinking_mode: str,
effort: Union[str, int, None],
) -> str:
"""Render the V4.1 numeric reasoning effort prefix (thinking mode, index 0 only)."""
if effort is None:
effort = DEFAULT_REASONING_EFFORT
assert (
type(effort) is int and 1 <= effort <= 100
) or effort in REASONING_EFFORT_MAPPINGS, (
"Invalid reasoning effort for deepseek_v41: "
f"{effort}, should be int within [1,100] or {list(REASONING_EFFORT_MAPPINGS)}"
)
if type(effort) is str:
effort = REASONING_EFFORT_MAPPINGS[effort]
if index == 0 and thinking_mode == "thinking":
return REASONING_EFFORT_TEMPLATE.format(budget=effort)
return ""
TOOLS_TEMPLATE = """## Tools
You have access to a set of tools to help answer the user's question. You can invoke tools by writing a "<{dsml_token}{tc_block_name}>" block like the following:
<{dsml_token}{tc_block_name}>
<{dsml_token}{tool_call_tag_name} name="$TOOL_NAME">
<{dsml_token}{tool_parameter_tag_name} name="$PARAMETER_NAME" string="true|false">$PARAMETER_VALUE</{dsml_token}{tool_parameter_tag_name}>
...
</{dsml_token}{tool_call_tag_name}>
<{dsml_token}{tool_call_tag_name} name="$TOOL_NAME2">
...
</{dsml_token}{tool_call_tag_name}>
</{dsml_token}{tc_block_name}>
String parameters should be specified as is and set `string="true"`. For all other types (numbers, booleans, arrays, objects), pass the value in JSON format and set `string="false"`.
If thinking_mode is enabled (triggered by {thinking_start_token}), you MUST output your complete reasoning inside {thinking_start_token}...{thinking_end_token} BEFORE any tool calls or final response.
Otherwise, output directly after {thinking_end_token} with tool calls or final response.
### Available Tool Schemas
{tool_schemas}
You MUST strictly follow the above defined tool name and parameter schemas to invoke tool calls.
"""
def render_tools(tools: List[Dict[str, Union[str, Dict[str, Any]]]]) -> str:
"""Render tool schemas into the V4.1 system prompt format."""
tools_json = [to_json(t) for t in tools]
return TOOLS_TEMPLATE.format(
tool_schemas="\n".join(tools_json),
dsml_token=dsml_token,
tc_block_name=tool_calls_block_name,
tool_call_tag_name=tool_call_tag_name,
tool_parameter_tag_name=tool_parameter_tag_name,
thinking_start_token=thinking_start_token,
thinking_end_token=thinking_end_token,
)
def encode_arguments_to_dsml(tool_call: Dict[str, Any]) -> str:
"""Encode tool call arguments into V4.1 DSML parameter format."""
p_dsml_template = (
'<{dsml_token}{tool_parameter_tag_name} name="{key}" string="{is_str}">'
"{value}</{dsml_token}{tool_parameter_tag_name}>"
)
P_dsml_strs = []
arguments = tool_call["arguments"]
if not isinstance(arguments, dict):
# Tolerate JSON strings, including double-encoded ones.
for _ in range(2):
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except Exception:
break
else:
break
if not isinstance(arguments, dict):
arguments = {"arguments": tool_call["arguments"]}
for k, v in arguments.items():
P_dsml_strs.append(
p_dsml_template.format(
dsml_token=dsml_token,
tool_parameter_tag_name=tool_parameter_tag_name,
key=k,
is_str="true" if isinstance(v, str) else "false",
value=v if isinstance(v, str) else to_json(v),
)
)
return "\n".join(P_dsml_strs)
def find_last_user_index(messages: List[Dict[str, Any]]) -> int:
"""
Find the index of the last user/developer message.
V4.1 supports mid-conversation system messages, which count as user
messages for the purposes of the assistant generation header.
"""
last_user_index = -1
for idx in range(len(messages) - 1, -1, -1):
role = messages[idx].get("role")
if role in ["user", "developer"] or (role == "system" and idx > 0):
last_user_index = idx
break
return last_user_index
def render_message(
index: int,
messages: List[Dict[str, Any]],
thinking_mode: str,
drop_thinking: bool = True,
reasoning_effort: Union[str, int, None] = None,
) -> str:
"""
Render a single message at the given index into its V4.1 encoded string form.
"""
assert 0 <= index < len(messages)
assert thinking_mode in ["chat", "thinking"], (
f"Invalid thinking_mode `{thinking_mode}`"
)
msg = messages[index]
last_user_idx = find_last_user_index(messages)
role = msg.get("role")
content = msg.get("content")
tools = msg.get("tools")
response_format = msg.get("response_format")
tool_calls = msg.get("tool_calls")
reasoning_content = msg.get("reasoning_content")
wo_eos = msg.get("wo_eos", False)
if tools:
tools = tools_from_openai_format(tools)
if tool_calls:
tool_calls = tool_calls_from_openai_format(tool_calls)
# Reasoning effort prefix (thinking mode, index 0 only)
reasoning_effort_prompt = render_reasoning_effort(
index, thinking_mode, reasoning_effort
)
# System token leads the conversation when there is a reasoning effort prompt
# or the first message is a system message.
prompt = (
SYSTEM_SP_TOKEN
if index == 0 and (reasoning_effort_prompt or role == "system")
else ""
)
prompt += reasoning_effort_prompt
if role == "system":
if index > 0:
# Mid-conversation system message
prompt += SYSTEM_SP_TOKEN
prompt += system_msg_template.format(content=content or "")
if tools:
prompt += "\n\n" + render_tools(tools)
if response_format:
prompt += "\n\n" + response_format_template.format(
schema=to_json(response_format)
)
elif role == "developer":
assert content, f"Invalid message for role `{role}`: {msg}"
content_developer = USER_SP_TOKEN
content_developer += content
if tools:
content_developer += "\n\n" + render_tools(tools)
if response_format:
content_developer += "\n\n" + response_format_template.format(
schema=to_json(response_format)
)
prompt += user_msg_template.format(content=content_developer)
elif role == "user":
prompt += USER_SP_TOKEN
# Handle content blocks (tool results mixed with text)
content_blocks = msg.get("content_blocks")
if content_blocks:
parts = []
for block in content_blocks:
block_type = block.get("type")
if block_type == "text":
parts.append(block.get("text", ""))
elif block_type == "tool_result":
tool_content = block.get("content", "")
if isinstance(tool_content, list):
text_parts = []
for b in tool_content:
if b.get("type") == "text":
text_parts.append(b.get("text", ""))
else:
text_parts.append(f"[Unsupported {b.get('type')}]")
tool_content = "\n\n".join(text_parts)
parts.append(tool_output_template.format(content=tool_content))
else:
parts.append(f"[Unsupported {block_type}]")
prompt += "\n\n".join(parts)
else:
prompt += content or ""
elif role == "latest_reminder":
prompt += LATEST_REMINDER_SP_TOKEN + latest_reminder_msg_template.format(
content=content
)
elif role == "tool":
raise NotImplementedError(
"deepseek_v41 merges tool messages into user; please preprocess with merge_tool_messages()"
)
elif role == "assistant":
thinking_part = ""
tc_content = ""
if tool_calls:
tc_list = [
tool_call_template.format(
dsml_token=dsml_token,
tool_call_tag_name=tool_call_tag_name,
name=tc.get("name"),
arguments=encode_arguments_to_dsml(tc),
)
for tc in tool_calls
]
tc_content += "\n\n" + tool_calls_template.format(
dsml_token=dsml_token,
tool_calls="\n".join(tc_list),
tc_block_name=tool_calls_block_name,
)
summary_content = content or ""
rc = reasoning_content or ""
# Check if previous message has a task - if so, this is a task output (no thinking)
prev_has_task = index - 1 >= 0 and messages[index - 1].get("task") is not None
if thinking_mode == "thinking" and not prev_has_task:
if not drop_thinking or index > last_user_idx:
thinking_part = (
thinking_template.format(reasoning_content=rc) + thinking_end_token
)
else:
thinking_part = ""
if wo_eos:
prompt += assistant_msg_wo_eos_template.format(
reasoning=thinking_part,
content=summary_content,
tool_calls=tc_content,
)
else:
prompt += assistant_msg_template.format(
reasoning=thinking_part,
content=summary_content,
tool_calls=tc_content,
)
else:
raise NotImplementedError(f"Unknown role: {role}")
# Append transition tokens based on what follows
if index + 1 < len(messages) and messages[index + 1].get("role") not in [
"assistant",
"latest_reminder",
]:
return prompt
task = messages[index].get("task")
if task is not None:
# Task special token for internal classification tasks
assert task in VALID_TASKS, (
f"Invalid task: '{task}'. Valid tasks are: {list(VALID_TASKS)}"
)
task_sp_token = DS_TASK_SP_TOKENS[task]
if task != "action":
# Non-action tasks: append task sp token directly after the message
prompt += task_sp_token
else:
# Action task: append Assistant + thinking token + action sp token
prompt += ASSISTANT_SP_TOKEN
prompt += (
thinking_end_token
if thinking_mode != "thinking"
else thinking_start_token
)
prompt += task_sp_token
elif messages[index].get("role") in ["user", "developer"] or (
messages[index].get("role") == "system" and index > 0
):
# Normal generation: append Assistant + thinking token
# (mid-conversation system messages also trigger the assistant header)
prompt += ASSISTANT_SP_TOKEN
if not drop_thinking and thinking_mode == "thinking":
prompt += thinking_start_token
elif drop_thinking and thinking_mode == "thinking" and index >= last_user_idx:
prompt += thinking_start_token
else:
prompt += thinking_end_token
return prompt
def _drop_thinking_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Drop reasoning_content and non-essential messages before the last user message.
Same as V4, but uses the V4.1 last-user definition (mid systems count).
"""
last_user_idx = find_last_user_index(messages)
result = []
keep_roles = {"user", "system", "tool", "latest_reminder", "direct_search_results"}
for idx, msg in enumerate(messages):
role = msg.get("role")
if role in keep_roles or idx >= last_user_idx:
result.append(msg)
elif role == "assistant":
msg = copy.copy(msg)
msg.pop("reasoning_content", None)
result.append(msg)
# developer and other roles before last_user_idx are dropped
return result
def encode_messages(
messages: List[Dict[str, Any]],
thinking_mode: str,
context: Optional[List[Dict[str, Any]]] = None,
drop_thinking: bool = True,
add_default_bos_token: bool = True,
reasoning_effort: Union[str, int, None] = None,
) -> str:
"""Encode preprocessed (text-only) messages into the V4.1 prompt format."""
context = context if context else []
# Preprocess: merge tool messages and sort tool results
messages = merge_tool_messages(messages)
messages = sort_tool_results_by_call_order(context + messages)[len(context) :]
if context:
context = merge_tool_messages(context)
context = sort_tool_results_by_call_order(context)
full_messages = context + messages
prompt = bos_token if add_default_bos_token and len(context) == 0 else ""
# Resolve drop_thinking: if any message has tools defined, don't drop thinking
effective_drop_thinking = drop_thinking
if any(m.get("tools") for m in full_messages):
effective_drop_thinking = False
if thinking_mode == "thinking" and effective_drop_thinking:
full_messages = _drop_thinking_messages(full_messages)
num_to_render = len(full_messages) - len(_drop_thinking_messages(context))
context_len = len(full_messages) - num_to_render
else:
num_to_render = len(messages)
context_len = len(context)
for idx in range(num_to_render):
prompt += render_message(
idx + context_len,
full_messages,
thinking_mode=thinking_mode,
drop_thinking=effective_drop_thinking,
reasoning_effort=reasoning_effort,
)
return prompt
+1
View File
@@ -45,6 +45,7 @@ _VLLM_TOKENIZERS = {
"cohere": ("hf", "CachedHfTokenizer"),
"deepseek_v32": ("deepseek_v32", "DeepseekV32Tokenizer"),
"deepseek_v4": ("deepseek_v4", "DeepseekV4Tokenizer"),
"deepseek_v41": ("deepseek_v41", "DeepseekV41Tokenizer"),
"hf": ("hf", "CachedHfTokenizer"),
"kimi_audio": ("kimi_audio", "KimiAudioTokenizer"),
"kimi_k3": ("hf", "CachedHfTokenizer"),
+4
View File
@@ -42,6 +42,10 @@ _TOOL_PARSERS_TO_REGISTER = {
"deepseekv4_engine_tool_parser",
"DeepSeekV4EngineToolParser",
),
"deepseek_v41": (
"deepseekv41_engine_tool_parser",
"DeepSeekV41EngineToolParser",
),
"cohere_command3": (
"cohere_command_tool_parser",
"CohereCommand3ToolParser",
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import DeepSeekV41ParserToolAdapter
class DeepSeekV41EngineToolParser(DeepSeekV41ParserToolAdapter): # type: ignore[valid-type, misc]
structural_tag_model = "deepseek_v41"
+96 -1
View File
@@ -71,7 +71,9 @@ XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset(
"deepseek_v4",
}
)
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset({"hermes", "hy_v4", "kimi_k3"})
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset(
{"deepseek_v41", "hermes", "hy_v4", "kimi_k3"}
)
SUPPORTED_STRUCTURAL_TAG_MODELS = (
XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS | VLLM_BUILTIN_STRUCTURAL_TAG_MODELS
)
@@ -225,6 +227,99 @@ def get_function_parameters(function) -> dict[str, Any] | bool:
return function.parameters if function.parameters is not None else True
_V41_CALLS_START = "<|DSML| calls>"
_V41_CALLS_END = "</|DSML| calls>"
_V41_INVOKE_END = "</|DSML| invoke>"
_V41_PARAMETER_END = "</|DSML| parameter>"
@register_vllm_structural_tag("deepseek_v41")
def get_deepseek_v41_structural_tag(
tools: list[FunctionToolParam],
builtin_tools: list[BuiltinToolParam],
tool_choice: SimplifiedToolChoice,
reasoning: bool,
token_suffix: str = "",
) -> StructuralTag:
# Serving enables this visible-text grammar after the reasoning boundary.
del builtin_tools, reasoning, token_suffix
# TODO: lower parameter schemas into DSML constraints. This builder constrains
# tool names and DSML/value syntax only. Parameter names, presence, uniqueness
# and value schemas remain unconstrained, including for strict=true. The request
# layer still uses strict to decide whether auto tool choice activates a grammar.
parameter = TagFormat(
begin='<|DSML| parameter name="',
content=SequenceFormat(
elements=[
RegexFormat(pattern=r'[^"]+'),
ConstStringFormat(value='" string="'),
OrFormat(
elements=[
SequenceFormat(
elements=[
ConstStringFormat(value='true">'),
AnyTextFormat(
excludes=[
_V41_PARAMETER_END,
_V41_INVOKE_END,
_V41_CALLS_END,
]
),
]
),
SequenceFormat(
elements=[
ConstStringFormat(value='false">'),
JSONSchemaFormat(json_schema=True),
]
),
]
),
]
),
end=f"{_V41_PARAMETER_END}\n",
)
calls = TagsWithSeparatorFormat(
tags=[
TagFormat(
begin=f'<|DSML| invoke name="{tool.function.name}">\n',
content=StarFormat(content=parameter),
end=f"{_V41_INVOKE_END}\n",
)
for tool in tools
],
separator="",
at_least_one=True,
stop_after_first=tool_choice == "forced",
)
if tool_choice == "auto":
return StructuralTag(
format=TriggeredTagsFormat(
triggers=[_V41_CALLS_START],
tags=[
TagFormat(
begin=f"{_V41_CALLS_START}\n",
content=calls,
end=_V41_CALLS_END,
)
],
excludes=["<think>", "</think>"],
)
if tools
else AnyTextFormat(excludes=["<think>", "</think>"])
)
return StructuralTag(
format=SequenceFormat(
elements=[
ConstStringFormat(value=f"\n\n{_V41_CALLS_START}\n"),
calls,
ConstStringFormat(value=_V41_CALLS_END),
]
)
)
def _hermes_tool_tags(tools: list[FunctionToolParam]) -> list[TagFormat]:
arguments_field_prefix = '", "arguments": '
formats = [
+1
View File
@@ -152,6 +152,7 @@ _CONFIG_REGISTRY: dict[str, type[PretrainedConfig]] = LazyConfigDict(
laguna="LagunaConfig",
lfm2_moe="Lfm2MoeConfig",
**{"unlimited-ocr": "UnlimitedOCRConfig"},
**{"deepseek_v41": "DeepseekV41Config"},
inkling_mm_model="InklingMMConfig",
inkling_model="InklingModelConfig",
)
@@ -33,6 +33,7 @@ _CLASS_TO_MODULE: dict[str, str] = {
"DiffusionGemmaTextConfig": "vllm.transformers_utils.configs.diffusion_gemma",
"DeepseekVLV2Config": "vllm.transformers_utils.configs.deepseek_vl2",
"DeepseekV4Config": "vllm.transformers_utils.configs.deepseek_v4",
"DeepseekV41Config": "vllm.transformers_utils.configs.deepseek_v41",
"Dots3NoteConfig": "vllm.transformers_utils.configs.dots3_note",
"K3DSparkConfig": "vllm.transformers_utils.configs.k3_dspark",
"DotsOCRConfig": "vllm.transformers_utils.configs.dotsocr",
@@ -0,0 +1,76 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
from transformers import PretrainedConfig
class DeepseekV41Config(PretrainedConfig):
"""DeepSeek V4.1 config.
The HF config nests the text model under ``text_config`` and the vision
tower under ``vision_config``. The vLLM model code (ported from
``deepseek_v4``) reads flat attributes, so both sub-configs are flattened
onto the top level here: text fields are exposed as-is, vision fields
with the ``vision_*`` naming used by ``deepseek_v4_1.common.vision``.
"""
model_type = "deepseek_v41"
def __init__(
self,
text_config: dict[str, Any] | None = None,
vision_config: dict[str, Any] | None = None,
**kwargs,
):
text_config = dict(text_config or {})
vision_config = dict(vision_config or {})
# ``rope_scaling`` is a property in Transformers v5 (backed by
# ``rope_parameters``); capture it here and restore after
# super().__init__, which re-standardizes rope params.
rope_scaling = text_config.pop("rope_scaling", None)
for key, value in text_config.items():
if key == "model_type":
continue
# Don't clobber PretrainedConfig properties (e.g. is_encoder_decoder).
if isinstance(getattr(type(self), key, None), property):
continue
setattr(self, key, value)
super().__init__(**kwargs)
if rope_scaling is not None:
self.rope_parameters = rope_scaling
# The v4.1 quantization_config carries the expert dtype; the model
# code reads it from the top-level hf_config.
quant_cfg = getattr(self, "quantization_config", None) or {}
if not hasattr(self, "expert_dtype") and "expert_dtype" in quant_cfg:
self.expert_dtype = quant_cfg["expert_dtype"]
vision_n_layers = vision_config.get("num_hidden_layers", 0)
self.vision_n_layers = vision_n_layers
self.vision_dim = vision_config.get("hidden_size", 1024)
self.vision_n_heads = vision_config.get("num_attention_heads", 16)
self.vision_inter_dim = vision_config.get("intermediate_size", 2816)
self.vision_patch_size = vision_config.get("patch_size", 14)
self.vision_rope_theta = vision_config.get("rope_theta", 10000.0)
self.vision_downsample_ratio = vision_config.get("downsample_ratio", 3)
self.vision_max_n_token = vision_config.get("max_image_tokens", 1024)
self.vision_min_pixels = vision_config.get("min_pixels", 295936)
self.vision_max_wh_ratio = vision_config.get("max_wh_ratio")
# The vision variant needs the mm-prefix plumbing (atomic image-span
# prefill + sparse-SWA window widening); the base arch-config
# convertor reads this config-level attribute.
self.is_mm_prefix_lm = vision_n_layers > 0
# The sparse-SWA index kernels widen the window within image spans
# in-kernel, so mm-prefix ranges longer than sliding_window must be
# kept (they are only consumed by those kernels).
self.mm_prefix_clamp_sliding_window = vision_n_layers > 0
# The visibility span covers the image block [IMAGE_START,
# IMAGE_END]; the mm placeholder additionally carries a leading
# compressor-alignment pad of ``COMPRESS_PAD_TO - 1 - offset %
# COMPRESS_PAD_TO`` tokens (see common/mm_preprocess.py), with
# COMPRESS_PAD_TO = 2 for v4.1's ratio-2 compressors.
self.mm_prefix_span_leading_pad_modulus = 2 if vision_n_layers > 0 else 0
@@ -317,6 +317,7 @@ class ModelArchConfigConvertorBase:
"deepseek_v3",
"deepseek_v32",
"deepseek_v4",
"deepseek_v41",
"dots3_note",
"deepseek_mtp",
"k3_dspark",