[Mini-vLLM] SM86-only cut: models, backends, Rust, tests

- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries
- Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels
- Remove inc/quark quant loaders; keep compressed-tensors and Marlin
- Drop the Rust frontend, pooling entrypoints, and idle test suites
- Rebuild kernels for sm_80;sm_86 and strip the extensions
- Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-18 19:19:56 +07:00
co-authored by Hinata
parent c5ab42bc0f
commit e61dcb9143
2728 changed files with 159 additions and 950401 deletions
@@ -1,2 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -1,529 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Multimodal preprocessing for the DeepSeek-V4 vision variants
(DeepSeek-V4-Flash-Vision-Exp).
The image transform and sentinel-block 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 a variable-length block of sentinel tokens; only positions with
``type == IMAGE`` receive vision embeddings, the other sentinels are looked
up from learned embedding vectors in the model.
Unlike the reference (which uses out-of-vocab ids ``vocab_size + type``),
the sentinel block borrows five consecutive reserved tokenizer tokens
(``<|place_holder_mm_span_0431|>`` .. ``_0435|>``): they are special tokens
the tokenizer never emits from plain text, so the ids stay in-vocabulary and
work with stock token validation, logprobs and detokenization. The ids are
pure markers — every sentinel position's embedding is overwritten with
vision/sentinel vectors before the decoder layers see it, exactly like the
reference's out-of-vocab scheme.
"""
import math
from collections.abc import Mapping, Sequence
from typing import Any, assert_never
import numpy as np
import torch
from PIL import Image, ImageOps
from transformers import BatchFeature, DeepseekV4Config
from vllm.config.multimodal import MultiModalDummyOptions
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,
)
IMAGE_START, IMAGE_PAD, IMAGE, IMAGE_NEW_LINE, IMAGE_END = range(5)
COMPRESS_PAD_TO = 4
IMAGE_PLACEHOLDER = "<|deepseek_image|>"
# Sentinel roles borrow five consecutive ``<|place_holder_mm_span_XXXX|>``
# tokens (reserved special tokens, never emitted from plain text). The order
# must match IMAGE_START..IMAGE_END above so that
# ``id == IMAGE_SENTINEL_BASE_ID + type``.
IMAGE_SENTINEL_BASE_ID = 129257
IMAGE_SENTINEL_TOKEN_NAMES = (
"<|place_holder_mm_span_0431|>", # IMAGE_START
"<|place_holder_mm_span_0432|>", # IMAGE_PAD
"<|place_holder_mm_span_0433|>", # IMAGE
"<|place_holder_mm_span_0434|>", # IMAGE_NEW_LINE
"<|place_holder_mm_span_0435|>", # IMAGE_END
)
def image_sentinel_mask(token_ids: torch.Tensor) -> torch.Tensor:
"""Boolean mask for image-block sentinel positions (in-vocab ids)."""
return (token_ids >= IMAGE_SENTINEL_BASE_ID) & (
token_ids < IMAGE_SENTINEL_BASE_ID + len(IMAGE_SENTINEL_TOKEN_NAMES)
)
def validate_image_sentinel_ids(tokenizer) -> None:
"""Check the borrowed sentinel ids against the tokenizer."""
for i, name in enumerate(IMAGE_SENTINEL_TOKEN_NAMES):
token_id = tokenizer.convert_tokens_to_ids(name)
if token_id != IMAGE_SENTINEL_BASE_ID + i:
raise ValueError(
f"Image sentinel token {name!r} has id {token_id}, expected "
f"{IMAGE_SENTINEL_BASE_ID + i}; the DeepSeek-V4 vision "
"sentinel block requires these consecutive reserved ids."
)
def grid_tokens(best_height, best_width, patch_size, downsample_ratio):
"""Number of LLM tokens the aligner grid occupies (N-layout, including
row/align padding)."""
n_llm_h = math.ceil((best_height // patch_size) / downsample_ratio)
n_llm_w = math.ceil((best_width // patch_size) / downsample_ratio)
num_tokens = n_llm_h * (n_llm_w + 1) + 2
if n_llm_h % 2 == 1:
num_tokens += n_llm_w + 1
num_tokens += (n_llm_h + 1) // 2 * (n_llm_w + 1) % 2 * 2
return n_llm_h, n_llm_w, num_tokens
def solve_resize_ratio(height, width, patch_size, downsample_ratio, max_n_token):
r = height / width
max_w_float = math.sqrt((max_n_token - 2) / r + 0.25) - 0.5
max_h_float = max_w_float * r
if max_w_float < 1.0:
max_w = 1
max_h = (max_n_token - 2) // (max_w + 1)
if max_h % 2 == 1:
max_h -= 1
best_width = max_w * patch_size * downsample_ratio
best_height = max_h * patch_size * downsample_ratio
elif max_h_float < 2.0:
max_h = 2
max_w = ((max_n_token - 2) // max_h) - 1
assert max_w > 1
best_width = max_w * patch_size * downsample_ratio
best_height = max_h * patch_size * downsample_ratio
else:
max_w = math.floor(max_w_float)
max_h = math.floor(max_h_float)
if max_h % 2 == 1:
max_h -= 1
beta = min(
max_w * patch_size * downsample_ratio / width,
max_h * patch_size * downsample_ratio / height,
)
best_width = math.floor(width * beta / patch_size) * patch_size
best_height = math.floor(height * beta / patch_size) * patch_size
n_llm_h, n_llm_w, num_tokens = grid_tokens(
best_height, best_width, patch_size, downsample_ratio
)
return n_llm_h, n_llm_w, best_height, best_width, num_tokens
def safe_resize(
height, width, best_height, best_width, patch_size, downsample_ratio, max_n_token
):
max_n_token -= COMPRESS_PAD_TO - 1
n_llm_h, n_llm_w, num_tokens = grid_tokens(
best_height, best_width, patch_size, downsample_ratio
)
budget = max_n_token
while num_tokens > max_n_token:
n_llm_h, n_llm_w, best_height, best_width, num_tokens = solve_resize_ratio(
height, width, patch_size, downsample_ratio, budget
)
budget -= 1
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 build_image_block(n_llm_h: int, n_llm_w: int, start_pos: int):
"""Builds the N-layout token types (final order) and the aligner-row order
for IMAGE slots."""
compress_pad = COMPRESS_PAD_TO - 1 - start_pos % COMPRESS_PAD_TO
pad_h = n_llm_h % 2
rows = n_llm_h + pad_h
row_len = n_llm_w + 1
pad_last = rows // 2 * row_len % 2 * 2
types = torch.tensor(
([IMAGE] * n_llm_w + [IMAGE_NEW_LINE]) * n_llm_h
+ [IMAGE_PAD] * (row_len * pad_h),
dtype=torch.int64,
)
order = torch.arange(rows * row_len).view(rows // 2, 2, row_len)
order = order.transpose(1, 2).reshape(-1)
image_idx = torch.full((rows * row_len,), -1, dtype=torch.int64)
image_idx.view(rows, row_len)[:n_llm_h, :n_llm_w] = torch.arange(
n_llm_h * n_llm_w
).view(n_llm_h, n_llm_w)
perm = image_idx[order]
perm = perm[perm >= 0]
types = torch.cat(
[
torch.full((compress_pad,), IMAGE_PAD, dtype=torch.int64),
torch.tensor([IMAGE_START]),
types[order],
torch.full((pad_last,), IMAGE_PAD, dtype=torch.int64),
torch.tensor([IMAGE_END]),
]
)
return types, perm
def build_image_block_pad_free(n_llm_h: int, n_llm_w: int):
"""``build_image_block`` without the position-dependent compressor pad.
``start_pos`` is chosen so that ``compress_pad == 0``; the pad is instead
prepended when the block is spliced into the final prompt, where its
position is known.
"""
return build_image_block(n_llm_h, n_llm_w, COMPRESS_PAD_TO - 1)
class DeepseekV4VLImageProcessor:
"""Per-image transform (the PIL-input equivalent of the reference
``load_image``)."""
def __init__(self, config: DeepseekV4Config) -> 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 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]``.
- ``perm``: concatenated per-image ``(n_llm_h * n_llm_w,)`` int64 index
selecting aligner outputs into the final N-layout order.
- ``types``: concatenated per-image pad-free sentinel block types;
``block ids = IMAGE_SENTINEL_BASE_ID + types``.
"""
def __init__(self, config: DeepseekV4Config) -> 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 = []
perm_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)
types, perm = build_image_block_pad_free(n_llm_h, n_llm_w)
patches_list.append(patches)
vit_grid.append((n_vit_h, n_vit_w))
llm_grid.append((n_llm_h, n_llm_w))
perm_list.append(perm)
types_list.append(types)
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, dtype=torch.int64),
"perm": torch.cat(perm_list),
"types": torch.cat(types_list),
}
)
class DeepseekV4VLProcessingInfo(BaseProcessingInfo):
def get_hf_config(self) -> DeepseekV4Config:
return self.ctx.get_hf_config(DeepseekV4Config)
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
# sentinel block 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
max_wh_ratio = hf_config.vision_max_wh_ratio
# Every aligner row costs an extra IMAGE_NEW_LINE token, so height is
# more expensive than width and a square is *not* optimal: search the
# LLM grids that fit the budget for the one with the most ViT patches
# (ties broken by the longer sentinel block).
budget = hf_config.vision_max_n_token - (COMPRESS_PAD_TO - 1)
step = patch_size * downsample_ratio
best_grid = (1, 1)
best_key = (0, 0)
for n_llm_h in range(1, budget):
if (
grid_tokens(n_llm_h * step, step, patch_size, downsample_ratio)[2]
> budget
):
break
for n_llm_w in range(1, budget):
if max_wh_ratio is not None and n_llm_w > n_llm_h * max_wh_ratio:
break
num_tokens = grid_tokens(
n_llm_h * step, n_llm_w * step, patch_size, downsample_ratio
)[2]
if num_tokens > budget:
break
key = (n_llm_h * n_llm_w, num_tokens)
if key > best_key:
best_key, best_grid = key, (n_llm_h, n_llm_w)
n_llm_h, n_llm_w = best_grid
return ImageSize(width=n_llm_w * step, height=n_llm_h * step)
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: MultiModalDummyOptions,
) -> 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=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 = perm_sizes = types_sizes = empty
else:
patch_sizes = vit_grid.prod(-1)
perm_sizes = llm_grid.prod(-1)
n_llm_h, n_llm_w = llm_grid[:, 0], llm_grid[:, 1]
# Pad-free block length; same formula as ``grid_tokens`` given
# the LLM grid.
types_sizes = (
n_llm_h * (n_llm_w + 1)
+ 2
+ (n_llm_h % 2) * (n_llm_w + 1)
+ (n_llm_h + 1) // 2 * (n_llm_w + 1) % 2 * 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),
"perm": MultiModalFieldConfig.flat_from_sizes("image", perm_sizes),
"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())
image_embed_id = IMAGE_SENTINEL_BASE_ID + IMAGE
def get_image_replacement(item_idx: int) -> PromptUpdateDetails:
types: torch.Tensor = out_mm_kwargs["image"][item_idx]["types"].data
full = (IMAGE_SENTINEL_BASE_ID + types).tolist()
return PromptUpdateDetails.select_token_id(full, image_embed_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 (``3 - start_pos % 4`` IMAGE_PAD
# sentinels) 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.
matched_updates, result = _plan_prompt_updates(token_ids, mm_prompt_updates)
placeholders: dict[str, list[PlaceholderFeaturesInfo]] = {
modality: [] for modality in mm_prompt_updates
}
pad_id = IMAGE_SENTINEL_BASE_ID + IMAGE_PAD
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 = [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
@@ -1,23 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from .cache_utils import (
build_flashinfer_mixed_sparse_indices,
combine_topk_swa_indices,
compute_global_topk_indices_and_lens,
dequantize_and_gather_k_cache,
quantize_and_insert_k_cache,
)
from .fused_indexer_q import MXFP4_BLOCK_SIZE, fused_indexer_q_rope_quant
from .fused_inv_rope_fp8_quant import fused_inv_rope_fp8_quant
__all__ = [
"MXFP4_BLOCK_SIZE",
"build_flashinfer_mixed_sparse_indices",
"combine_topk_swa_indices",
"compute_global_topk_indices_and_lens",
"dequantize_and_gather_k_cache",
"fused_indexer_q_rope_quant",
"fused_inv_rope_fp8_quant",
"quantize_and_insert_k_cache",
]
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,733 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Any
import torch
from vllm.model_executor.warmup.jit_warmup import kernel_launcher
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
LaunchSpec,
TritonWarmupTensor,
VllmTritonJitKernel,
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.import_utils import has_cutedsl
# MXFP4: 32 elements per block, packed 2 nibbles per byte, ue8m0 block scale.
MXFP4_BLOCK_SIZE = 32
@triton.jit
def _get_cos_sin(
cos_sin_cache_ptr,
cos_sin_cache_stride,
pos,
HALF_ROT_DIM: tl.constexpr,
):
block = tl.arange(0, HALF_ROT_DIM)
cos = tl.load(cos_sin_cache_ptr + pos * cos_sin_cache_stride + block)
cos = cos.to(tl.float32)
sin = tl.load(cos_sin_cache_ptr + pos * cos_sin_cache_stride + block + HALF_ROT_DIM)
sin = sin.to(tl.float32)
return cos, sin
@triton.jit
def _fp32x2_to_fp4x2(x_lo, x_hi):
# NOTE: $1 is high nibble, $2 is low nibble
return tl.inline_asm_elementwise(
"""
{
.reg .b8 tmp;
cvt.rn.satfinite.e2m1x2.f32 tmp, $1, $2;
cvt.u32.u8 $0, tmp;
}
""",
constraints="=r,f,f",
args=[x_hi, x_lo],
dtype=tl.uint32,
is_pure=True,
pack=1,
).to(tl.uint8)
@triton.jit
def _quantize_mxfp4_pair(x_lo, x_hi):
"""Quantize a block of MXFP4_BLOCK_SIZE fp32 values given as two
interleaved halves (x_lo = values at even positions in the block,
x_hi = values at odd positions). Returns:
- packed : uint8[BLOCK/2] (low nibble = quant(x_lo), high = quant(x_hi))
- ue8m0 : scalar uint8 (block scale = 2^(ue8m0 - 127))
"""
amax = tl.maximum(tl.max(tl.abs(x_lo)), tl.max(tl.abs(x_hi)))
# 6 * 2^-126 is from https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/main/inference/kernel.py#L163
amax = tl.maximum(amax, 6.0 * (2**-126))
# ue8m0 block scale: 2^ceil(log2(amax/6.0)).
log2_ratio = tl.math.ceil(tl.math.log2(amax * (1.0 / 6.0)))
log2_ratio = tl.minimum(tl.maximum(log2_ratio, -127.0), 127.0)
scale = tl.math.exp2(log2_ratio)
ue8m0 = (log2_ratio + 127.0).to(tl.uint8)
inv_scale = 1.0 / scale
packed = _fp32x2_to_fp4x2(x_lo * inv_scale, x_hi * inv_scale)
return packed, ue8m0
class FusedIndexerQRopeQuantTritonKernel(
VllmTritonJitKernel["FusedIndexerQRopeQuantTritonKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
dtype: torch.dtype
num_heads: int
index_q_half_rot_dim: int
index_q_head_dim: int
fp8_max: float
use_fnuz: bool
use_explicit_fma: bool
@staticmethod
@triton.jit
def kernel(
pos_ptr,
# Index Q RoPE
index_q_ptr,
index_q_stride0,
index_q_stride1,
index_q_cos_sin_ptr,
index_q_cos_sin_stride,
INDEX_Q_HALF_ROT_DIM: tl.constexpr,
# Index Q Quantize
index_q_fp8_ptr,
index_q_fp8_stride0,
index_q_fp8_stride1,
INDEX_Q_HEAD_DIM: tl.constexpr,
# Index weights
index_weights_ptr,
index_weights_stride,
index_weights_softmax_scale,
index_weights_head_scale,
index_weights_out_ptr,
index_weights_out_stride,
FP8_MAX: tl.constexpr = 448.0,
USE_FNUZ: tl.constexpr = False,
USE_EXPLICIT_FMA: tl.constexpr = False,
):
# Layout matches the unfused reference (DeepseekV4ScalingRotaryEmbedding
# + per_token_group_quant_fp8): GPT-J interleaved RoPE applied to the
# LAST rope_dim dims of each head; the leading [0, NOPE_DIM) is passed
# through unchanged.
INDEX_Q_ROT_DIM: tl.constexpr = 2 * INDEX_Q_HALF_ROT_DIM
INDEX_Q_NOPE_DIM: tl.constexpr = INDEX_Q_HEAD_DIM - INDEX_Q_ROT_DIM
tl.static_assert(INDEX_Q_NOPE_DIM >= 0)
tok_idx = tl.program_id(0)
head_idx = tl.program_id(1)
pos = tl.load(pos_ptr + tok_idx)
cos, sin = _get_cos_sin(
index_q_cos_sin_ptr,
index_q_cos_sin_stride,
pos,
INDEX_Q_HALF_ROT_DIM,
)
half_offset = tl.arange(0, INDEX_Q_HALF_ROT_DIM)
base_ptr = index_q_ptr + tok_idx * index_q_stride0 + head_idx * index_q_stride1
# Interleaved (GPT-J) RoPE on dims [NOPE_DIM, HEAD_DIM):
# even = q[NOPE_DIM + 2*i], odd = q[NOPE_DIM + 2*i + 1]
rot_base = base_ptr + INDEX_Q_NOPE_DIM
x_even = tl.load(rot_base + half_offset * 2).to(tl.float32)
x_odd = tl.load(rot_base + half_offset * 2 + 1).to(tl.float32)
if USE_EXPLICIT_FMA:
# Match HIP rotary_embedding contraction before bf16 materialization.
r_even = tl.fma(x_even, cos, -(x_odd * sin))
r_odd = tl.fma(x_odd, cos, x_even * sin)
else:
r_even = x_even * cos - x_odd * sin
r_odd = x_odd * cos + x_even * sin
# Match reference numerics: fp32 → bf16 → fp32 before the ue8m0 absmax.
# Same pattern as the K-side compressor kernel (fused_compress_quant_cache.py).
r_even = r_even.to(tl.bfloat16).to(tl.float32)
r_odd = r_odd.to(tl.bfloat16).to(tl.float32)
amax = tl.maximum(tl.max(tl.abs(r_even)), tl.max(tl.abs(r_odd)))
if INDEX_Q_NOPE_DIM > 0:
nope_offset = tl.arange(0, INDEX_Q_NOPE_DIM)
x_nope = tl.load(base_ptr + nope_offset).to(tl.float32)
amax = tl.maximum(amax, tl.max(tl.abs(x_nope)))
index_q_scale = tl.div_rn(tl.maximum(amax, 1e-4), FP8_MAX)
index_q_scale = tl.math.exp2(tl.math.ceil(tl.math.log2(index_q_scale)))
# Store quantized values to index_q_fp8. FNUZ (e4m3fnuz) on gfx942, OCP
# (e4m3fn) elsewhere -- matches the K cache.
fp8_dtype = tl.float8e4b8 if USE_FNUZ else tl.float8e4nv
fp8_base_ptr = (
index_q_fp8_ptr
+ tok_idx * index_q_fp8_stride0
+ head_idx * index_q_fp8_stride1
)
if INDEX_Q_NOPE_DIM > 0:
tl.store(
fp8_base_ptr + nope_offset,
tl.div_rn(x_nope, index_q_scale).to(fp8_dtype),
)
fp8_rot_base = fp8_base_ptr + INDEX_Q_NOPE_DIM
tl.store(
fp8_rot_base + half_offset * 2,
tl.div_rn(r_even, index_q_scale).to(fp8_dtype),
)
tl.store(
fp8_rot_base + half_offset * 2 + 1,
tl.div_rn(r_odd, index_q_scale).to(fp8_dtype),
)
# FP8 weight-fold contract:
# index_weights_out = index_weights * q_scale * softmax_scale * head_scale
# The per-token-per-head q_scale (fp32) IS folded into the output weights
# here because FP8 Q is stored WITHOUT a companion scale tensor — the
# downstream fp8_fp4_mqa_logits/fp8_fp4_paged_mqa_logits kernels use
# `weights` to apply per-token Q scale inline. See the MXFP4 kernel below for
# contrasting convention (scales live with the Q values, weights are NOT
# q-scaled).
index_weights = tl.load(
index_weights_ptr + tok_idx * index_weights_stride + head_idx
)
index_weights = index_weights.to(tl.float32)
index_weights *= index_q_scale
index_weights *= index_weights_softmax_scale
index_weights *= index_weights_head_scale
tl.store(
index_weights_out_ptr + tok_idx * index_weights_out_stride + head_idx,
index_weights,
)
def dispatch( # type: ignore[override]
self,
*,
dtype: torch.dtype,
num_heads: int,
head_dim: int,
rope_dim: int,
use_fnuz: bool,
) -> CompileKey:
return self.CompileKey(
dtype=dtype,
num_heads=num_heads,
index_q_half_rot_dim=rope_dim // 2,
index_q_head_dim=head_dim,
fp8_max=224.0 if use_fnuz else 448.0,
use_fnuz=use_fnuz,
use_explicit_fma=current_platform.is_rocm(),
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
hf_config = vllm_config.model_config.hf_config
num_heads = int(getattr(hf_config, "index_n_heads", 0) or 0)
head_dim = int(getattr(hf_config, "index_head_dim", 0) or 0)
rope_dim = int(getattr(hf_config, "qk_rope_head_dim", 0) or 0)
if num_heads <= 0 or head_dim <= 0 or rope_dim <= 0:
return []
return self._trace_dispatch(self.dispatch)(
dtype=vllm_config.model_config.dtype,
num_heads=num_heads,
head_dim=head_dim,
rope_dim=rope_dim,
use_fnuz=current_platform.fp8_dtype() == torch.float8_e4m3fnuz,
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
q_stride0 = compile_key.num_heads * compile_key.index_q_head_dim
return dict(
positions=TritonWarmupTensor(torch.int64),
index_q=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.num_heads, compile_key.index_q_head_dim),
strides=(q_stride0, compile_key.index_q_head_dim, 1),
),
index_q_cos_sin_cache=TritonWarmupTensor(
torch.float32,
shape=(1, compile_key.index_q_half_rot_dim * 2),
),
index_weights=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.num_heads),
),
index_weights_softmax_scale=1.0,
index_weights_head_scale=1.0,
index_q_fp8=TritonWarmupTensor(
current_platform.fp8_dtype(),
shape=(1, compile_key.num_heads, compile_key.index_q_head_dim),
strides=(q_stride0, compile_key.index_q_head_dim, 1),
),
index_weights_out=TritonWarmupTensor(
torch.float32,
shape=(1, compile_key.num_heads),
),
fp8_max=compile_key.fp8_max,
use_fnuz=compile_key.use_fnuz,
)
@kernel_launcher
def __call__(
self,
positions: torch.Tensor,
index_q: torch.Tensor,
index_q_cos_sin_cache: torch.Tensor,
index_weights: torch.Tensor,
index_weights_softmax_scale: float,
index_weights_head_scale: float,
index_q_fp8: torch.Tensor,
index_weights_out: torch.Tensor,
*,
fp8_max: float,
use_fnuz: bool,
) -> LaunchSpec:
num_tokens = positions.shape[0]
num_index_q_heads = index_q.shape[1]
return (num_tokens, num_index_q_heads), dict(
pos_ptr=positions,
index_q_stride0=index_q.stride(0),
index_q_stride1=index_q.stride(1),
index_q_cos_sin_ptr=index_q_cos_sin_cache,
index_q_cos_sin_stride=index_q_cos_sin_cache.stride(0),
INDEX_Q_HALF_ROT_DIM=index_q_cos_sin_cache.shape[-1] // 2,
index_q_fp8_stride0=index_q_fp8.stride(0),
index_q_fp8_stride1=index_q_fp8.stride(1),
INDEX_Q_HEAD_DIM=index_q.shape[2],
index_weights_stride=index_weights.stride(0),
index_weights_out_stride=index_weights_out.stride(0),
FP8_MAX=fp8_max,
USE_FNUZ=use_fnuz,
USE_EXPLICIT_FMA=current_platform.is_rocm(),
enable_fp_fusion=True,
num_warps=1,
)
def _indexer_weights_out_dtypes(vllm_config: Any) -> tuple[torch.dtype, ...]:
"""Weights dtypes the model's indexer layers ask for: fp32 for the dense
scoring kernels, plus bf16 when the DeepSeek V4.1 sparse-logits indexer
(`SparseMQAIndexer`) is enabled."""
if vllm_config.attention_config.indexer_sparse_logits:
return (torch.float32, torch.bfloat16)
return (torch.float32,)
class FusedIndexerQRopeMxFp4TritonKernel(
VllmTritonJitKernel["FusedIndexerQRopeMxFp4TritonKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
dtype: torch.dtype
weights_out_dtype: torch.dtype
num_heads: int
index_q_half_rot_dim: int
index_q_head_dim: int
mxfp4_block: int
@staticmethod
@triton.jit
def kernel(
pos_ptr,
# Index Q RoPE input (fp/bf16)
index_q_ptr,
index_q_stride0,
index_q_stride1,
index_q_cos_sin_ptr,
index_q_cos_sin_stride,
INDEX_Q_HALF_ROT_DIM: tl.constexpr,
# MXFP4 Q outputs
index_q_mxfp4_ptr, # uint8, (T, H, HEAD_DIM // 2)
index_q_mxfp4_stride0,
index_q_mxfp4_stride1,
index_q_scale_ptr, # uint8 ue8m0, (T, H, HEAD_DIM // BLOCK)
index_q_scale_stride0,
index_q_scale_stride1,
INDEX_Q_HEAD_DIM: tl.constexpr,
MXFP4_BLOCK: tl.constexpr,
# Weights (NO per-token q_scale fold for MXFP4; per-block scales stay
# with the Q values in the output scale tensor).
index_weights_ptr,
index_weights_stride,
index_weights_softmax_scale,
index_weights_head_scale,
index_weights_out_ptr,
index_weights_out_stride,
):
INDEX_Q_ROT_DIM: tl.constexpr = 2 * INDEX_Q_HALF_ROT_DIM
INDEX_Q_NOPE_DIM: tl.constexpr = INDEX_Q_HEAD_DIM - INDEX_Q_ROT_DIM
NUM_NOPE_BLOCKS: tl.constexpr = INDEX_Q_NOPE_DIM // MXFP4_BLOCK
NUM_ROPE_BLOCKS: tl.constexpr = INDEX_Q_ROT_DIM // MXFP4_BLOCK
HALF_BLOCK: tl.constexpr = MXFP4_BLOCK // 2
tl.static_assert(INDEX_Q_NOPE_DIM >= 0)
tl.static_assert(INDEX_Q_NOPE_DIM % MXFP4_BLOCK == 0)
tl.static_assert(INDEX_Q_ROT_DIM % MXFP4_BLOCK == 0)
tl.static_assert(MXFP4_BLOCK % 2 == 0)
tok_idx = tl.program_id(0)
head_idx = tl.program_id(1)
pos = tl.load(pos_ptr + tok_idx)
q_base = index_q_ptr + tok_idx * index_q_stride0 + head_idx * index_q_stride1
out_base = (
index_q_mxfp4_ptr
+ tok_idx * index_q_mxfp4_stride0
+ head_idx * index_q_mxfp4_stride1
)
scale_base = (
index_q_scale_ptr
+ tok_idx * index_q_scale_stride0
+ head_idx * index_q_scale_stride1
)
half_off = tl.arange(0, HALF_BLOCK)
# ---- NoPE blocks: direct load, pair as (even-index, odd-index) values ----
for b in tl.static_range(NUM_NOPE_BLOCKS):
base = b * MXFP4_BLOCK
x_lo = tl.load(q_base + base + half_off * 2).to(tl.float32)
x_hi = tl.load(q_base + base + half_off * 2 + 1).to(tl.float32)
packed, ue8m0 = _quantize_mxfp4_pair(x_lo, x_hi)
tl.store(out_base + base // 2 + half_off, packed)
tl.store(scale_base + b, ue8m0)
# ---- RoPE blocks: apply GPT-J interleaved RoPE to the block's 16 pairs,
# then quantize. Each block covers HALF_BLOCK (=16) cos/sin pairs. ----
rot_q_base = q_base + INDEX_Q_NOPE_DIM
for b in tl.static_range(NUM_ROPE_BLOCKS):
pair_off = b * HALF_BLOCK + half_off # indices in [0, HALF_ROT_DIM)
cos_b = tl.load(
index_q_cos_sin_ptr + pos * index_q_cos_sin_stride + pair_off
).to(tl.float32)
sin_b = tl.load(
index_q_cos_sin_ptr
+ pos * index_q_cos_sin_stride
+ pair_off
+ INDEX_Q_HALF_ROT_DIM
).to(tl.float32)
x_even = tl.load(rot_q_base + pair_off * 2).to(tl.float32)
x_odd = tl.load(rot_q_base + pair_off * 2 + 1).to(tl.float32)
r_even = x_even * cos_b - x_odd * sin_b
r_odd = x_odd * cos_b + x_even * sin_b
# bf16 roundtrip for parity with the FP8 kernel / reference numerics.
r_even = r_even.to(tl.bfloat16).to(tl.float32)
r_odd = r_odd.to(tl.bfloat16).to(tl.float32)
packed, ue8m0 = _quantize_mxfp4_pair(r_even, r_odd)
rope_byte_off = (INDEX_Q_NOPE_DIM + b * MXFP4_BLOCK) // 2
tl.store(out_base + rope_byte_off + half_off, packed)
tl.store(scale_base + NUM_NOPE_BLOCKS + b, ue8m0)
# MXFP4 weight-fold contract:
# index_weights_out = index_weights * softmax_scale * head_scale
# NOTE: q_scale is NOT folded here (contrast with the FP8 kernel above).
# MXFP4 Q emits a separate ue8m0 scale tensor of shape
# (T, H, HEAD_DIM // MXFP4_BLOCK) alongside the packed values, so each
# per-block scale is applied by the downstream MXFP4 logits kernel when
# dequantizing Q — there is no per-token scalar to fold into `weights`.
index_weights = tl.load(
index_weights_ptr + tok_idx * index_weights_stride + head_idx
).to(tl.float32)
index_weights *= index_weights_softmax_scale
index_weights *= index_weights_head_scale
tl.store(
index_weights_out_ptr + tok_idx * index_weights_out_stride + head_idx,
index_weights,
)
def dispatch( # type: ignore[override]
self,
*,
dtype: torch.dtype,
weights_out_dtype: torch.dtype,
num_heads: int,
head_dim: int,
rope_dim: int,
) -> CompileKey:
return self.CompileKey(
dtype=dtype,
weights_out_dtype=weights_out_dtype,
num_heads=num_heads,
index_q_half_rot_dim=rope_dim // 2,
index_q_head_dim=head_dim,
mxfp4_block=MXFP4_BLOCK_SIZE,
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
hf_config = vllm_config.model_config.hf_config
num_heads = int(getattr(hf_config, "index_n_heads", 0) or 0)
head_dim = int(getattr(hf_config, "index_head_dim", 0) or 0)
rope_dim = int(getattr(hf_config, "qk_rope_head_dim", 0) or 0)
if num_heads <= 0 or head_dim <= 0 or rope_dim <= 0:
return []
return self._trace_dispatch(self.dispatch)(
dtype=vllm_config.model_config.dtype,
weights_out_dtype=_indexer_weights_out_dtypes(vllm_config),
num_heads=num_heads,
head_dim=head_dim,
rope_dim=rope_dim,
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
q_stride0 = compile_key.num_heads * compile_key.index_q_head_dim
packed_head_dim = compile_key.index_q_head_dim // 2
scale_head_dim = compile_key.index_q_head_dim // compile_key.mxfp4_block
return dict(
positions=TritonWarmupTensor(torch.int64),
index_q=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.num_heads, compile_key.index_q_head_dim),
strides=(q_stride0, compile_key.index_q_head_dim, 1),
),
index_q_cos_sin_cache=TritonWarmupTensor(
torch.float32,
shape=(1, compile_key.index_q_half_rot_dim * 2),
),
index_weights=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.num_heads),
),
index_weights_softmax_scale=1.0,
index_weights_head_scale=1.0,
index_q_packed=TritonWarmupTensor(
torch.uint8,
shape=(1, compile_key.num_heads, packed_head_dim),
),
index_q_scale=TritonWarmupTensor(
torch.uint8,
shape=(1, compile_key.num_heads, scale_head_dim),
),
index_weights_out=TritonWarmupTensor(
compile_key.weights_out_dtype,
shape=(1, compile_key.num_heads),
),
)
@kernel_launcher
def __call__(
self,
positions: torch.Tensor,
index_q: torch.Tensor,
index_q_cos_sin_cache: torch.Tensor,
index_weights: torch.Tensor,
index_weights_softmax_scale: float,
index_weights_head_scale: float,
index_q_packed: torch.Tensor,
index_q_scale: torch.Tensor,
index_weights_out: torch.Tensor,
) -> LaunchSpec:
num_tokens = positions.shape[0]
num_index_q_heads = index_q.shape[1]
return (num_tokens, num_index_q_heads), dict(
pos_ptr=positions,
index_q_stride0=index_q.stride(0),
index_q_stride1=index_q.stride(1),
index_q_cos_sin_ptr=index_q_cos_sin_cache,
index_q_cos_sin_stride=index_q_cos_sin_cache.stride(0),
INDEX_Q_HALF_ROT_DIM=index_q_cos_sin_cache.shape[-1] // 2,
index_q_mxfp4_ptr=index_q_packed,
index_q_mxfp4_stride0=index_q_packed.stride(0),
index_q_mxfp4_stride1=index_q_packed.stride(1),
index_q_scale_stride0=index_q_scale.stride(0),
index_q_scale_stride1=index_q_scale.stride(1),
INDEX_Q_HEAD_DIM=index_q.shape[2],
MXFP4_BLOCK=MXFP4_BLOCK_SIZE,
index_weights_stride=index_weights.stride(0),
index_weights_out_stride=index_weights_out.stride(0),
enable_fp_fusion=True,
num_warps=1,
)
def fused_indexer_q_rope_quant(
positions: torch.Tensor,
index_q: torch.Tensor,
index_q_cos_sin_cache: torch.Tensor,
# Index weights
index_weights: torch.Tensor,
index_weights_softmax_scale: float,
index_weights_head_scale: float,
use_fp4: bool = False,
weights_out_dtype: torch.dtype = torch.float32,
) -> tuple[
torch.Tensor | tuple[torch.Tensor, torch.Tensor],
torch.Tensor,
]:
"""Fused RoPE + quantize Q for the sparse indexer.
``weights_out_dtype`` is the dtype the downstream scoring kernel takes:
fp32 for the dense MQA-logits kernels, bf16 for DeepGEMM's sparse
MQA-logits kernels (CUDA MXFP4 path only).
Weight-fold semantics (important — the two paths differ):
FP8 path (use_fp4=False, default):
q_fp8 : (T, H, HEAD_DIM) platform fp8 (e4m3fnuz on gfx942,
e4m3fn elsewhere); per-token-per-head scalar scale
(NOT stored — folded into weights below)
weights_out = weights * q_scale * softmax_scale * head_scale
Rationale: a single per-token q_scale is a scalar the downstream FP8
logits kernel would otherwise multiply in. Folding it into `weights`
avoids emitting a separate tensor and is free for the logits kernel.
MXFP4 path (use_fp4=True):
q_packed : (T, H, HEAD_DIM // 2) uint8 (2 E2M1 nibbles per byte)
q_scale : (T, H, HEAD_DIM // MXFP4_BLOCK_SIZE) uint8 ue8m0 bytes
weights_out = weights * softmax_scale * head_scale
Rationale: MXFP4 has PER-BLOCK (32-element) scales that live with
the Q values — they cannot be folded into a per-token weight
scalar, so `weights` carries only the softmax and head scales.
Returns (q_quant, weights_out) where q_quant is either a Tensor (FP8) or
a (values, scales) tuple (MXFP4). This matches the union type accepted
by `SparseAttnIndexer.forward_*`.
"""
assert positions.ndim == 1
assert index_q.ndim == 3
assert index_q_cos_sin_cache.ndim == 2
num_tokens = positions.shape[0]
num_index_q_heads = index_q.shape[1]
index_q_head_dim = index_q.shape[2]
index_weights_out = torch.empty_like(index_weights, dtype=weights_out_dtype)
if use_fp4:
assert index_q_head_dim % MXFP4_BLOCK_SIZE == 0, (
f"head_dim={index_q_head_dim} must be a multiple of MXFP4 block "
f"size {MXFP4_BLOCK_SIZE}"
)
num_scale_blocks = index_q_head_dim // MXFP4_BLOCK_SIZE
index_q_packed = torch.empty(
(num_tokens, num_index_q_heads, index_q_head_dim // 2),
dtype=torch.uint8,
device=index_q.device,
)
index_q_scale = torch.empty(
(num_tokens, num_index_q_heads, num_scale_blocks),
dtype=torch.uint8,
device=index_q.device,
)
if has_cutedsl():
# lazily import, otherwise some tests fail due to CUDA driver init failure.
from vllm.models.deepseek_v4.nvidia.ops.fused_indexer_q_cutedsl import (
_INDEXER_Q_MXFP4_KERNEL,
)
_INDEXER_Q_MXFP4_KERNEL(
positions=positions,
q=index_q,
cos_sin_cache=index_q_cos_sin_cache,
weights=index_weights,
weights_softmax_scale=index_weights_softmax_scale,
weights_head_scale=index_weights_head_scale,
q_packed=index_q_packed,
q_scale=index_q_scale,
weights_out=index_weights_out,
)
elif current_platform.is_xpu():
assert weights_out_dtype == torch.float32, weights_out_dtype
torch.ops.vllm.xpu_deepseek_fused_indexer_q_rope_mxfp4(
index_q,
positions,
index_q_cos_sin_cache,
index_weights,
index_weights_softmax_scale,
index_weights_head_scale,
index_q_packed,
index_q_scale,
index_weights_out,
)
else:
_FUSED_INDEXER_Q_ROPE_MXFP4_TRITON_KERNEL(
positions,
index_q,
index_q_cos_sin_cache,
index_weights,
index_weights_softmax_scale,
index_weights_head_scale,
index_q_packed,
index_q_scale,
index_weights_out,
)
# Values stay uint8 (2 E2M1 nibbles per byte). Scales are 4 ue8m0
# bytes per (token, head) reinterpreted as one int32, then squeezed
# from (T, H, 1) to (T, H) to match DeepGEMM's expected q_sf rank
# (prefill wants 2-D (seq_len, num_heads); decode reshapes this to
# 3-D (batch, next_n, num_heads)).
return (
index_q_packed,
index_q_scale.view(torch.int32).squeeze(-1),
), index_weights_out
assert weights_out_dtype == torch.float32, weights_out_dtype
fp8_dtype = current_platform.fp8_dtype()
use_fnuz = fp8_dtype == torch.float8_e4m3fnuz
fp8_max = 224.0 if use_fnuz else 448.0
index_q_fp8 = torch.empty_like(index_q, dtype=fp8_dtype)
if has_cutedsl():
# lazily import, otherwise some tests fail due to CUDA driver init failure.
from vllm.models.deepseek_v4.nvidia.ops.fused_indexer_q_cutedsl import (
_INDEXER_Q_FP8_KERNEL,
)
_INDEXER_Q_FP8_KERNEL(
positions=positions,
q=index_q,
cos_sin_cache=index_q_cos_sin_cache,
weights=index_weights,
weights_softmax_scale=index_weights_softmax_scale,
weights_head_scale=index_weights_head_scale,
q_fp8=index_q_fp8.view(torch.uint8),
weights_out=index_weights_out,
)
elif current_platform.is_xpu():
torch.ops.vllm.xpu_deepseek_fused_indexer_q_rope_fp8(
index_q,
positions,
index_q_cos_sin_cache,
index_weights,
index_weights_softmax_scale,
index_weights_head_scale,
index_q_fp8,
index_weights_out,
)
elif current_platform.is_cpu():
from vllm._custom_ops import fused_indexer_q_rope_quant_cpu
fused_indexer_q_rope_quant_cpu(
positions.contiguous(),
index_q.to(torch.float32),
index_q_cos_sin_cache.to(torch.float32).contiguous(),
index_q_fp8,
index_weights.to(torch.float32),
index_weights_softmax_scale,
index_weights_head_scale,
index_weights_out,
)
else:
_FUSED_INDEXER_Q_ROPE_QUANT_TRITON_KERNEL(
positions,
index_q,
index_q_cos_sin_cache,
index_weights,
index_weights_softmax_scale,
index_weights_head_scale,
index_q_fp8,
index_weights_out,
fp8_max=fp8_max,
use_fnuz=use_fnuz,
)
return index_q_fp8, index_weights_out
_FUSED_INDEXER_Q_ROPE_QUANT_TRITON_KERNEL = FusedIndexerQRopeQuantTritonKernel()
_FUSED_INDEXER_Q_ROPE_MXFP4_TRITON_KERNEL = FusedIndexerQRopeMxFp4TritonKernel()
@@ -1,538 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused inverse RoPE + block-scaled FP8 quantization kernel for DeepseekV4 attention.
Output scale format is pre-transformed (MN-major TMA-aligned; FP32 on SM90,
INT32-packed UE8M0 on SM100) so fp8_einsum skips transform_sf_into_required_layout.
"""
from dataclasses import dataclass
from typing import Any
import torch
from vllm.model_executor.warmup.jit_warmup import kernel_launcher
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
LaunchSpec,
TritonWarmupTensor,
VllmTritonJitKernel,
)
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import direct_register_custom_op
class FusedInvRopeFP8QuantKernel(
VllmTritonJitKernel["FusedInvRopeFP8QuantKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
heads_per_group: int
fp8_max: float
quant_group_size: int
chunks_per_head: int
nope_dim: int
half_rope: int
tma_aligned_scales: bool
launch_pdl: bool
quantize: bool
@staticmethod
# scale_stride_k = align(num_tokens, 4) is only 4-aligned, so its Triton int
# class varies with batch size; not specialized so one warmup key covers all
# (int64-cast, so perf-neutral).
@triton.jit(do_not_specialize=["num_tokens", "scale_stride_k"])
def kernel(
o_ptr,
positions_ptr,
cos_sin_cache_ptr,
out_ptr,
scale_ptr,
num_tokens,
heads_per_group: tl.constexpr,
o_stride_token,
o_stride_head,
cache_stride_pos,
out_stride_group,
out_stride_token,
scale_stride_group,
scale_stride_k,
fp8_max: tl.constexpr,
eps: tl.constexpr,
QUANT_GROUP_SIZE: tl.constexpr,
CHUNKS_PER_HEAD: tl.constexpr,
NOPE_DIM: tl.constexpr,
HALF_ROPE: tl.constexpr,
QUANTIZE: tl.constexpr,
TMA_ALIGNED_SCALES: tl.constexpr,
launch_pdl: tl.constexpr,
):
# Cast every stride to int64 — without this, Python-int strides are
# inferred as int32 and `pid_token(int64) × stride(int32)` can lower to
# int32 arithmetic, wrapping past 2³¹ for large prefill batches → IMA.
pid_token = tl.program_id(0).to(tl.int64)
pid_gh = tl.program_id(1).to(tl.int64)
o_stride_token = o_stride_token.to(tl.int64)
o_stride_head = o_stride_head.to(tl.int64)
cache_stride_pos = cache_stride_pos.to(tl.int64)
out_stride_group = out_stride_group.to(tl.int64)
out_stride_token = out_stride_token.to(tl.int64)
scale_stride_group = scale_stride_group.to(tl.int64)
scale_stride_k = scale_stride_k.to(tl.int64)
g = pid_gh // heads_per_group
head_in_group = pid_gh % heads_per_group
global_head = pid_gh
qb_start = head_in_group * CHUNKS_PER_HEAD
if launch_pdl:
tl.extra.cuda.gdc_launch_dependents()
tl.extra.cuda.gdc_wait()
# Padding rows in the TMA-aligned scale buffer: fill with zero and skip quant.
if pid_token >= num_tokens:
if not QUANTIZE:
return
if TMA_ALIGNED_SCALES:
packed_offsets = tl.arange(0, CHUNKS_PER_HEAD // 4)
scale_addr = (
scale_ptr
+ g * scale_stride_group
+ pid_token
+ (head_in_group * (CHUNKS_PER_HEAD // 4) + packed_offsets)
* scale_stride_k
)
tl.store(scale_addr, tl.zeros((CHUNKS_PER_HEAD // 4,), dtype=tl.int32))
else:
block_offsets = tl.arange(0, CHUNKS_PER_HEAD)
qb_indices = qb_start + block_offsets
scale_addrs = (
scale_ptr
+ g * scale_stride_group
+ pid_token
+ qb_indices * scale_stride_k
)
tl.store(scale_addrs, tl.zeros((CHUNKS_PER_HEAD,), dtype=tl.float32))
return
input_base = o_ptr + pid_token * o_stride_token + global_head * o_stride_head
HEAD_DIM: tl.constexpr = CHUNKS_PER_HEAD * QUANT_GROUP_SIZE
offsets = tl.arange(0, HEAD_DIM)
x = tl.load(input_base + offsets).to(tl.float32)
rope_abs_start: tl.constexpr = NOPE_DIM
pos = tl.load(positions_ptr + pid_token)
cache_base = cos_sin_cache_ptr + pos * cache_stride_pos
is_rope = offsets >= rope_abs_start
rope_local = offsets - rope_abs_start
x_partner = tl.load(input_base + (offsets ^ 1), mask=is_rope, other=0.0).to(
tl.float32
)
cs_idx = tl.maximum(rope_local >> 1, 0)
cos_v = tl.load(cache_base + cs_idx, mask=is_rope, other=1.0)
sin_v = tl.load(cache_base + HALF_ROPE + cs_idx, mask=is_rope, other=0.0)
x_add = x * cos_v + x_partner * sin_v
x_sub = x * cos_v - x_partner * sin_v
is_even = (rope_local & 1) == 0
rotated = tl.where(is_even, x_add, x_sub)
x = tl.where(is_rope, rotated, x)
if not QUANTIZE:
out_base = (
out_ptr
+ g * out_stride_group
+ pid_token * out_stride_token
+ qb_start * QUANT_GROUP_SIZE
)
tl.store(out_base + offsets, x)
return
x_2d = tl.reshape(tl.abs(x), (CHUNKS_PER_HEAD, QUANT_GROUP_SIZE))
block_absmax = tl.maximum(tl.max(x_2d, axis=1), eps)
scale_raw = block_absmax * (1.0 / fp8_max)
scales = tl.math.exp2(tl.ceil(tl.log2(scale_raw)))
scales_exp = tl.reshape(
tl.broadcast_to(
tl.reshape(scales, (CHUNKS_PER_HEAD, 1)),
(CHUNKS_PER_HEAD, QUANT_GROUP_SIZE),
),
(HEAD_DIM,),
)
x_quant = tl.clamp(x / scales_exp, -fp8_max, fp8_max).to(tl.float8e4nv)
out_base = (
out_ptr
+ g * out_stride_group
+ pid_token * out_stride_token
+ qb_start * QUANT_GROUP_SIZE
)
tl.store(out_base + offsets, x_quant)
block_offsets = tl.arange(0, CHUNKS_PER_HEAD)
qb_indices = qb_start + block_offsets
if TMA_ALIGNED_SCALES:
scale_bits = scales.to(tl.int32, bitcast=True)
ue8m0_bytes = (scale_bits >> 23) & 0xFF
packed_val = tl.sum(
tl.reshape(ue8m0_bytes, (CHUNKS_PER_HEAD // 4, 4))
<< (tl.arange(0, 4)[None, :] * 8),
axis=1,
)
packed_offsets = tl.arange(0, CHUNKS_PER_HEAD // 4)
scale_addr = (
scale_ptr
+ g * scale_stride_group
+ pid_token
+ (head_in_group * (CHUNKS_PER_HEAD // 4) + packed_offsets)
* scale_stride_k
)
tl.store(scale_addr, packed_val)
else:
scale_addrs = (
scale_ptr
+ g * scale_stride_group
+ pid_token
+ qb_indices * scale_stride_k
)
tl.store(scale_addrs, scales)
def dispatch( # type: ignore[override]
self,
*,
heads_per_group: int,
head_dim: int,
nope_dim: int,
rope_dim: int,
quant_group_size: int,
runtime_fp8_max: float | None = None,
runtime_chunks_per_head: int | None = None,
runtime_nope_dim: int | None = None,
runtime_half_rope: int | None = None,
**compile_key_fields: bool,
) -> CompileKey:
fp8_max = (
runtime_fp8_max
if runtime_fp8_max is not None
else torch.finfo(torch.float8_e4m3fn).max
)
chunks_per_head = (
runtime_chunks_per_head
if runtime_chunks_per_head is not None
else head_dim // quant_group_size
)
nope_dim = runtime_nope_dim if runtime_nope_dim is not None else nope_dim
half_rope = (
runtime_half_rope if runtime_half_rope is not None else rope_dim // 2
)
return self.CompileKey(
**compile_key_fields,
heads_per_group=heads_per_group,
fp8_max=fp8_max,
quant_group_size=quant_group_size,
chunks_per_head=chunks_per_head,
nope_dim=nope_dim,
half_rope=half_rope,
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
hf_config = vllm_config.model_config.hf_config
if hf_config is None:
return []
tp_size = vllm_config.parallel_config.tensor_parallel_size
num_heads = int(getattr(hf_config, "num_attention_heads", 0) or 0)
num_groups = int(getattr(hf_config, "o_groups", 0) or 0)
if num_heads <= 0 or num_groups <= 0:
return []
local_heads = num_heads // tp_size
local_groups = num_groups // tp_size
if local_groups <= 0:
return []
capability = current_platform.get_device_capability()
if capability is None:
return []
head_dim = int(getattr(hf_config, "head_dim", 512) or 512)
rope_dim = int(getattr(hf_config, "qk_rope_head_dim", 64) or 64)
return self._trace_dispatch(self.dispatch)(
heads_per_group=local_heads // local_groups,
head_dim=head_dim,
nope_dim=head_dim - rope_dim,
rope_dim=rope_dim,
quant_group_size=128,
tma_aligned_scales=capability.major >= 10,
launch_pdl=current_platform.is_arch_support_pdl(),
quantize=True,
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
head_dim = compile_key.chunks_per_head * compile_key.quant_group_size
out_dim = compile_key.heads_per_group * head_dim
scale_dtype = torch.int32 if compile_key.tma_aligned_scales else torch.float32
return dict(
o=TritonWarmupTensor(
torch.bfloat16,
shape=(1, compile_key.heads_per_group, head_dim),
),
positions=TritonWarmupTensor(torch.int64),
cos_sin_cache=TritonWarmupTensor(
torch.float32,
shape=(1, compile_key.half_rope * 2),
),
out_buf=TritonWarmupTensor(
torch.float8_e4m3fn if compile_key.quantize else torch.bfloat16,
shape=(compile_key.heads_per_group, 1, out_dim),
strides=(out_dim, out_dim, 1),
),
scale_buf=TritonWarmupTensor(
scale_dtype,
shape=(compile_key.heads_per_group, 1, 16),
strides=(16, 16, 16),
),
num_tokens=1,
heads_per_group=compile_key.heads_per_group,
quant_group_size=compile_key.quant_group_size,
chunks_per_head=compile_key.chunks_per_head,
nope_dim=compile_key.nope_dim,
half_rope=compile_key.half_rope,
tma_aligned_scales=compile_key.tma_aligned_scales,
quantize=compile_key.quantize,
fp8_max=compile_key.fp8_max,
launch_pdl=compile_key.launch_pdl,
grid=(1, compile_key.heads_per_group),
)
@kernel_launcher
def __call__(
self,
o: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
out_buf: torch.Tensor,
scale_buf: torch.Tensor,
num_tokens: int,
*,
heads_per_group: int,
quant_group_size: int,
chunks_per_head: int,
nope_dim: int,
half_rope: int,
tma_aligned_scales: bool,
quantize: bool,
fp8_max: float,
launch_pdl: bool,
grid: tuple[int, int],
) -> LaunchSpec:
return grid, dict(
out_ptr=out_buf,
scale_ptr=scale_buf,
o_stride_token=o.stride(0),
o_stride_head=o.stride(1),
cache_stride_pos=cos_sin_cache.stride(0),
out_stride_group=out_buf.stride(0),
out_stride_token=out_buf.stride(1),
scale_stride_group=scale_buf.stride(0) if quantize else 0,
scale_stride_k=scale_buf.stride(2) if quantize else 0,
eps=1e-10,
QUANT_GROUP_SIZE=quant_group_size,
CHUNKS_PER_HEAD=chunks_per_head,
NOPE_DIM=nope_dim,
HALF_ROPE=half_rope,
QUANTIZE=quantize,
TMA_ALIGNED_SCALES=tma_aligned_scales,
launch_pdl=launch_pdl,
num_stages=1,
num_warps=1,
)
def fused_inv_rope_fp8_quant(
o: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
n_groups: int,
heads_per_group: int,
nope_dim: int = 448,
rope_dim: int = 64,
quant_group_size: int = 128,
tma_aligned_scales: bool = False,
quantize: bool = True,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Fused inverse RoPE + block-scaled FP8 quantization.
Args:
o: Attention output [num_tokens, num_heads, head_dim] bf16.
positions: Token positions [num_tokens] int64.
cos_sin_cache: Precomputed [max_pos, rope_dim] with cos||sin.
n_groups: Number of output groups.
heads_per_group: Heads per group.
nope_dim: Non-RoPE dimensions per head (default 448).
rope_dim: RoPE dimensions per head (default 64).
quant_group_size: FP8 quantization block size (default 128).
tma_aligned_scales: Output INT32 packed UE8M0 for SM100 (True)
or FP32 for SM90 (False).
quantize: Quantize the rotated output to FP8 and return its scales.
Returns:
Rotated output in [T, G, D] and its FP8 scales. The scale tensor is
empty when quantization is disabled.
"""
from vllm.utils.deep_gemm import get_tma_aligned_size
num_tokens, num_heads, head_dim = o.shape
assert num_heads == n_groups * heads_per_group
assert head_dim == nope_dim + rope_dim
assert head_dim % quant_group_size == 0
assert rope_dim % 2 == 0
assert cos_sin_cache.shape[-1] == rope_dim
assert cos_sin_cache.dtype == torch.float32
d = heads_per_group * head_dim
num_scale_blocks = d // quant_group_size
chunks_per_head = head_dim // quant_group_size
fp8_dtype = torch.float8_e4m3fn
fp8_max = torch.finfo(fp8_dtype).max
tma_aligned_T = get_tma_aligned_size(num_tokens, 4) if quantize else num_tokens
if quantize and tma_aligned_scales:
assert chunks_per_head % 4 == 0
packed_sf_k = (num_scale_blocks + 3) // 4
scale_inner = packed_sf_k
elif quantize:
scale_inner = num_scale_blocks
else:
scale_inner = 0
# Run kernel through a custom op so inductor sees an opaque boundary.
# It's a pytorch bug, see https://github.com/vllm-project/vllm/issues/41106
out_buf, scale_buf = torch.ops.vllm.fused_inv_rope_fp8_quant_kernel(
o,
positions,
cos_sin_cache,
heads_per_group,
quant_group_size,
chunks_per_head,
nope_dim,
rope_dim // 2,
tma_aligned_scales,
fp8_max,
tma_aligned_T,
num_tokens,
n_groups,
d,
scale_inner,
quantize,
)
output = out_buf.transpose(0, 1)
scales = scale_buf.transpose(0, 1) if quantize else scale_buf
return output, scales
def _fused_inv_rope_fp8_quant_kernel_impl(
o: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
heads_per_group: int,
quant_group_size: int,
chunks_per_head: int,
nope_dim: int,
half_rope: int,
tma_aligned_scales: bool,
fp8_max: float,
tma_aligned_T: int,
num_tokens: int,
n_groups: int,
d: int,
scale_inner: int,
quantize: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
scale_dtype = torch.int32 if tma_aligned_scales else torch.float32
out_buf = torch.empty(
(n_groups, num_tokens, d),
dtype=torch.float8_e4m3fn if quantize else o.dtype,
device=o.device,
)
if quantize:
scale_buf = torch.empty(
n_groups * scale_inner * tma_aligned_T,
dtype=scale_dtype,
device=o.device,
).as_strided(
(n_groups, num_tokens, scale_inner),
(scale_inner * tma_aligned_T, 1, tma_aligned_T),
)
else:
scale_buf = torch.empty(0, dtype=scale_dtype, device=o.device)
grid = (tma_aligned_T, n_groups * heads_per_group)
launch_pdl = current_platform.is_arch_support_pdl()
_FUSED_INV_ROPE_FP8_QUANT_KERNEL(
o,
positions,
cos_sin_cache,
out_buf,
scale_buf,
num_tokens,
heads_per_group=heads_per_group,
quant_group_size=quant_group_size,
chunks_per_head=chunks_per_head,
nope_dim=nope_dim,
half_rope=half_rope,
tma_aligned_scales=tma_aligned_scales,
quantize=quantize,
fp8_max=fp8_max,
launch_pdl=launch_pdl,
grid=grid,
)
return out_buf, scale_buf
def _fused_inv_rope_fp8_quant_kernel_fake(
o: torch.Tensor,
positions: torch.Tensor,
cos_sin_cache: torch.Tensor,
heads_per_group: int,
quant_group_size: int,
chunks_per_head: int,
nope_dim: int,
half_rope: int,
tma_aligned_scales: bool,
fp8_max: float,
tma_aligned_T: int,
num_tokens: int,
n_groups: int,
d: int,
scale_inner: int,
quantize: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
scale_dtype = torch.int32 if tma_aligned_scales else torch.float32
out_buf = torch.empty(
(n_groups, num_tokens, d),
dtype=torch.float8_e4m3fn if quantize else o.dtype,
device=o.device,
)
if not quantize:
return out_buf, torch.empty(0, dtype=scale_dtype, device=o.device)
scale_buf = torch.empty(
n_groups * scale_inner * tma_aligned_T,
dtype=scale_dtype,
device=o.device,
).as_strided(
(n_groups, num_tokens, scale_inner),
(scale_inner * tma_aligned_T, 1, tma_aligned_T),
)
return out_buf, scale_buf
direct_register_custom_op(
op_name="fused_inv_rope_fp8_quant_kernel",
op_func=_fused_inv_rope_fp8_quant_kernel_impl,
fake_impl=_fused_inv_rope_fp8_quant_kernel_fake,
)
_FUSED_INV_ROPE_FP8_QUANT_KERNEL = FusedInvRopeFP8QuantKernel()
@@ -1,340 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused MTP-input RMSNorm: enorm (with mask-zero at position 0) + hnorm.
Replaces the eager sequence at the top of the MTP draft forward:
inputs_embeds = torch.where(positions.unsqueeze(-1) == 0, 0, inputs_embeds)
inputs_embeds = self.enorm(inputs_embeds)
previous_hidden_states = previous_hidden_states.view(-1, hc_mult, H)
previous_hidden_states = self.hnorm(previous_hidden_states)
which lowers to ~6 small kernels (CompareEq, where, Fill, enorm rms_norm,
hnorm rms_norm, plus aten elementwise helpers) on the breakable-cudagraph
path. Math is preserved: positions==0 → masked row → zero RMS output
regardless of weight.
A single grid (T, hc_mult+1) drives both norms: task 0 is enorm on
inputs_embeds[token, :], task k+1 is hnorm on previous_hidden_states[token, k, :].
"""
from dataclasses import dataclass
from typing import Any
import torch
from vllm.model_executor.warmup.jit_warmup import kernel_launcher
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
LaunchSpec,
TritonWarmupTensor,
VllmTritonJitKernel,
)
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import next_power_of_2
@triton.jit
def _rmsnorm_row(
x,
w_ptr,
out_row_ptr,
block,
mask,
eps,
HIDDEN: tl.constexpr,
):
x = x.to(tl.float32)
variance = tl.sum(x * x, axis=0) / HIDDEN
rrms = tl.rsqrt(variance + eps)
w = tl.load(w_ptr + block, mask=mask, other=0.0).to(tl.float32)
y = x * rrms * w
tl.store(out_row_ptr + block, y.to(out_row_ptr.dtype.element_ty), mask=mask)
class FusedMTPInputRMSNormKernel(
VllmTritonJitKernel["FusedMTPInputRMSNormKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
dtype: torch.dtype
hidden: int
hc_mult: int
block_size: int
eps: float
@staticmethod
@triton.jit
def kernel(
inputs_embeds_ptr,
positions_ptr,
prev_hidden_ptr,
enorm_weight_ptr,
hnorm_weight_ptr,
enorm_out_ptr,
hnorm_out_ptr,
eps,
HIDDEN: tl.constexpr,
HC_MULT: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# int64 token index so per-token offsets don't overflow int32 at
# large num_tokens (matches the convention in fused_q_kv_rmsnorm).
token_idx = tl.program_id(0).to(tl.int64)
pid_task = tl.program_id(1)
block = tl.arange(0, BLOCK_SIZE)
mask = block < HIDDEN
if pid_task == 0:
# enorm path: load inputs_embeds[token, :] then zero-mask at pos==0.
# Math is preserved: pos==0 → x=0 → variance=0 → RMSNorm output is 0
# regardless of weight, matching torch.where(pos==0, 0, x) + RMSNorm.
pos = tl.load(positions_ptr + token_idx)
keep = pos != 0
x = tl.load(
inputs_embeds_ptr + token_idx * HIDDEN + block, mask=mask, other=0.0
)
x = tl.where(keep, x, 0.0)
_rmsnorm_row(
x,
enorm_weight_ptr,
enorm_out_ptr + token_idx * HIDDEN,
block,
mask,
eps,
HIDDEN,
)
else:
# hnorm path: load prev_hidden[token, slot, :].
slot = pid_task - 1
row_offset = (token_idx * HC_MULT + slot) * HIDDEN
x = tl.load(prev_hidden_ptr + row_offset + block, mask=mask, other=0.0)
_rmsnorm_row(
x,
hnorm_weight_ptr,
hnorm_out_ptr + row_offset,
block,
mask,
eps,
HIDDEN,
)
def dispatch( # type: ignore[override]
self,
*,
dtype: torch.dtype,
hidden: int,
hc_mult: int,
eps: float,
) -> CompileKey:
return self.CompileKey(
dtype=dtype,
hidden=hidden,
hc_mult=hc_mult,
block_size=next_power_of_2(hidden),
eps=eps,
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
hf_config = vllm_config.model_config.hf_config
if int(getattr(hf_config, "num_nextn_predict_layers", 0) or 0) <= 0:
return []
return self._trace_dispatch(self.dispatch)(
dtype=vllm_config.model_config.dtype,
hidden=int(hf_config.hidden_size),
hc_mult=int(hf_config.hc_mult),
eps=float(hf_config.rms_norm_eps),
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
return dict(
inputs_embeds=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.hidden),
),
positions=TritonWarmupTensor(torch.int64),
previous_hidden_states=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.hc_mult, compile_key.hidden),
),
enorm_weight=TritonWarmupTensor(
compile_key.dtype,
shape=(compile_key.hidden,),
),
hnorm_weight=TritonWarmupTensor(
compile_key.dtype,
shape=(compile_key.hidden,),
),
_outputs=(
TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.hidden),
),
TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.hc_mult, compile_key.hidden),
),
),
eps=compile_key.eps,
hc_mult=compile_key.hc_mult,
)
@kernel_launcher
def __call__(
self,
inputs_embeds: torch.Tensor,
positions: torch.Tensor,
previous_hidden_states: torch.Tensor,
enorm_weight: torch.Tensor,
hnorm_weight: torch.Tensor,
eps: float,
hc_mult: int,
*,
_outputs: tuple[Any, Any] | None = None,
) -> LaunchSpec:
num_tokens, hidden = inputs_embeds.shape
if _outputs is None:
assert inputs_embeds.ndim == 2
assert previous_hidden_states.ndim == 3
assert previous_hidden_states.shape[1] == hc_mult
assert inputs_embeds.shape[0] == previous_hidden_states.shape[0], (
"token dim mismatch"
)
assert (
hidden
== previous_hidden_states.shape[2]
== enorm_weight.shape[0]
== hnorm_weight.shape[0]
)
assert (
inputs_embeds.is_contiguous() and previous_hidden_states.is_contiguous()
)
assert enorm_weight.is_contiguous() and hnorm_weight.is_contiguous()
_outputs = (
torch.empty_like(inputs_embeds),
torch.empty_like(previous_hidden_states),
)
enorm_out, hnorm_out = _outputs
grid = None if num_tokens == 0 else (num_tokens, hc_mult + 1)
return (
grid,
dict(
prev_hidden_ptr=previous_hidden_states,
enorm_out_ptr=enorm_out,
hnorm_out_ptr=hnorm_out,
HIDDEN=hidden,
HC_MULT=hc_mult,
BLOCK_SIZE=next_power_of_2(hidden),
),
_outputs,
)
class MTPSharedHeadRMSNormKernel(
VllmTritonJitKernel["MTPSharedHeadRMSNormKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
dtype: torch.dtype
hidden: int
block_size: int
eps: float
@staticmethod
@triton.jit
def kernel(
x_ptr,
weight_ptr,
out_ptr,
eps,
HIDDEN: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
token_idx = tl.program_id(0).to(tl.int64)
block = tl.arange(0, BLOCK_SIZE)
mask = block < HIDDEN
x = tl.load(x_ptr + token_idx * HIDDEN + block, mask=mask, other=0.0)
_rmsnorm_row(
x,
weight_ptr,
out_ptr + token_idx * HIDDEN,
block,
mask,
eps,
HIDDEN,
)
def dispatch( # type: ignore[override]
self,
*,
dtype: torch.dtype,
hidden: int,
eps: float,
) -> CompileKey:
return self.CompileKey(
dtype=dtype,
hidden=hidden,
block_size=next_power_of_2(hidden),
eps=eps,
)
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
hf_config = vllm_config.model_config.hf_config
if int(getattr(hf_config, "num_nextn_predict_layers", 0) or 0) <= 0:
return []
return self._trace_dispatch(self.dispatch)(
dtype=vllm_config.model_config.dtype,
hidden=int(hf_config.hidden_size),
eps=float(hf_config.rms_norm_eps),
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
return dict(
hidden_states=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.hidden),
),
weight=TritonWarmupTensor(
compile_key.dtype,
shape=(compile_key.hidden,),
),
_output=TritonWarmupTensor(
compile_key.dtype,
shape=(1, compile_key.hidden),
),
eps=compile_key.eps,
)
@kernel_launcher
def __call__(
self,
hidden_states: torch.Tensor,
weight: torch.Tensor,
eps: float,
*,
_output: Any | None = None,
) -> LaunchSpec:
num_tokens, hidden = hidden_states.shape
if _output is None:
assert hidden_states.ndim == 2
assert hidden_states.is_contiguous()
assert weight.is_contiguous()
_output = torch.empty_like(hidden_states)
grid = None if num_tokens == 0 else (num_tokens,)
return (
grid,
dict(
x_ptr=hidden_states,
out_ptr=_output,
HIDDEN=hidden,
BLOCK_SIZE=next_power_of_2(hidden),
),
_output,
)
_FUSED_MTP_INPUT_RMSNORM_KERNEL = FusedMTPInputRMSNormKernel()
_MTP_SHARED_HEAD_RMSNORM_KERNEL = MTPSharedHeadRMSNormKernel()
@@ -1,193 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import Any
import torch
from vllm.model_executor.warmup.jit_warmup import kernel_launcher
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
LaunchSpec,
TritonWarmupTensor,
VllmTritonJitKernel,
)
from vllm.triton_utils import tl, triton
from vllm.utils.math_utils import next_power_of_2
class SavePartialStatesKernel(
VllmTritonJitKernel["SavePartialStatesKernel.CompileKey"]
):
@dataclass(frozen=True)
class CompileKey:
head_size: int
triton_block_size: int
state_width: int
compress_ratio: int
kv_stride: int
score_stride: int
ape_stride: int
state_cache_stride0: int
state_cache_stride1: int
block_size: int
@staticmethod
@triton.jit
def kernel(
kv_ptr,
kv_stride,
score_ptr,
score_stride,
ape_ptr,
ape_stride,
positions_ptr,
state_cache_ptr,
state_cache_stride0,
state_cache_stride1,
slot_mapping_ptr,
block_size,
HEAD_SIZE: tl.constexpr,
TRITON_BLOCK_SIZE: tl.constexpr,
# state_cache last dim packs [kv_state, score_state], each STATE_WIDTH wide.
STATE_WIDTH: tl.constexpr,
COMPRESS_RATIO: tl.constexpr,
):
token_idx = tl.program_id(0)
slot_id = tl.load(slot_mapping_ptr + token_idx)
# Skip padded / invalid tokens (slot_id == -1 is the PAD sentinel used
# by vLLM). During CUDA graph replay the batch may contain padding
# tokens whose slot_mapping is -1; writing to kv_state[-1] would be an
# illegal memory access.
if slot_id < 0:
return
block_idx = slot_id // block_size
pos_in_block = slot_id % block_size
base_ptr = (
state_cache_ptr
+ block_idx * state_cache_stride0
+ pos_in_block * state_cache_stride1
)
block = tl.arange(0, TRITON_BLOCK_SIZE)
mask = block < HEAD_SIZE
kv = tl.load(kv_ptr + token_idx * kv_stride + block, mask=mask)
tl.store(base_ptr + block, kv, mask=mask)
# Fused: score += ape[position % compress_ratio]
position = tl.load(positions_ptr + token_idx)
ape_row = position % COMPRESS_RATIO
ape = tl.load(ape_ptr + ape_row * ape_stride + block, mask=mask)
score = tl.load(score_ptr + token_idx * score_stride + block, mask=mask)
tl.store(
base_ptr + STATE_WIDTH + block,
score + ape,
mask=mask,
)
def dispatch( # type: ignore[override]
self,
*,
head_size: int,
**compile_key_fields: int,
) -> CompileKey:
return self.CompileKey(
**compile_key_fields,
head_size=head_size,
triton_block_size=next_power_of_2(head_size),
)
def get_warmup_keys(
self,
*,
head_dim: int,
compress_ratio: int,
) -> list[CompileKey]:
if head_dim <= 0 or compress_ratio not in (4, 128):
return []
coefficient = 2 if compress_ratio == 4 else 1
return self._trace_dispatch(self.dispatch)(
head_size=coefficient * head_dim,
state_width=coefficient * head_dim,
compress_ratio=compress_ratio,
kv_stride=2 * coefficient * head_dim,
score_stride=2 * coefficient * head_dim,
ape_stride=coefficient * head_dim,
state_cache_stride0=8 * coefficient * head_dim,
state_cache_stride1=2 * coefficient * head_dim,
block_size=4 if compress_ratio == 4 else 8,
)
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
return dict(
kv=TritonWarmupTensor(
torch.float32,
shape=(1, compile_key.head_size),
strides=(compile_key.kv_stride, 1),
),
score=TritonWarmupTensor(
torch.float32,
shape=(1, 1),
strides=(compile_key.score_stride, 1),
),
ape=TritonWarmupTensor(
torch.float32,
shape=(1, 1),
strides=(compile_key.ape_stride, 1),
),
positions=TritonWarmupTensor(torch.int64),
state_cache=TritonWarmupTensor(
torch.float32,
shape=(1, 1, compile_key.state_width),
strides=(
compile_key.state_cache_stride0,
compile_key.state_cache_stride1,
1,
),
),
slot_mapping=TritonWarmupTensor(torch.int64),
block_size=compile_key.block_size,
state_width=compile_key.state_width,
compress_ratio=compile_key.compress_ratio,
)
@kernel_launcher
def __call__(
self,
kv: torch.Tensor,
score: torch.Tensor,
ape: torch.Tensor,
positions: torch.Tensor,
state_cache: torch.Tensor,
slot_mapping: torch.Tensor,
block_size: int,
state_width: int,
compress_ratio: int,
pdl_kwargs: dict | None = None,
) -> LaunchSpec:
"""Write packed [kv, score+ape] partial states into the compressor cache.
One program per token; pads (slot_id == -1) are skipped.
"""
num_actual = slot_mapping.shape[0]
head_size = kv.shape[-1]
return (num_actual,), dict(
kv_stride=kv.stride(0),
score_stride=score.stride(0),
ape_stride=ape.stride(0),
state_cache_stride0=state_cache.stride(0),
state_cache_stride1=state_cache.stride(1),
block_size=block_size,
HEAD_SIZE=head_size,
TRITON_BLOCK_SIZE=next_power_of_2(head_size),
STATE_WIDTH=state_width,
COMPRESS_RATIO=compress_ratio,
**(pdl_kwargs or {}),
)
_SAVE_PARTIAL_STATES_KERNEL = SavePartialStatesKernel()
-52
View File
@@ -1,52 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DeepseekV4 rotary embedding initialization."""
from vllm.model_executor.layers.rotary_embedding import get_rope
from vllm.model_executor.layers.rotary_embedding.base import RotaryEmbedding
def build_deepseek_v4_rope(
config,
*,
head_dim: int,
rope_head_dim: int,
max_position_embeddings: int,
compress_ratio: int,
) -> RotaryEmbedding:
rope_parameters = config.rope_parameters
# Newer checkpoints nest per-layer-type rope dicts ({"main", "compress"});
# older ones ship a single flat dict shared by all layer types.
if isinstance(rope_parameters.get("main"), dict) and isinstance(
rope_parameters.get("compress"), dict
):
key = "compress" if compress_ratio > 1 else "main"
rope_parameters = dict(rope_parameters[key])
else:
rope_parameters = dict(rope_parameters)
rope_parameters["rope_theta"] = (
config.compress_rope_theta if compress_ratio > 1 else config.rope_theta
)
if compress_ratio > 1 and rope_parameters["rope_type"] != "default":
# YaRN applies only to compressor (CSA/HCA) layers.
rope_parameters["rope_type"] = (
"deepseek_llama_scaling"
if rope_parameters.get("attention_factor") == 1.0
else "deepseek_yarn"
)
else:
# Sliding-window layers use plain RoPE (theta=rope_theta, no YaRN).
rope_parameters["rope_type"] = "deepseek_yarn"
rope_parameters["factor"] = 1.0
rope_parameters["original_max_position_embeddings"] = max_position_embeddings
rope_parameters["mscale"] = 0 # Disable mscale
rope_parameters["mscale_all_dim"] = 0 # Disable mscale
rope_parameters["is_deepseek_v4"] = True
rope_parameters["rope_dim"] = rope_head_dim
return get_rope(
head_dim,
max_position=max_position_embeddings,
rope_parameters=rope_parameters,
is_neox_style=False,
)
-476
View File
@@ -1,476 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DeepSeek-V4 vision tower (ViT + aligner) with TP-sharded linears.
Ported from the official reference implementation
(deepseek-ai/DeepSeek-V4-Flash-Vision-Exp). Weight names match the HF
checkpoint so no renaming is needed at load time. Attention and MLP weights
are tensor-parallel sharded (replicated when the vision head count is not
divisible by TP size, or under ``--mm-encoder-tp-mode data``); the patch
embed and norms are replicated, so the residual stream is full-width on
every rank.
"""
import itertools
from functools import lru_cache
import torch
import torch.nn.functional as F
from torch import nn
from vllm.distributed import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
tensor_model_parallel_all_gather,
)
from vllm.model_executor.layers.activation import SiluAndMul
from vllm.model_executor.layers.attention.mm_encoder_attention import (
MMEncoderAttention,
)
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
MergedColumnParallelLinear,
QKVParallelLinear,
ReplicatedLinear,
RowParallelLinear,
)
from vllm.model_executor.models.vision import (
get_load_balance_assignment,
is_vit_use_data_parallel,
)
from vllm.utils.torch_utils import async_tensor_h2d
def _compute_vision_cos_sin(
n_h: int, n_w: int, dim: int, theta: float
) -> tuple[torch.Tensor, torch.Tensor]:
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
hpos = torch.arange(n_h).unsqueeze(1).expand(n_h, n_w)
wpos = torch.arange(n_w).unsqueeze(0).expand(n_h, n_w)
freqs = torch.stack([hpos, wpos], dim=-1).reshape(-1, 2, 1).float()
freqs = (freqs * inv_freq).flatten(1)
return freqs.cos().unsqueeze(1), freqs.sin().unsqueeze(1)
@lru_cache(8)
def get_vision_cos_sin(
n_h: int, n_w: int, dim: int, theta: float
) -> tuple[torch.Tensor, torch.Tensor]:
return _compute_vision_cos_sin(n_h, n_w, dim, theta)
def apply_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
dtype = x.dtype
x1, x2 = x.float().chunk(2, dim=-1)
return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1).to(dtype)
class DeepseekV4RMSNorm(nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim, dtype=torch.float32))
def forward(self, x: torch.Tensor) -> torch.Tensor:
dtype = x.dtype
x = x.float()
x = x * torch.rsqrt(x.square().mean(-1, keepdim=True) + self.eps)
return (self.weight * x).to(dtype)
class DeepseekV4PatchEmbed(nn.Module):
def __init__(self, config):
super().__init__()
# Replicated: the residual stream is full-width on every rank.
self.proj = ReplicatedLinear(
3 * config.vision_patch_size**2,
config.vision_dim,
bias=True,
quant_config=None,
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out, _ = self.proj(x.flatten(1))
return out
class DeepseekV4VisionAttention(nn.Module):
def __init__(self, config, prefix: str = ""):
super().__init__()
# Convention from minimax_m3/siglip: compute the TP/DP choice locally
# instead of threading a flag through every constructor.
use_data_parallel = is_vit_use_data_parallel(config.vision_n_heads)
self.tp_size = (
1 if use_data_parallel else get_tensor_model_parallel_world_size()
)
self.n_heads = config.vision_n_heads // self.tp_size
self.head_dim = config.vision_dim // config.vision_n_heads
self.hidden_size = config.vision_dim
self.wqkv = QKVParallelLinear(
config.vision_dim,
self.head_dim,
config.vision_n_heads,
bias=True,
quant_config=None,
prefix=f"{prefix}.wqkv",
disable_tp=use_data_parallel,
)
self.wo = RowParallelLinear(
config.vision_dim,
config.vision_dim,
bias=True,
quant_config=None,
prefix=f"{prefix}.wo",
disable_tp=use_data_parallel,
)
self.attn = MMEncoderAttention(
num_heads=self.n_heads,
head_size=self.head_dim,
prefix=f"{prefix}.attn",
)
def forward(
self,
x: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
cu_seqlens: torch.Tensor | None = None,
max_seqlen: torch.Tensor | None = None,
) -> torch.Tensor:
n = x.size(0)
qkv, _ = self.wqkv(x)
q, k, v = (t.view(n, self.n_heads, self.head_dim) for t in qkv.chunk(3, -1))
q = apply_rotary(q, cos, sin).unsqueeze(0) # (b=1, n, h, d)
k = apply_rotary(k, cos, sin).unsqueeze(0)
# Dense (cu_seqlens=None): one image per call. Varlen (cu_seqlens
# set): packed multi-image batch for encoder CUDA graph replay.
o = self.attn(
q, k, v.unsqueeze(0), cu_seqlens=cu_seqlens, max_seqlen=max_seqlen
)
out, _ = self.wo(o.reshape(n, -1))
return out
class DeepseekV4VisionMLP(nn.Module):
def __init__(self, config, prefix: str = ""):
super().__init__()
use_data_parallel = is_vit_use_data_parallel(config.vision_n_heads)
self.w1 = MergedColumnParallelLinear(
config.vision_dim,
[config.vision_inter_dim] * 2,
bias=False,
quant_config=None,
prefix=f"{prefix}.w1",
disable_tp=use_data_parallel,
)
self.w2 = RowParallelLinear(
config.vision_inter_dim,
config.vision_dim,
bias=False,
quant_config=None,
prefix=f"{prefix}.w2",
disable_tp=use_data_parallel,
)
self.act_fn = SiluAndMul()
def forward(self, x: torch.Tensor) -> torch.Tensor:
gate_up, _ = self.w1(x)
out, _ = self.w2(self.act_fn(gate_up))
return out
class DeepseekV4VisionBlock(nn.Module):
def __init__(self, config, prefix: str = ""):
super().__init__()
self.norm1 = DeepseekV4RMSNorm(config.vision_dim)
self.attn = DeepseekV4VisionAttention(config, prefix=f"{prefix}.attn")
self.norm2 = DeepseekV4RMSNorm(config.vision_dim)
self.mlp = DeepseekV4VisionMLP(config, prefix=f"{prefix}.mlp")
def forward(
self,
x: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
cu_seqlens: torch.Tensor | None = None,
max_seqlen: torch.Tensor | None = None,
) -> torch.Tensor:
x = x + self.attn(self.norm1(x), cos, sin, cu_seqlens, max_seqlen)
return x + self.mlp(self.norm2(x))
class DeepseekV4ViT(nn.Module):
"""DeepSeek-V4 ViT: full bidirectional attention per image, 2D RoPE."""
def __init__(self, config):
super().__init__()
self.rope_dim = config.vision_dim // config.vision_n_heads // 2
self.rope_theta = config.vision_rope_theta
self.patch_embed = DeepseekV4PatchEmbed(config)
self.blocks = nn.ModuleList(
[
DeepseekV4VisionBlock(config, prefix=f"blocks.{i}")
for i in range(config.vision_n_layers)
]
)
self.norm = DeepseekV4RMSNorm(config.vision_dim)
def forward(
self, patches: torch.Tensor, n_vit_h: int, n_vit_w: int
) -> torch.Tensor:
x = self.patch_embed(patches)
cos, sin = get_vision_cos_sin(n_vit_h, n_vit_w, self.rope_dim, self.rope_theta)
cos = async_tensor_h2d(cos, x.device)
sin = async_tensor_h2d(sin, x.device)
for block in self.blocks:
x = block(x, cos, sin)
return self.norm(x)
def forward_packed(
self,
patches: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
cu_seqlens: torch.Tensor,
max_seqlen: torch.Tensor,
) -> torch.Tensor:
"""Varlen path for encoder CUDA graphs: multiple images packed along
rows, per-image attention via ``cu_seqlens``, RoPE tables precomputed
on device. Pure-tensor (no host reads, no H2D), safe to capture."""
x = self.patch_embed(patches)
for block in self.blocks:
x = block(x, cos, sin, cu_seqlens, max_seqlen)
return self.norm(x)
def build_packed_vit_metadata(
grids: list[list[int]] | list[tuple[int, int]],
*,
rope_dim: int,
rope_theta: float,
device: torch.device,
max_seqlen_override: int | None = None,
cached: bool = True,
) -> dict[str, torch.Tensor]:
"""Precompute packed-batch ViT metadata for ``DeepseekV4ViT.forward_packed``.
Args:
grids: ``[n_vit_h, n_vit_w]`` per image, in packing order.
rope_dim: RoPE embedding dimension of the ViT.
rope_theta: RoPE base frequency of the ViT.
device: Device for the returned tensors (except ``max_seqlen``,
which stays on the host).
max_seqlen_override: Worst-case value baked in at CUDA graph capture
(the attention wrapper reads ``max_seqlen`` on the host, so the
capture-time value becomes a graph constant).
cached: Use the shared ``lru_cache`` for RoPE tables. Capture-time
dummy grids pass ``False`` to avoid evicting real entries.
"""
cos_sin = get_vision_cos_sin if cached else _compute_vision_cos_sin
cos_list: list[torch.Tensor] = []
sin_list: list[torch.Tensor] = []
cu_seqlens = [0]
max_seqlen = 0
for n_h, n_w in grids:
cos, sin = cos_sin(n_h, n_w, rope_dim, rope_theta)
cos_list.append(cos)
sin_list.append(sin)
n = n_h * n_w
cu_seqlens.append(cu_seqlens[-1] + n)
max_seqlen = max(max_seqlen, n)
if cos_list:
cos = async_tensor_h2d(torch.cat(cos_list), device)
sin = async_tensor_h2d(torch.cat(sin_list), device)
else:
cos = torch.zeros((0, 1, rope_dim), dtype=torch.float32, device=device)
sin = torch.zeros((0, 1, rope_dim), dtype=torch.float32, device=device)
if max_seqlen_override is not None:
max_seqlen = max_seqlen_override
return {
"vit_cos": cos,
"vit_sin": sin,
"cu_seqlens": async_tensor_h2d(cu_seqlens, device, dtype=torch.int32),
# Read on the host by the attention wrapper; keep on CPU.
"max_seqlen": torch.tensor(max_seqlen, dtype=torch.int32),
}
def build_packed_merge_metadata(
grids: list[list[int]] | list[tuple[int, int]],
downsample_ratio: int,
*,
device: torch.device,
dtype: torch.dtype,
) -> dict[str, torch.Tensor]:
"""Gather indices/mask for ``DeepseekV4Aligner.forward_packed``.
For each aligner output row, the ``r x r`` source patch rows in the
packed ViT output; positions past the image edge (the eager path pads
them with zeros) get mask 0 and a clamped in-range index.
"""
r = downsample_ratio
idx_list: list[torch.Tensor] = []
mask_list: list[torch.Tensor] = []
offset = 0
for n_h, n_w in grids:
rows = -(-n_h // r)
cols = -(-n_w // r)
bi = torch.arange(rows).repeat_interleave(cols)
bj = torch.arange(cols).repeat(rows)
di = torch.arange(r).repeat_interleave(r)
dj = torch.arange(r).repeat(r)
hi = bi[:, None] * r + di[None, :]
wj = bj[:, None] * r + dj[None, :]
valid = (hi < n_h) & (wj < n_w)
idx = offset + hi.clamp(max=n_h - 1) * n_w + wj.clamp(max=n_w - 1)
idx_list.append(idx)
mask_list.append(valid)
offset += n_h * n_w
if idx_list:
merge_idx = async_tensor_h2d(torch.cat(idx_list), device)
merge_mask = async_tensor_h2d(
torch.cat(mask_list).unsqueeze(-1), device, dtype=dtype
)
else:
merge_idx = torch.zeros((0, r * r), dtype=torch.int64, device=device)
merge_mask = torch.zeros((0, r * r, 1), dtype=dtype, device=device)
return {"merge_idx": merge_idx, "merge_mask": merge_mask}
class DeepseekV4Aligner(nn.Module):
"""Spatial merge (downsample_ratio x downsample_ratio) + MLP projector."""
def __init__(self, config):
super().__init__()
use_data_parallel = is_vit_use_data_parallel(config.vision_n_heads)
self.downsample_ratio = config.vision_downsample_ratio
self.out_dim = config.hidden_size
in_dim = config.vision_dim * self.downsample_ratio**2
self.w1 = ColumnParallelLinear(
in_dim,
config.hidden_size,
bias=True,
quant_config=None,
disable_tp=use_data_parallel,
)
self.w2 = RowParallelLinear(
config.hidden_size,
config.hidden_size,
bias=True,
quant_config=None,
disable_tp=use_data_parallel,
)
def forward(self, x: torch.Tensor, n_vit_h: int, n_vit_w: int) -> torch.Tensor:
r = self.downsample_ratio
x = x.view(n_vit_h, n_vit_w, -1).permute(2, 0, 1)
x = F.pad(x, (0, -n_vit_w % r, 0, -n_vit_h % r))
x = F.unfold(x.unsqueeze(0), r, stride=r).squeeze(0).transpose(0, 1)
hidden, _ = self.w1(x)
out, _ = self.w2(F.gelu(hidden))
return out
def forward_packed(
self,
x: torch.Tensor,
merge_idx: torch.Tensor,
merge_mask: torch.Tensor,
) -> torch.Tensor:
"""Packed multi-image path for encoder CUDA graphs.
``merge_idx``/``merge_mask`` come from ``build_packed_merge_metadata``;
gather+mask reproduces the eager ``F.pad`` + ``F.unfold`` merge
exactly (unfold rows are channel-major, so the gathered patch rows
are transposed before flattening).
"""
r2 = self.downsample_ratio**2
m = merge_idx.shape[0]
gathered = (x[merge_idx] * merge_mask).view(m, r2, -1)
gathered = gathered.permute(0, 2, 1).reshape(m, -1)
hidden, _ = self.w1(gathered)
out, _ = self.w2(F.gelu(hidden))
return out
def run_dp_sharded_vision_tower(
vision_model: DeepseekV4ViT,
aligner: DeepseekV4Aligner,
patches: torch.Tensor,
vit_grid: list[list[int]],
) -> list[torch.Tensor]:
"""Run the ViT + aligner with images sharded across TP ranks.
Every rank holds the full tower weights (``--mm-encoder-tp-mode data``)
and receives the full ``patches`` batch. Images are assigned to ranks by
patch count (greedy load balancing), each rank encodes only its share,
and per-image embeddings are exchanged with one padded all-gather and
returned in the original image order.
Args:
vision_model: The (weight-replicated) ViT tower.
aligner: The (weight-replicated) spatial-merge projector.
patches: ``(sum(n_vit_h * n_vit_w), 3, p, p)`` patches of all images.
vit_grid: ``[n_vit_h, n_vit_w]`` per image.
Returns:
One ``(n_aligner_rows, hidden_size)`` embedding tensor per image.
"""
tp_size = get_tensor_model_parallel_world_size()
tp_rank = get_tensor_model_parallel_rank()
sizes = [h * w for h, w in vit_grid]
cum_patches = [0, *itertools.accumulate(sizes)]
image_to_tp_rank, gpu_sample_counts, _ = get_load_balance_assignment(sizes, tp_size)
cum_sample_counts = [0, *itertools.accumulate(gpu_sample_counts)]
# Rows the aligner emits per image: each grid dim is padded up to a
# multiple of the merge ratio before r x r patches fold into one row.
r = aligner.downsample_ratio
rows_per_image = [-(-h // r) * -(-w // r) for h, w in vit_grid]
def rank_image_idxs(g: int) -> list[int]:
return image_to_tp_rank[cum_sample_counts[g] : cum_sample_counts[g + 1]]
# All-gather needs one shape on every rank; pad each rank's packed
# output to the largest per-rank row count (computable locally).
max_rows = max(
sum(rows_per_image[i] for i in rank_image_idxs(g)) for g in range(tp_size)
)
local_embeds = [
aligner(
vision_model(
patches[cum_patches[i] : cum_patches[i + 1]],
vit_grid[i][0],
vit_grid[i][1],
),
vit_grid[i][0],
vit_grid[i][1],
)
for i in rank_image_idxs(tp_rank)
]
if local_embeds:
embeds_local = torch.cat(local_embeds, dim=0)
else:
embeds_local = patches.new_zeros((0, aligner.out_dim))
if embeds_local.shape[0] < max_rows:
embeds_local = torch.cat(
[
embeds_local,
embeds_local.new_zeros(
(max_rows - embeds_local.shape[0], embeds_local.shape[1])
),
],
dim=0,
)
gathered = tensor_model_parallel_all_gather(embeds_local.contiguous(), dim=0)
out: list[torch.Tensor] = [None] * len(vit_grid) # type: ignore[list-item]
for g in range(tp_size):
offset = g * max_rows
for i in rank_image_idxs(g):
out[i] = gathered[offset : offset + rows_per_image[i]]
offset += rows_per_image[i]
return out
-393
View File
@@ -1,393 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DeepSeek-V4 vision variant (e.g. DeepSeek-V4-Flash-Vision-Exp).
Thin multimodal wrapper around the text-only ``DeepseekV4ForCausalLM``:
- ``vision`` ViT + ``aligner`` produce per-image embeddings for the IMAGE
sentinel positions; four learned vectors (``image_start`` / ``image_pad`` /
``image_newline`` / ``image_end``) fill the remaining sentinel positions.
- Image placeholders (``<|deepseek_image|>``) are expanded by the processor
in ``common/mm_preprocess.py`` into sentinel blocks borrowing reserved
in-vocab tokens ``<|place_holder_mm_span_0431|>``..``_0435|>``
(see ``common/vision.py`` for the tower itself).
- Merged embeddings enter the text model via ``inputs_embeds``, i.e. before
its hyper-connection stream expansion. Raw ``input_ids`` still flow into
the model so the MoE router can apply ``bias_vl`` to image tokens
(``requires_raw_input_tokens``).
"""
from collections.abc import Iterable
import torch
from torch import nn
from vllm.model_executor.models.interfaces import (
MultiModalEmbeddings,
SupportsEagle3,
SupportsLoRA,
SupportsMultiModal,
SupportsPP,
)
from vllm.model_executor.models.module_mapping import MultiModelKeys
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
WeightsMapper,
init_vllm_registered_model,
maybe_prefix,
)
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.inputs import MultiModalKwargsItem
from .mm_preprocess import (
COMPRESS_PAD_TO,
IMAGE_PLACEHOLDER,
IMAGE_SENTINEL_BASE_ID,
DeepseekV4VLDummyInputsBuilder,
DeepseekV4VLMultiModalProcessor,
DeepseekV4VLProcessingInfo,
image_sentinel_mask,
)
from .vision import DeepseekV4Aligner, DeepseekV4ViT
def _make_deepseek_v4_vl_weights_mapper(
text_mapper: WeightsMapper, image_enabled: bool
) -> WeightsMapper:
"""Text-checkpoint mapping rules re-rooted under ``language_model.``."""
orig_to_new_prefix = {
src: None if dst is None else f"language_model.{dst}"
for src, dst in text_mapper.orig_to_new_prefix.items()
}
if not image_enabled:
orig_to_new_prefix.update({"vision.": None, "aligner.": None, "image_": None})
return WeightsMapper(
orig_to_new_renaming=text_mapper.orig_to_new_renaming,
orig_to_new_prefix=orig_to_new_prefix,
orig_to_new_regex=text_mapper.orig_to_new_regex,
orig_to_new_stacked=text_mapper.orig_to_new_stacked,
orig_to_new_suffix={
**text_mapper.orig_to_new_suffix,
"head.weight": "language_model.lm_head.weight",
},
orig_to_new_substr={
**text_mapper.orig_to_new_substr,
# Draft models load the checkpoint's MTP weights separately from
# the target model.
"mtp.": None,
},
)
def stream_language_model_first(
weights: Iterable[tuple[str, torch.Tensor]],
) -> Iterable[tuple[str, torch.Tensor]]:
"""Yield ``language_model.*`` weights as they arrive, then the rest.
Keeps the language model's weights in one contiguous group without
materializing the stream. Deferred weights are cloned so they do not keep
the loader's per-shard storage alive until the end of the load.
"""
rest = []
for name, tensor in weights:
if name.startswith("language_model."):
yield name, tensor
else:
rest.append((name, tensor.clone()))
yield from rest
@MULTIMODAL_REGISTRY.register_processor(
DeepseekV4VLMultiModalProcessor,
info=DeepseekV4VLProcessingInfo,
dummy_inputs=DeepseekV4VLDummyInputsBuilder,
)
class DeepseekV4ForConditionalGeneration(
nn.Module, SupportsMultiModal, SupportsPP, SupportsEagle3, SupportsLoRA
):
"""Multimodal entry point for DeepSeek-V4 checkpoints with a vision tower.
``SupportsEagle3`` (aux hidden-state plumbing for MTP/DSpark drafters)
delegates through ``language_model`` via the protocol defaults.
"""
packed_modules_mapping = {
"gate_up_proj": ["w1", "w3"],
"fused_wqa_wkv": ["wq_a", "wkv"],
"fused_wkv_wgate": ["wkv", "wgate"],
# for visual encoder
"wqkv": ["wqkv"],
"w1": ["w1"],
}
# The MoE router needs raw token ids to detect image sentinel tokens
# (borrowed reserved ids, see common/mm_preprocess.py) and apply bias_vl.
requires_raw_input_tokens = True
supports_tower_connector_lora = True
# Image spans widen the sparse-SWA window in-kernel and the placeholder
# starts with a compressor-alignment pad
mm_prefix_clamp_sliding_window = True
mm_prefix_span_leading_pad_modulus = COMPRESS_PAD_TO
@classmethod
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
if modality == "image":
return IMAGE_PLACEHOLDER
raise ValueError(f"Unsupported modality: {modality!r}")
def __init__(self, *, vllm_config, prefix: str = "") -> None:
super().__init__()
model_config = vllm_config.model_config
config = model_config.hf_config
self.config = config
self.multimodal_config = model_config.multimodal_config
assert self.multimodal_config is not None
image_enabled = (
config.vision_n_layers > 0
and self.multimodal_config.get_limit_per_prompt("image") > 0
)
with self._mark_tower_model(vllm_config, {"image"}):
self.vision: DeepseekV4ViT | None = None
self.aligner: DeepseekV4Aligner | None = None
self.image_start: nn.Parameter | None = None
self.image_end: nn.Parameter | None = None
self.image_newline: nn.Parameter | None = None
self.image_pad: nn.Parameter | None = None
if image_enabled:
self.vision = DeepseekV4ViT(config)
self.aligner = DeepseekV4Aligner(config)
for name in (
"image_start",
"image_end",
"image_newline",
"image_pad",
):
setattr(
self,
name,
nn.Parameter(
torch.empty(config.hidden_size, dtype=torch.float32)
),
)
self.vision.to(dtype=model_config.dtype)
self.aligner.to(dtype=model_config.dtype)
with self._mark_language_model(vllm_config):
# The arch convertor routes any config with a vision tower to
# this wrapper class; mark the copy handed to the text backbone
# so it resolves to DeepseekV4ForCausalLM instead of recursing
# (with_hf_config deepcopies the config, the marker survives).
config._dsv4_vl_inner = True # type: ignore[attr-defined]
try:
self.language_model = init_vllm_registered_model(
vllm_config=vllm_config,
hf_config=config,
prefix=maybe_prefix(prefix, "language_model"),
architectures=["DeepseekV4ForCausalLM"],
)
finally:
del config._dsv4_vl_inner # type: ignore[attr-defined]
# The outer mapper (see load_weights) fully resolves HF names into
# this wrapper's namespace before AutoWeightsLoader strips the
# "language_model." prefix and delegates to the child's load_weights,
# so the child's own mapper must be a no-op. Its suffix rules are not
# idempotent (e.g. "lm_head.weight".endswith("head.weight") would
# re-fire "head.weight" -> "lm_head.weight").
text_mapper = self.language_model.hf_to_vllm_mapper
self.language_model.hf_to_vllm_mapper = WeightsMapper()
self.make_empty_intermediate_tensors = ( # type: ignore[method-assign]
self.language_model.make_empty_intermediate_tensors
)
self.hf_to_vllm_mapper = _make_deepseek_v4_vl_weights_mapper(
text_mapper, image_enabled
)
self._weights_finalized = False
def _parse_and_validate_image_input(self, **kwargs: object) -> dict | None:
patches = kwargs.pop("patches", None)
if patches is None:
return None
vit_grid = kwargs.pop("vit_grid", None)
llm_grid = kwargs.pop("llm_grid", None)
perm = kwargs.pop("perm", None)
assert vit_grid is not None and llm_grid is not None and perm is not None
return {
"patches": patches,
"vit_grid": vit_grid,
"llm_grid": llm_grid,
"perm": perm,
}
def _encode_image(
self,
patches: torch.Tensor,
n_vit_h: int,
n_vit_w: int,
perm: torch.Tensor,
) -> torch.Tensor:
assert self.vision is not None and self.aligner is not None
image_embeds = self.aligner(
self.vision(patches, n_vit_h, n_vit_w), n_vit_h, n_vit_w
)
# Reorder into the N-layout block order used in the prompt.
return image_embeds[perm.to(image_embeds.device)]
def _process_image_input(
self,
patches: torch.Tensor,
vit_grid: torch.Tensor,
llm_grid: torch.Tensor,
perm: torch.Tensor,
) -> tuple[torch.Tensor, ...]:
assert self.vision is not None and self.aligner is not None
patches = patches.to(self.aligner.w1.weight.dtype)
embeds: list[torch.Tensor] = []
vit_offset = 0
llm_offset = 0
for (n_vit_h, n_vit_w), (n_llm_h, n_llm_w) in zip(
vit_grid.tolist(), llm_grid.tolist(), strict=True
):
n_vit = n_vit_h * n_vit_w
n_llm = n_llm_h * n_llm_w
embeds.append(
self._encode_image(
patches[vit_offset : vit_offset + n_vit],
n_vit_h,
n_vit_w,
perm[llm_offset : llm_offset + n_llm],
)
)
vit_offset += n_vit
llm_offset += n_llm
return tuple(embeds)
def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
image_input = self._parse_and_validate_image_input(**kwargs)
if image_input is None or self.vision is None:
return []
return self._process_image_input(
image_input["patches"],
image_input["vit_grid"],
image_input["llm_grid"],
image_input["perm"],
)
def embed_input_ids(
self,
input_ids: torch.Tensor,
multimodal_embeddings: MultiModalEmbeddings | None = None,
*,
is_multimodal: torch.Tensor | None = None,
) -> torch.Tensor:
from vllm.model_executor.models.utils import _merge_multimodal_embeddings
# All ids are in-vocab here: image-block sentinels are borrowed
# reserved tokens (their embedding rows are always overwritten below).
inputs_embeds = self.language_model.embed_input_ids(input_ids)
if self.image_start is not None:
# Branch-free sentinel overwrite: safe inside compiled/captured
# regions (no data-dependent control flow).
sentinel_mask = image_sentinel_mask(input_ids)
if is_multimodal is not None:
# IMAGE positions get vision embeddings via the merge below.
sentinel_mask = sentinel_mask & ~is_multimodal.to(input_ids.device)
table = torch.stack(
[
self.image_start,
self.image_pad,
self.image_pad,
self.image_newline,
self.image_end,
]
).to(inputs_embeds.dtype)
idx = (input_ids - IMAGE_SENTINEL_BASE_ID).clamp(0, 4)
inputs_embeds = torch.where(
sentinel_mask.unsqueeze(-1), table[idx], inputs_embeds
)
if multimodal_embeddings is None or len(multimodal_embeddings) == 0:
return inputs_embeds
assert is_multimodal is not None
return _merge_multimodal_embeddings(
inputs_embeds=inputs_embeds,
multimodal_embeddings=multimodal_embeddings,
is_multimodal=is_multimodal,
)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors=None,
inputs_embeds: torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor:
return self.language_model(
input_ids, positions, intermediate_tensors, inputs_embeds
)
def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None:
return self.language_model.compute_logits(hidden_states)
def compute_logits_local(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.language_model.compute_logits_local(hidden_states)
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
return self.language_model.get_expert_mapping()
def get_mtp_target_hidden_states(self) -> torch.Tensor | None:
"""Pre-hc_head residual stream buffer for the MTP/DSpark draft model."""
return self.language_model.get_mtp_target_hidden_states()
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
child_finalizes = getattr(
self.language_model, "finalizes_weights_during_load", True
)
mapped = self.hf_to_vllm_mapper.apply(weights)
if child_finalizes:
# A child which finalizes inside load_weights must see all of its
# weights in one contiguous delegation from AutoWeightsLoader.
mapped = stream_language_model_first(mapped)
loader = AutoWeightsLoader(self)
loaded_params = loader.load_weights(mapped)
self._weights_finalized = child_finalizes
return loaded_params
def process_weights_after_loading(self) -> None:
# Backbones such as the ROCm implementation require this to run only
# after the loader's generic per-layer quantization finalization.
if getattr(self, "_weights_finalized", False):
return
self.language_model.process_weights_after_loading()
self._weights_finalized = True
def get_mm_mapping(self) -> MultiModelKeys:
"""Get the module prefixes in the multimodal model."""
return MultiModelKeys.from_string_field(
language_model="language_model",
connector="aligner",
tower_model="vision.",
)
def get_mm_lora_token_counts(
self,
*,
modality: str,
mm_kwargs: MultiModalKwargsItem | None,
num_mm_embeds: int,
) -> tuple[int, int | None]:
if modality != "image":
raise ValueError(f"Unsupported modality: {modality!r}")
patches = mm_kwargs.get("patches") if mm_kwargs else None
if patches is not None and isinstance(patches.data, torch.Tensor):
tower_tokens = patches.data.shape[0]
else:
tower_tokens = num_mm_embeds * self.config.vision_downsample_ratio**2
return tower_tokens, num_mm_embeds