Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-09-29 12:54:18 +07:00
264 changed files with 13095 additions and 1541 deletions
+124
View File
@@ -1927,6 +1927,7 @@ class rocm_aiter_ops:
VLLM_ROCM_USE_AITER_FP8BMM: Controls FP8 batched matrix multiply.
VLLM_ROCM_USE_AITER_FP4_ASM_GEMM: Controls FP4 assembly GEMM.
VLLM_ROCM_USE_AITER_TRITON_ROPE: Controls Triton rotary embeddings.
VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA: Controls Triton sparse MLA (gfx950).
VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS: Controls shared expert fusion.
VLLM_ROCM_USE_AITER_MOE_SITUV2: SiTUv2 FlyDSL MoE activation
dtype (a16w4 | a8w4 | a4w4).
@@ -1998,6 +1999,7 @@ class rocm_aiter_ops:
_FP4_GEMM_DYNAMIC_QUANT_ASM = envs.VLLM_ROCM_USE_AITER_FP4_ASM_GEMM
# TODO: Consolidate under VLLM_ROCM_USE_AITER_ROPE
_TRITON_ROTARY_EMBED = envs.VLLM_ROCM_USE_AITER_TRITON_ROPE
_TRITON_SPARSE_MLA = envs.VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA
_MOE_SHARED_EXPERTS_ENABLED = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
_MOE_SITUV2 = _resolve_situv2_activation()
# TODO: Consolidate under _LINEAR_ENABLED
@@ -2027,6 +2029,7 @@ class rocm_aiter_ops:
cls._LINEAR_HIPBMM_ENABLED = envs.VLLM_ROCM_USE_AITER_LINEAR_HIPBMM
cls._FP4_GEMM_DYNAMIC_QUANT_ASM = envs.VLLM_ROCM_USE_AITER_FP4_ASM_GEMM
cls._TRITON_ROTARY_EMBED = envs.VLLM_ROCM_USE_AITER_TRITON_ROPE
cls._TRITON_SPARSE_MLA = envs.VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA
cls._MOE_SHARED_EXPERTS_ENABLED = envs.VLLM_ROCM_USE_AITER_FUSION_SHARED_EXPERTS
cls._MOE_SITUV2 = _resolve_situv2_activation()
_sync_aiter_situv2_moe_env()
@@ -2391,6 +2394,25 @@ class rocm_aiter_ops:
def is_triton_rotary_embed_enabled(cls) -> bool:
return cls._AITER_ENABLED and cls._TRITON_ROTARY_EMBED
@classmethod
@if_aiter_supported
def is_triton_sparse_mla_enabled(cls) -> bool:
if not cls._TRITON_SPARSE_MLA:
return False
from vllm.platforms.rocm import on_gfx950
if not cls._AITER_ENABLED:
reason = "VLLM_ROCM_USE_AITER is off"
elif not on_gfx950():
reason = "the kernel is gfx950-only"
else:
return True
logger.warning_once(
"VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA is set, but %s; ignoring it.",
reason,
)
return False
@classmethod
@if_aiter_supported
def is_triton_gemm_enabled(cls) -> bool:
@@ -3137,6 +3159,57 @@ class rocm_aiter_ops:
) -> tuple[torch.Tensor, torch.Tensor]:
return torch.ops.vllm.rocm_aiter_fused_topk(x, router_logits, top_k, gate_up)
@staticmethod
def triton_sparse_mla_fwd(
q: torch.Tensor,
kv_buffer: torch.Tensor,
o: torch.Tensor,
sm_scale: float,
kv_indptr: torch.Tensor,
kv_indices: torch.Tensor,
kv_lora_rank: int = 512,
qk_rope_head_dim: int = 64,
q_scale: torch.Tensor | None = None,
kv_scale: torch.Tensor | None = None,
attn_sink: torch.Tensor | None = None,
extra_kv_buffer: torch.Tensor | None = None,
extra_kv_indptr: torch.Tensor | None = None,
extra_kv_indices: torch.Tensor | None = None,
has_invalid: bool = True,
) -> None:
"""Sparse MLA read straight from the KV cache, for prefill and decode.
kv_indices are ragged global slot ids. With has_invalid they may hold
-1, which the kernel masks; a caller whose stream never holds a
negative slot passes False, which lets the fp8 kernel stage K straight
into LDS. The cache format (bf16, per-tensor fp8, or DeepSeek V4's
paged fp8_ds_mla) is inferred from kv_buffer and kv_scale. An fp8 q
must come with its q_scale and runs both dots in fp8. The extra segment
is DeepSeek V4's second cache: SWA window in kv_buffer, top-k
compressed tokens here.
"""
from aiter.ops.triton.attention.sparse_mla import sparse_mla_fwd
fp8_q = q.dtype == FP8_DTYPE
sparse_mla_fwd(
q,
kv_buffer,
kv_indptr,
kv_indices,
sm_scale,
kv_scale=kv_scale,
kv_lora_rank=kv_lora_rank,
qk_rope_head_dim=qk_rope_head_dim,
has_invalid=has_invalid,
dot_precision="fp8" if fp8_q else "bf16",
q_scale=q_scale if fp8_q else None,
out=o,
attn_sink=attn_sink,
extra_kv=extra_kv_buffer,
extra_indptr=extra_kv_indptr,
extra_indices=extra_kv_indices,
)
@staticmethod
def mla_decode_fwd(
q: torch.Tensor,
@@ -4162,6 +4235,57 @@ class rocm_aiter_ops:
next_pre_mix.view(*outer_shape, hc_mult),
)
@staticmethod
def mhc_fused_post_pre_delayed_rms_norm(
residual: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
pre_mix: torch.Tensor | None,
sublayer_out: torch.Tensor | None,
post_layer_mix: torch.Tensor | None,
comb_res_mix: torch.Tensor | None,
norm_weight: torch.Tensor,
norm_eps: float,
residual_out: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
""":meth:`mhc_pre_delayed` with the RMSNorm of the collapse folded in.
Runs aiter's fused Triton kernel ``mhc_fused_post_pre_delayed_rmsnorm``;
the returned ``layer_input`` is already normalised with ``norm_weight`` /
``norm_eps``.
"""
from aiter.ops.triton.fusions.mhc_fused_post_pre_delayed_rmsnorm import (
mhc_fused_post_pre_delayed_rmsnorm,
)
_, post_mix, comb_mix, layer_input, next_pre_mix = (
mhc_fused_post_pre_delayed_rmsnorm(
residual,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix,
sublayer_out,
post_layer_mix,
comb_res_mix,
norm_weight,
norm_eps,
residual_out=residual_out,
)
)
return post_mix, comb_mix, layer_input, next_pre_mix
@staticmethod
def mhc_fused_post_pre_delayed_prefers_unfused(num_tokens: int) -> bool:
"""True when AITER's own heuristic favours separate post and pre.
@@ -1,21 +1,24 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Coalesce duplicate ``split_with_sizes`` nodes that operate on the same
input tensor with the same split sizes.
"""Canonicalize tensor partitions to a single ``split_with_sizes`` node.
On certain hardware/dtype combinations (e.g. B200 + FP8) the Inductor
graph may contain multiple ``split_with_sizes`` calls on the same tensor
that CSE fails to merge. This pass detects and replaces the duplicates
so that downstream pattern-matching passes (e.g. QK-Norm+RoPE fusion)
see a single split node with all users attached.
Functionalization may replay the individual outputs of a multi-output split as
contiguous ``slice`` nodes. This pass converts complete slice partitions back
to ``split_with_sizes`` and coalesces equivalent split nodes so downstream
pattern-matching passes see one canonical split with all users attached.
See Also:
- vLLM #33295 (original issue)
- vLLM #33295 (original duplicate-split issue)
- PyTorch #174472 (upstream CSE gap)
- PyTorch #194037 (multi-output views replayed as individual slices)
"""
import operator
from collections import defaultdict
from copy import copy
from dataclasses import dataclass
from typing import Any
import torch
from torch import fx
@@ -28,35 +31,177 @@ from ..vllm_inductor_pass import VllmInductorPass
logger = init_logger(__name__)
@dataclass(frozen=True)
class _SliceInfo:
node: fx.Node
dim: int
start: int
end: int
class SplitCoalescingPass(VllmInductorPass):
"""Replace duplicate ``split_with_sizes`` nodes with a single canonical
node when they share the same input tensor and split sizes."""
"""Canonicalize tensor partitions to one shared ``split_with_sizes``.
@VllmInductorPass.time_and_log
def __call__(self, graph: fx.Graph) -> None:
count = 0
A complete contiguous slice partition is rewritten from::
# Map from input tensor node -> list of split nodes seen so far.
split_nodes: dict[fx.Node, list[fx.Node]] = {}
q = slice(qkv, 0, q_size)
k = slice(qkv, q_size, q_size + kv_size)
v = slice(qkv, q_size + kv_size, q_size + 2 * kv_size)
for node in graph.nodes:
if not is_func(node, torch.ops.aten.split_with_sizes.default):
to::
qkv_split = split_with_sizes(qkv, [q_size, kv_size, kv_size])
q = qkv_split[0]
k = qkv_split[1]
v = qkv_split[2]
Equivalent splits are also coalesced from::
q = split_with_sizes(qkv, sizes)[0]
k = split_with_sizes(qkv, sizes)[1]
to::
qkv_split = split_with_sizes(qkv, sizes)
q = qkv_split[0]
k = qkv_split[1]
"""
@staticmethod
def _get_arg(node: fx.Node, index: int, name: str, default: Any) -> Any:
"""Read an FX argument by position, keyword, or schema default."""
if len(node.args) > index:
return node.args[index]
return node.kwargs.get(name, default)
@staticmethod
def _normalize_dim(dim: int, rank: int) -> int:
return dim + rank if dim < 0 else dim
@staticmethod
def _tensor_val(node: fx.Node) -> torch.Tensor | None:
value = node.meta.get("val")
return value if isinstance(value, torch.Tensor) else None
def _slice_info(self, node: fx.Node) -> _SliceInfo | None:
source = node.args[0]
source_val = self._tensor_val(source)
slice_val = self._tensor_val(node)
# in case someone forgot to set meta !
if source_val is None or slice_val is None:
return None
dim = self._normalize_dim(self._get_arg(node, 1, "dim", 0), source_val.dim())
extent = source_val.shape[dim]
# do not support dynamic slices.
if not isinstance(extent, int):
return None
start = self._get_arg(node, 2, "start", None)
end = self._get_arg(node, 3, "end", None)
step = self._get_arg(node, 4, "step", 1)
start = 0 if start is None else start
end = extent if end is None else end
if not isinstance(start, int) or not isinstance(end, int) or step != 1:
return None
if start < 0 or end < 0:
return None
# aten.slice clamps an oversized end to the selected dimension.
end = min(end, extent)
if start >= end:
return None
return _SliceInfo(node=node, dim=dim, start=start, end=end)
def _canonicalize_slices(self, graph: fx.Graph) -> int:
groups: dict[tuple[fx.Node, int], list[_SliceInfo]] = defaultdict(list)
for node in graph.find_nodes(
op="call_function", target=torch.ops.aten.slice.Tensor
):
slice_info = self._slice_info(node)
if slice_info is None:
continue
groups[(node.args[0], slice_info.dim)].append(slice_info)
count = 0
for slice_group in groups.values():
if len(slice_group) < 2:
continue
source = slice_group[0].node.args[0]
dim = slice_group[0].dim
source_val = self._tensor_val(source)
assert source_val is not None
extent = source_val.shape[dim]
assert isinstance(extent, int)
ordered = sorted(slice_group, key=lambda info: info.start)
# Ensure they are contiguous partitions.
if (
ordered[0].start != 0
or ordered[-1].end != extent
or any(
left.end != right.start for left, right in zip(ordered, ordered[1:])
)
):
continue
split_sizes = [info.end - info.start for info in ordered]
# Use -1 for the last dimension; otherwise use the positive dimension index.
split_dim = -1 if dim == source_val.dim() - 1 else dim
first_slice = slice_group[0].node
with graph.inserting_before(first_slice):
split = graph.call_function(
torch.ops.aten.split_with_sizes.default,
args=(source, split_sizes, split_dim),
)
split.meta["val"] = [info.node.meta["val"] for info in ordered]
replacements: list[tuple[fx.Node, fx.Node]] = []
for index, info in enumerate(ordered):
getitem = graph.call_function(
operator.getitem,
args=(split, index),
type_expr=info.node.type,
)
getitem.meta = copy(info.node.meta)
replacements.append((info.node, getitem))
for slice_node, getitem in replacements:
slice_node.replace_all_uses_with(getitem)
graph.erase_node(slice_node)
count += 1
return count
def _coalesce_splits(self, graph: fx.Graph) -> int:
count = 0
split_nodes: dict[tuple[fx.Node, int], list[fx.Node]] = defaultdict(list)
for node in graph.find_nodes(
op="call_function", target=torch.ops.aten.split_with_sizes.default
):
if not all(is_func(user, operator.getitem) for user in node.users):
continue
arg_node, split_sizes = node.args[:2]
if arg_node not in split_nodes:
split_nodes[arg_node] = [node]
source, split_sizes = node.args[:2]
source_val = self._tensor_val(source)
if source_val is None:
continue
# Find existing node with same split_sizes
raw_dim = self._get_arg(node, 2, "dim", 0)
dim = self._normalize_dim(raw_dim, source_val.dim())
candidates = split_nodes[(source, dim)]
canonical = next(
(
n
for n in split_nodes[arg_node]
if list(n.args[1]) == list(split_sizes)
candidate
for candidate in candidates
if list(candidate.args[1]) == list(split_sizes)
),
None,
)
@@ -65,6 +210,16 @@ class SplitCoalescingPass(VllmInductorPass):
graph.erase_node(node)
count += 1
else:
split_nodes[arg_node].append(node)
candidates.append(node)
logger.debug("Coalesced %d duplicate split_with_sizes nodes", count)
return count
@VllmInductorPass.time_and_log
def __call__(self, graph: fx.Graph) -> None:
canonicalized = self._canonicalize_slices(graph)
coalesced = self._coalesce_splits(graph)
logger.debug(
"Canonicalized %d slice partitions and coalesced %d split nodes",
canonicalized,
coalesced,
)
+18 -1
View File
@@ -12,7 +12,13 @@ from typing import Any, ParamSpec, TypeVar
import torch
import vllm.envs as envs
from vllm.config import CompilationMode, CUDAGraphMode, get_current_vllm_config
from vllm.compilation.counter import compilation_counter
from vllm.config import (
CompilationMode,
CUDAGraphMode,
VllmConfig,
get_current_vllm_config,
)
from vllm.config.compilation import DynamicShapesType
from vllm.logger import init_logger
from vllm.utils.nvtx_pytorch_hooks import layerwise_nvtx_marker_context
@@ -44,6 +50,17 @@ def _compilation_context() -> Generator[None, None, None]:
torch._dynamo.config.accumulated_cache_size_limit = original_accumulated_cache
def compile_model_with_stock_torch(
model: torch.nn.Module, vllm_config: VllmConfig
) -> None:
from vllm.env_override import _apply_constrain_to_fx_strides_patch
_apply_constrain_to_fx_strides_patch()
backend = vllm_config.compilation_config.init_backend(vllm_config)
compilation_counter.stock_torch_compile_count += 1
model.compile(fullgraph=True, backend=backend)
class TorchCompileWithNoGuardsWrapper:
"""A wrapper class for torch.compile, it ensures that all guards are dropped
when CompilationMode is not CompilationMode.STOCK_TORCH_COMPILE.
+1
View File
@@ -100,6 +100,7 @@ class EngramConfig:
if self.dp_shared_memory is None:
self.dp_shared_memory = (
self.cpu_offload
and not self.use_thp
and parallel_config.data_parallel_size > 1
and not parallel_config.enable_elastic_ep
)
+4
View File
@@ -84,6 +84,9 @@ class LoRAConfig:
experts (stored once with expert-dim 1) instead of per-expert. The shared
factors are broadcast to the expert count at kernel time. Only meaningful for
MoE models whose adapters use this layout; ignored otherwise."""
max_lora_cls_labels: int | None = Field(default=None, ge=1)
"""Maximum output size for LoRA classification heads. Defaults to the
base classification head size."""
def compute_hash(self) -> str:
"""WARNING: Whenever a new field is added to this config,
@@ -104,6 +107,7 @@ class LoRAConfig:
factors.append(self.enable_tower_connector_lora)
factors.append(self.enable_mixed_moe_lora_format)
factors.append(self.enable_moe_shared_loras)
factors.append(self.max_lora_cls_labels)
# target_modules affects which modules get LoRA applied
factors.append(
tuple(sorted(self.target_modules)) if self.target_modules else None
+187 -1
View File
@@ -27,6 +27,186 @@ logger = init_logger(__name__)
_T = TypeVar("_T")
# HuggingFace processors accept a shared flat namespace in addition to the
# nested processor kwarg scopes ``text_kwargs`` / ``images_kwargs`` /
# ``videos_kwargs`` / ``audio_kwargs``. vLLM recognizes these scopes when
# resolving ``mm_processor_kwargs``.
_HF_PROCESSOR_KWARG_SCOPES = (
"text_kwargs",
"images_kwargs",
"videos_kwargs",
"audio_kwargs",
)
def _recursively_merge_mm_processor_kwargs(
defaults: Mapping[str, object],
overrides: Mapping[str, object],
) -> dict[str, object]:
"""Merge two mappings recursively, with ``overrides`` taking precedence.
Nested values are merged only when both values are mappings; otherwise the
override replaces the existing value.
"""
merged = dict(defaults)
for key, value in overrides.items():
default_value = merged.get(key)
if isinstance(default_value, Mapping) and isinstance(value, Mapping):
merged[key] = _recursively_merge_mm_processor_kwargs(default_value, value)
else:
merged[key] = value
return merged
def _merge_mm_processor_scope(
config_flat: Mapping[str, object],
config_scoped: Mapping[str, object],
inference_flat: Mapping[str, object],
inference_scoped: Mapping[str, object],
) -> dict[str, object]:
"""Merge kwargs for one existing HuggingFace processor kwarg scope.
Flat kwargs contribute only to keys present in either the configured or
inference-time scope. For those keys, precedence is:
configured flat < configured scoped < inference flat < inference scoped.
Nested mappings are merged recursively; otherwise the higher-priority value
replaces the lower-priority value.
"""
# Flat kwargs contribute only to keys present in this scope in either input.
scoped_keys = config_scoped.keys() | inference_scoped.keys()
config_flat_for_scope = {
key: value for key, value in config_flat.items() if key in scoped_keys
}
inference_flat_for_scope = {
key: value for key, value in inference_flat.items() if key in scoped_keys
}
# Merge from lowest to highest priority:
# configured flat -> configured scoped -> inference flat -> inference scoped.
merged = _recursively_merge_mm_processor_kwargs(
config_flat_for_scope, config_scoped
)
merged = _recursively_merge_mm_processor_kwargs(merged, inference_flat_for_scope)
merged = _recursively_merge_mm_processor_kwargs(merged, inference_scoped)
return merged
def _merge_mm_processor_kwargs(
config_kwargs: Mapping[str, object],
inference_kwargs: Mapping[str, object],
) -> dict[str, object]:
"""Merge configured and inference-time multi-modal processor kwargs.
The merge is performed in two parts:
1. The shared flat kwargs are merged recursively, with inference-time values
taking precedence.
2. Each existing HuggingFace processor kwarg scope is merged separately.
For keys present in either the configured or inference-time scope,
precedence is:
configured flat < configured scoped < inference flat < inference scoped.
For example:
configured = {
"size": {"shortest_edge": 256},
"videos_kwargs": {
"size": {"longest_edge": 1024},
"num_frames": 16,
},
}
inference = {
"size": {"shortest_edge": 512},
"videos_kwargs": {"fps": 4},
}
produces:
{
"size": {"shortest_edge": 512},
"videos_kwargs": {
"size": {
"shortest_edge": 512,
"longest_edge": 1024,
},
"num_frames": 16,
"fps": 4,
},
}
Scoped values do not modify the shared flat kwargs or sibling scopes.
Missing scopes, None-valued scopes, and empty scope mappings are treated as
absent and do not create a scope.
"""
# Merge the shared flat kwargs first; nested scopes are handled separately
# below.
config_flat = {
key: value
for key, value in config_kwargs.items()
if key not in _HF_PROCESSOR_KWARG_SCOPES
}
inference_flat = {
key: value
for key, value in inference_kwargs.items()
if key not in _HF_PROCESSOR_KWARG_SCOPES
}
merged = _recursively_merge_mm_processor_kwargs(config_flat, inference_flat)
# Merge each nested processor kwarg scope present in either input.
for scoped_key in _HF_PROCESSOR_KWARG_SCOPES:
config_scope_value = config_kwargs.get(scoped_key)
inference_scope_value = inference_kwargs.get(scoped_key)
# Treat missing scopes, None-valued scopes, and empty scope mappings as
# absent.
if isinstance(config_scope_value, Mapping) and not config_scope_value:
config_scope_value = None
if isinstance(inference_scope_value, Mapping) and not inference_scope_value:
inference_scope_value = None
# Skip adding the scope to the merged result when it is absent from both
# sources.
if config_scope_value is None and inference_scope_value is None:
continue
# Handle the inference scope first because it has higher precedence; only
# mapping-valued scopes participate in the recursive scoped merge.
inference_scope_kwargs: Mapping[str, object]
if inference_scope_value is None:
inference_scope_kwargs = {}
elif not isinstance(inference_scope_value, Mapping):
# Non-mapping scopes cannot participate in the recursive scoped merge;
# the higher-priority inference value replaces the configured scope.
merged[scoped_key] = inference_scope_value
continue
else:
inference_scope_kwargs = inference_scope_value
# Handle the configured scope next because it has lower precedence; only
# mapping-valued scopes participate in the recursive scoped merge.
if isinstance(config_scope_value, Mapping):
config_scope_kwargs = config_scope_value
elif inference_scope_value is None:
# Non-mapping scopes cannot participate in the recursive scoped merge;
# preserve the configured value when inference contributes nothing.
merged[scoped_key] = config_scope_value
continue
else:
config_scope_kwargs = {}
# Merge this scope together with the matching flat kwargs.
merged[scoped_key] = _merge_mm_processor_scope(
config_flat,
config_scope_kwargs,
inference_flat,
inference_scope_kwargs,
)
return merged
@dataclass
class BaseDummyOptions:
@@ -533,8 +713,14 @@ class MultiModalConfig:
) -> dict[str, object]:
"""Get the keyword arguments to pass to the multi-modal processor
according to the extra arguments passed during inference.
Nested mappings are merged recursively, with inference-time values taking
precedence over configured values.
"""
merged = dict(self.mm_processor_kwargs or {}) | dict(inference_kwargs)
merged = _merge_mm_processor_kwargs(
self.mm_processor_kwargs or {},
inference_kwargs,
)
if self.mm_device_do_normalize:
# The model expects raw pixels and normalises on device;
# overriding these per request would silently double-normalise.
+7
View File
@@ -4,6 +4,7 @@
import os
import socket
from collections.abc import Callable
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Literal, overload
import regex as re
@@ -613,6 +614,11 @@ class ParallelConfig:
"""
return self.data_parallel_external_lb or self.data_parallel_hybrid_lb
@property
def cpu_distributed_timeout(self) -> timedelta | None:
seconds = self.cpu_distributed_timeout_seconds
return timedelta(seconds=seconds) if seconds is not None else None
def get_next_dp_init_port(self) -> int:
"""We might need to initialize process groups in multiple
processes that is related to data parallelism,
@@ -694,6 +700,7 @@ class ParallelConfig:
backend="gloo",
return_store=return_store,
listen_socket=listen_socket,
timeout=self.cpu_distributed_timeout,
)
except DistNetworkError as e:
# We only want to retry when the root cause is EADDRINUSE.
+23 -8
View File
@@ -2041,6 +2041,7 @@ class VllmConfig:
self._validate_mm_processor_device()
if self.use_v2_model_runner:
self._disable_cudagraphs_for_v2_stock_torch_compile()
self._validate_v2_model_runner()
else:
self._validate_v1_model_runner()
@@ -3045,9 +3046,6 @@ class VllmConfig:
unsupported: list[str] = []
speculative_config = self.speculative_config
if self.compilation_config.mode == CompilationMode.STOCK_TORCH_COMPILE:
unsupported.append("stock torch.compile")
if (
self.compilation_config.pass_config.enable_sp
and self.parallel_config.tensor_parallel_size > 1
@@ -3067,8 +3065,6 @@ class VllmConfig:
# https://github.com/vllm-project/vllm/pull/40704
"ngram",
"ngram_gpu",
# https://github.com/vllm-project/vllm/pull/43091
"draft_model",
"suffix",
"medusa",
"mlp_speculator",
@@ -3088,9 +3084,6 @@ class VllmConfig:
if self.parallel_config.use_ubatching:
unsupported.extend(self._get_dbo_unsupported_features())
if self.parallel_config.enable_elastic_ep:
unsupported.append("elastic expert parallelism")
if self.cache_config.mamba_cache_mode == "all":
unsupported.append("mamba cache mode 'all'")
@@ -3306,6 +3299,28 @@ class VllmConfig:
"Enable attribution or use --enforce-eager."
)
def _disable_cudagraphs_for_v2_stock_torch_compile(self) -> None:
"""Run stock torch.compile without CUDA graphs in Model Runner V2.
V1 never wraps a stock-compiled model in CUDAGraphWrapper, so it runs
without CUDA graphs. V2's CUDA graph manager would otherwise capture
FULL graphs around the stock-compiled model, so disable them to match.
"""
compilation_config = self.compilation_config
if (
compilation_config.mode != CompilationMode.STOCK_TORCH_COMPILE
or compilation_config.cudagraph_mode == CUDAGraphMode.NONE
):
return
logger.info_once(
"CUDA graphs are not supported with stock torch.compile in Model "
"Runner V2. Overriding cudagraph_mode %s to NONE.",
compilation_config.cudagraph_mode.name,
)
compilation_config.cudagraph_mode = CUDAGraphMode.NONE
compilation_config.max_cudagraph_capture_size = 0
compilation_config.cudagraph_capture_sizes = []
def _validate_v2_model_runner(self) -> None:
"""Check for features not yet supported by the V2 model runner."""
if not HAS_TRITON:
@@ -20,6 +20,7 @@ from vllm.distributed.device_communicators.all_reduce_utils import (
from vllm.distributed.parallel_state import _node_count, get_node_count
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
logger = init_logger(__name__)
@@ -45,6 +46,10 @@ _fi_ar_workspace = None
# allreduce backend or a fallback backend when the primary workspace is not
# available on the current topology.
_fi_ar_quant_workspace = None
# Creation is collective, so a failed attempt must not be retried on every
# all-reduce call.
_fi_ar_workspace_failed = False
_fi_ar_quant_workspace_failed = False
_fi_ar_workspace_groups: dict[int, ProcessGroup] = {}
@@ -79,16 +84,19 @@ def _create_workspace(
rng_state = random.getstate()
try:
random.seed(int.from_bytes(os.urandom(16), byteorder="big"))
workspace = flashinfer_comm.create_allreduce_fusion_workspace(
backend=backend,
world_size=world_size,
rank=rank,
max_token_num=max_token_num,
hidden_dim=hidden_dim,
dtype=dtype,
comm_backend=comm_backend,
group=group,
)
# Creation may run lazily inside the first sync-checked forward (e.g.
# with enforce_eager, which skips warmup).
with gpu_sync_allowed(first_only=True):
workspace = flashinfer_comm.create_allreduce_fusion_workspace(
backend=backend,
world_size=world_size,
rank=rank,
max_token_num=max_token_num,
hidden_dim=hidden_dim,
dtype=dtype,
comm_backend=comm_backend,
group=group,
)
if backend == "mnnvl" and not getattr(workspace, "mc_ptr", 0):
workspace.destroy()
logger.warning_once(
@@ -175,8 +183,8 @@ def get_fi_ar_workspace(
for standalone allreduce. Backend is controlled by
VLLM_FLASHINFER_ALLREDUCE_BACKEND env var.
"""
global _fi_ar_workspace
if _fi_ar_workspace is not None:
global _fi_ar_workspace, _fi_ar_workspace_failed
if _fi_ar_workspace is not None or _fi_ar_workspace_failed:
return _fi_ar_workspace
backend, allow_trtllm_fallback = _resolve_fi_ar_backend()
@@ -218,6 +226,7 @@ def get_fi_ar_workspace(
f"with backend={backend}"
)
else:
_fi_ar_workspace_failed = True
logger.error_once(
"Failed to initialize FlashInfer Allreduce norm fusion workspace "
f"with backend={backend}"
@@ -240,8 +249,8 @@ def get_fi_ar_quant_workspace(
non-quant fusion. With ``auto`` this prefers mnnvl and falls back to trtllm
only on single-node topologies where mnnvl multicast is unavailable.
"""
global _fi_ar_quant_workspace
if _fi_ar_quant_workspace is not None:
global _fi_ar_quant_workspace, _fi_ar_quant_workspace_failed
if _fi_ar_quant_workspace is not None or _fi_ar_quant_workspace_failed:
return _fi_ar_quant_workspace
backend, allow_trtllm_fallback = _resolve_fi_ar_backend()
@@ -291,6 +300,7 @@ def get_fi_ar_quant_workspace(
f"fusion workspace with backend={backend}"
)
else:
_fi_ar_quant_workspace_failed = True
logger.error_once(
"Failed to initialize FlashInfer Allreduce norm quantization "
f"fusion workspace with backend={backend}"
@@ -304,6 +314,7 @@ _fi_ar_workspace_lock = threading.Lock()
def destroy_fi_ar_workspace():
global _fi_ar_workspace, _fi_ar_quant_workspace
global _fi_ar_workspace_failed, _fi_ar_quant_workspace_failed
with _fi_ar_workspace_lock:
is_alias = _fi_ar_workspace is _fi_ar_quant_workspace
@@ -313,6 +324,7 @@ def destroy_fi_ar_workspace():
_fi_ar_quant_workspace.destroy()
_fi_ar_workspace = _fi_ar_quant_workspace = None
_fi_ar_workspace_failed = _fi_ar_quant_workspace_failed = False
_fi_ar_workspace_groups.clear()
+33 -22
View File
@@ -54,6 +54,8 @@ from vllm.platforms import current_platform
from vllm.utils import is_moe_layer
from vllm.v1.engine import ReconfigureDistributedRequest, ReconfigureRankType
from vllm.v1.worker.dp_utils import skip_dp_coordination
from vllm.v1.worker.gpu.cudagraph_utils import CudaGraphManager
from vllm.v1.worker.gpu.eplb_utils import preserve_serving_state
from vllm.v1.worker.gpu_ubatch_wrapper import UBatchWrapper
from vllm.v1.worker.workspace import lock_workspace, unlock_workspace
@@ -171,6 +173,17 @@ class ElasticEPScalingExecutor:
self.worker.vllm_config.parallel_config,
)
@contextmanager
def _suppress_eplb(self) -> Iterator[None]:
# A rank warming up alone must not advance the EPLB step counter.
runner = self.worker.model_runner
was_suppressed = runner.eep_eplb_suppressed
runner.eep_eplb_suppressed = True
try:
yield
finally:
runner.eep_eplb_suppressed = was_suppressed
@contextmanager
def _disable_flashinfer_autotune(self) -> Iterator[None]:
kernel_config = self.worker.vllm_config.kernel_config
@@ -421,7 +434,17 @@ class ElasticEPScalingExecutor:
self._staged_moe_quant_methods.clear()
def _release_cuda_graphs(self) -> None:
if isinstance(self.worker.model_runner.model, CUDAGraphWrapper):
manager = getattr(self.worker.model_runner, "cudagraph_manager", None)
speculator = getattr(self.worker.model_runner, "speculator", None)
if manager is not None:
# MRV2 captures through CudaGraphManager instead of wrapping the
# model, so neither wrapper branch below ever fires.
manager.release_graphs()
for attr in vars(speculator).values() if speculator else ():
if isinstance(attr, CudaGraphManager):
attr.release_graphs()
elif isinstance(self.worker.model_runner.model, CUDAGraphWrapper):
wrapper = self.worker.model_runner.model
wrapper.concrete_cudagraph_entries = {}
@@ -431,6 +454,8 @@ class ElasticEPScalingExecutor:
torch.compiler.reset()
with set_current_vllm_config(self.worker.vllm_config):
reset_compile_wrapper(self.worker.model_runner.get_model())
if speculator is not None:
reset_compile_wrapper(speculator.model)
gc.collect()
torch.accelerator.synchronize()
@@ -675,42 +700,28 @@ class ElasticEPScalingExecutor:
self.warm_and_capture()
def warm_and_capture(self) -> None:
# Save and clear block tables so the dummy MoE forward doesn't
# write dummy slot mappings into real KV-cache blocks.
multi_block_table = self.worker.model_runner.input_batch.block_table
saved_block_tables: list[tuple[torch.Tensor, torch.Tensor]] = []
for bt in multi_block_table.block_tables:
saved_block_tables.append(
(bt.block_table.gpu.clone(), bt.block_table.cpu.clone())
)
multi_block_table.clear()
# _ensure_workspace_size allocates a fresh tensor on grow, leaving
# any captured CUDA graph with a stale data pointer; drop graphs
# before re-warm so captures realign with the resized buffer.
self._release_cuda_graphs()
unlock_workspace()
# Grow the MoE workspace at max_num_tokens. compile_or_warm_up_model
# alone only exercises cudagraph-capture sizes and can leave the
# workspace too small for post-reshuffle routing. Use _dummy_run
# directly with skip_eplb=True so dummy routing doesn't pollute the
# just-rebalanced EPLB stats.
runner = self.worker.model_runner
all2all_manager = get_ep_all2all_manager()
reuse_kernel = self._can_reuse_fused_moe_kernel()
serving_state = (
preserve_serving_state(runner)
if self.worker.use_v2_model_runner
else runner.preserve_serving_state()
)
with (
skip_dp_coordination() if reuse_kernel else nullcontext(),
all2all_manager.mask_remote_ranks() if reuse_kernel else nullcontext(),
self._disable_flashinfer_autotune() if reuse_kernel else nullcontext(),
self._suppress_eplb(),
serving_state,
):
runner._dummy_run(runner.max_num_tokens, is_profile=True, skip_eplb=True)
self.worker.compile_or_warm_up_model()
lock_workspace()
for bt, (saved_gpu, saved_cpu) in zip(
multi_block_table.block_tables, saved_block_tables
):
bt.block_table.gpu.copy_(saved_gpu)
bt.block_table.cpu.copy_(saved_cpu)
@@ -165,8 +165,8 @@ class NixlBaseConnectorWorker:
# Overridden by NixlPushConnectorWorker.
_TRANSFER_MODE: str = "pull"
# Layer-name routing is supported only by NixlPushConnector for HMA KV
# caches under PP.
# Layer-name routing is supported only by NixlPushConnector for HMA or
# packed KV caches under PP.
_supports_pp_hma = False
def _compute_desc_ids(
@@ -432,15 +432,22 @@ class NixlBaseConnectorWorker:
group_by_layer[name] for name in layer_names
)
def _requires_layer_name_routing(self) -> bool:
"""Whether PP push must match HMA layers by name, not region index."""
def _tracks_region_layers(self) -> bool:
"""Whether regions advertise their member layer names.
Push workers do so for HMA and packed layouts, so a PP producer can
match layers by name instead of by region index.
"""
return (
self._supports_pp_hma
and self.pp_size > 1
and self._is_hma_required
and (self._is_hma_required or self._has_packed_cache)
and not self._has_mamba
)
def _requires_layer_name_routing(self) -> bool:
"""Whether PP push must match HMA/packed layers by name, not region index."""
return self.pp_size > 1 and self._tracks_region_layers()
def _align_remote_regions_by_layer(
self, nixl_agent_meta: NixlAgentMetadata
) -> None:
@@ -479,6 +486,10 @@ class NixlBaseConnectorWorker:
]
assert not missing, f"Remote is missing locally owned layers: {missing}"
packed_regions = {
remote_region_by_layer[name]
for name in nixl_agent_meta.packed_member_layouts
}
remote_regions = [
remote_region_by_layer[name] for name in self._transfer_layer_names
]
@@ -505,6 +516,24 @@ class NixlBaseConnectorWorker:
]
if nixl_agent_meta.region_names is not None:
nixl_agent_meta.region_names = list(self._transfer_layer_names)
if nixl_agent_meta.packed_member_layouts:
for i, layer_name in enumerate(self._transfer_layer_names):
if remote_regions[i] not in packed_regions:
continue
assert layer_name in nixl_agent_meta.packed_member_layouts, (
f"Remote packed layer {layer_name!r} has no layout"
)
offset, page_size = nixl_agent_meta.packed_member_layouts[layer_name]
assert (
0 <= offset < offset + page_size <= nixl_agent_meta.block_lens[i]
), f"Remote packed layer {layer_name!r} escapes its block"
local_region = self._transfer_layer_region_indices[i]
assert page_size == self.block_len_per_layer[local_region], (
f"Packed MLA page sizes must match for layer {layer_name!r}"
)
nixl_agent_meta.kv_caches_base_addr[i] += offset
nixl_agent_meta.block_lens[i] = page_size
nixl_agent_meta.packed_member_layouts = {}
# One layer per region keeps a second alignment pass a no-op.
nixl_agent_meta.region_members = [[name] for name in self._transfer_layer_names]
@@ -899,7 +928,10 @@ class NixlBaseConnectorWorker:
# within a block (BLHNC/BHLNC), where stride > block_len.
self.block_stride_per_layer = list[int]()
# Region layer membership is populated for HMA layouts.
# Block-outermost layouts (BLHNC/BHLNC) pack every layer's page into one
# block row of a shared allocation.
self._has_packed_cache = KVCacheLayout[self.kv_cache_layout].is_block_outermost
# Region layer membership is populated for HMA and packed layouts.
self.region_members = []
# Local layer order, set by ``_set_region_layers`` only when
# routing by layer name. Empty means region-index routing.
@@ -1352,6 +1384,8 @@ class NixlBaseConnectorWorker:
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
"""Register the KV Cache data in nixl."""
use_layer_name_routing = self._requires_layer_name_routing()
route_packed_layers = self._has_packed_cache and use_layer_name_routing
self.transfer_topo = TransferTopology(
tp_rank=self.transfer_tp_rank,
tp_size=self.transfer_tp_size,
@@ -1369,9 +1403,15 @@ class NixlBaseConnectorWorker:
else None,
is_mamba=self._has_mamba,
)
backend_name = self.backend_name
if self._supports_pp_hma and self._has_packed_cache:
# PP can reorder the same backends across stages of a packed model.
backend_name = ",".join(
sorted(backend.get_name() for backend in self.attn_backends)
)
self.compat_hash = compute_nixl_compatibility_hash(
self.vllm_config,
self.backend_name,
backend_name,
transfer_mode=self._TRANSFER_MODE,
)
@@ -1413,6 +1453,11 @@ class NixlBaseConnectorWorker:
# CSA-linear needs separate logical regions for attention and state
# aliases even though every view shares one block-major allocation.
packed_storage = packed_storage and not self._is_csa_linear
if route_packed_layers and any(
not isinstance(spec, (MLAAttentionSpec, SlidingWindowMLASpec))
for spec in self._layer_specs.values()
):
raise NotImplementedError("PP push with packed KV caches requires MLA")
layer_specs: dict[str, KVCacheSpec] = {}
compressed_region_owners: dict[int, torch.Tensor] = {}
@@ -1439,10 +1484,9 @@ class NixlBaseConnectorWorker:
):
compressed_region_owners.setdefault(cache.data_ptr(), cache)
track_region_layers = (
self._supports_pp_hma and self._is_hma_required and not self._has_mamba
)
track_region_layers = self._tracks_region_layers()
region_layers: list[list[str]] = []
packed_member_layouts: dict[str, tuple[int, int]] = {}
# K and V are packed into the content dim, so each attention layer is a
# single NIXL region whose block transfers as one unit. Mamba layers instead
@@ -1587,11 +1631,34 @@ class NixlBaseConnectorWorker:
virtual_transfer_pages = _uses_dense_virtual_transfer_pages(
layer_spec, cache, physical_page_size, num_blocks
)
# Push workers address the pages of packed MLA rows by layer.
packed_mla_push = (
track_region_layers
and self._has_packed_cache
and packed_storage
and storage_is_block_major
and is_mla_region
)
if virtual_transfer_pages:
# A compressed kernel row can contain multiple NIXL transfer pages.
region_specs = [
(cache.data_ptr(), physical_page_size, physical_page_size)
]
elif packed_mla_push and use_layer_name_routing:
# PP>1 prefill stage: register only this layer's page of each row.
region_specs = [
(cache.data_ptr(), physical_page_size, block_stride)
]
elif packed_mla_push:
# PP=1 decode or prefill: register whole rows, and advertise where
# this layer's page sits so a PP>1 prefill can write into it.
storage_block_len = registration_len // num_blocks
region_specs = [
(registration_base, storage_block_len, storage_block_len)
]
offset = cache.data_ptr() - storage_addr
assert offset >= 0 and offset + physical_page_size <= block_stride
packed_member_layouts[layer_name] = (offset, physical_page_size)
elif storage_is_block_major and (
not page_contiguous
and ((packed_storage and is_mla_region) or not self._is_csa_linear)
@@ -1633,7 +1700,9 @@ class NixlBaseConnectorWorker:
]
for base_addr, block_len, block_stride in region_specs:
if base_addr in seen_base_addresses:
# A packed PP producer keeps one region per layer, so aliases at
# one address (a layer and its SWA view) stay distinct.
if base_addr in seen_base_addresses and not route_packed_layers:
region_index = seen_base_addresses.index(base_addr)
assert region_mem_types[region_index] == mem_type
self._region_is_mla[region_index] |= is_mla_region
@@ -1717,7 +1786,7 @@ class NixlBaseConnectorWorker:
self._set_region_layers(region_layers)
if self.pp_size > 1 and not self._is_hma_required:
if self.pp_size > 1 and not use_layer_name_routing:
start_layer, end_layer = self.model_config.get_layers_start_end_indices(
self.vllm_config.parallel_config
)
@@ -1807,6 +1876,7 @@ class NixlBaseConnectorWorker:
dcp_size=self.dcp_size,
pcp_size=self.pcp_size,
region_members=self.region_members,
packed_member_layouts=packed_member_layouts,
)
# Wrap metadata in payload with hash for defensive decoding
assert self.compat_hash is not None
@@ -48,8 +48,9 @@ PUSH_REG_NOTIF_PREFIX = b"PUSH_REG:"
# 10: Add dense virtual transfer pages for compressed MLA caches
# 11: Add per-region transfer geometry and memory types to NixlAgentMetadata
# 12: Add per-region member names for PP push
# 13: Add packed-member layouts and order-independent packed-push backend hashes
#
NIXL_CONNECTOR_VERSION: int = 12
NIXL_CONNECTOR_VERSION: int = 13
@dataclass
@@ -74,6 +75,8 @@ class NixlAgentMetadata:
pcp_size: int = 1
# Layer names sharing each advertised region, in region order.
region_members: list[list[str]] = field(default_factory=list)
# Packed member -> (byte offset in its region's block, bytes per page).
packed_member_layouts: dict[str, tuple[int, int]] = field(default_factory=dict)
@dataclass
@@ -17,6 +17,8 @@ from vllm.distributed.parallel_state import (
)
from vllm.distributed.utils import (
StatelessProcessGroup,
get_cpu_distributed_timeout_or_none,
get_distributed_timeout_or_none,
stateless_destroy_torch_distributed_process_group,
stateless_init_torch_distributed_process_group,
)
@@ -104,6 +106,10 @@ class StatelessGroupCoordinator(GroupCoordinator):
backend = str(torch_distributed_backend)
self.backend = backend
cpu_timeout = get_cpu_distributed_timeout_or_none()
device_timeout = (
cpu_timeout if backend == "gloo" else get_distributed_timeout_or_none()
)
for idx, ranks in enumerate(group_ranks):
if self.rank in ranks:
self.ranks = ranks
@@ -130,6 +136,7 @@ class StatelessGroupCoordinator(GroupCoordinator):
backend=backend,
group_name=f"{self.unique_name}_device",
listen_socket=socks[0] if socks else None,
timeout=device_timeout,
)
cpu_group = stateless_init_torch_distributed_process_group(
host=host,
@@ -139,6 +146,7 @@ class StatelessGroupCoordinator(GroupCoordinator):
backend="gloo",
group_name=f"{self.unique_name}_cpu",
listen_socket=socks[1] if socks else None,
timeout=cpu_timeout,
)
tcp_store_group = StatelessProcessGroup.create(
host=host,
+6 -11
View File
@@ -530,8 +530,7 @@ def get_cpu_distributed_timeout_or_none() -> timedelta | None:
vllm_config = get_current_vllm_config_or_none()
if vllm_config is None:
return None
timeout_seconds = vllm_config.parallel_config.cpu_distributed_timeout_seconds
return timedelta(seconds=timeout_seconds) if timeout_seconds is not None else None
return vllm_config.parallel_config.cpu_distributed_timeout
def get_distributed_timeout_or_none() -> timedelta | None:
@@ -582,6 +581,7 @@ def stateless_init_torch_distributed_process_group(
group_name: str | None = None,
return_store: bool = False,
listen_socket: socket.socket | None = None,
timeout: timedelta | None = None,
) -> ProcessGroup | tuple[ProcessGroup, Store]:
"""A replacement for `torch.distributed.init_process_group` that does not
pollute the global state. The created ProcessGroup object can be used for
@@ -617,18 +617,13 @@ def stateless_init_torch_distributed_process_group(
is skipped and a ``TCPStore`` server is created directly using the
pre-bound socket. This is useful for eliminating TOCTOU races
between port allocation and binding.
If *timeout* is None, use PyTorch's default for the backend.
"""
init_method = get_tcp_uri(host, port)
backend = Backend(backend) # it is basically string
timeout = _get_default_timeout(backend)
if backend == "gloo":
gloo_timeout = get_cpu_distributed_timeout_or_none()
if gloo_timeout is not None:
timeout = gloo_timeout
else:
device_timeout = get_distributed_timeout_or_none()
if device_timeout is not None:
timeout = device_timeout
if timeout is None:
timeout = _get_default_timeout(backend)
if listen_socket is not None:
store = create_tcp_store(
+6
View File
@@ -676,6 +676,7 @@ class EngineArgs:
specialize_active_lora: bool = LoRAConfig.specialize_active_lora
enable_mixed_moe_lora_format: bool = LoRAConfig.enable_mixed_moe_lora_format
enable_moe_shared_loras: bool = LoRAConfig.enable_moe_shared_loras
max_lora_cls_labels: int | None = LoRAConfig.max_lora_cls_labels
ray_workers_use_nsight: bool = ParallelConfig.ray_workers_use_nsight
num_gpu_blocks_override: int | None = CacheConfig.num_gpu_blocks_override
@@ -1571,6 +1572,10 @@ class EngineArgs:
"--enable-moe-shared-loras",
**lora_kwargs["enable_moe_shared_loras"],
)
lora_group.add_argument(
"--max-lora-cls-labels",
**lora_kwargs["max_lora_cls_labels"],
)
# Logging arguments
logging_group = parser.add_argument_group(
@@ -2587,6 +2592,7 @@ class EngineArgs:
specialize_active_lora=self.specialize_active_lora,
enable_mixed_moe_lora_format=self.enable_mixed_moe_lora_format,
enable_moe_shared_loras=self.enable_moe_shared_loras,
max_lora_cls_labels=self.max_lora_cls_labels,
max_cpu_loras=self.max_cpu_loras
if self.max_cpu_loras and self.max_cpu_loras > 0
else None,
+6 -1
View File
@@ -1810,6 +1810,11 @@ PART_TYPES_TO_SKIP_NONE_CONTENT = (
"refusal",
)
# Content part types parsed as text rather than multimodal data.
TEXT_PART_TYPES = frozenset(
{"text", "input_text", "output_text", "refusal", "thinking"}
)
def _parse_chat_message_content_parts(
role: str,
@@ -1904,7 +1909,7 @@ def _parse_chat_message_content_part(
)
return None
if part_type in ("text", "input_text", "output_text", "refusal", "thinking"):
if part_type in TEXT_PART_TYPES:
str_content = cast(str, content)
_reject_reserved_placeholder_in_text(str_content, mm_parser.model_config)
if wrap_dicts:
@@ -20,6 +20,8 @@ from pydantic import (
from vllm.config import ModelConfig
from vllm.entrypoints.chat_utils import (
MM_PARSER_MAP,
TEXT_PART_TYPES,
ChatCompletionMessageParam,
ChatTemplateContentFormatOption,
)
@@ -58,6 +60,11 @@ logger = init_logger(__name__)
_INT64_MIN = -(2**63)
_INT64_MAX = 2**63 - 1
# Content part types that carry no multimodal data.
_TEXT_CONTENT_PART_TYPES = TEXT_PART_TYPES | {"tool_reference"}
# Keys that mark a content part as multimodal, whatever its ``type``.
_MEDIA_CONTENT_PART_KEYS = frozenset(MM_PARSER_MAP) - _TEXT_CONTENT_PART_TYPES
class ChatMessage(OpenAIBaseModel):
role: str
@@ -976,6 +983,39 @@ class ChatCompletionRequest(OpenAIBaseModel):
)
return data
@model_validator(mode="before")
@classmethod
def drop_prompt_token_ids_with_media(cls, data):
# The forwarded ids would drop media in ``messages``, so ignore them. Runs
# before validation, which can turn content into a one-shot iterator.
if not isinstance(data, dict):
return data
kv_transfer_params = data.get("kv_transfer_params")
messages = data.get("messages")
if (
not isinstance(kv_transfer_params, dict)
or kv_transfer_params.get("prompt_token_ids") is None
or not isinstance(messages, list)
):
return data
for msg in messages:
content = msg.get("content") if isinstance(msg, dict) else None
if not isinstance(content, list):
continue
for part in content:
if isinstance(part, dict) and (
any(key in part for key in _MEDIA_CONTENT_PART_KEYS)
or not isinstance(part_type := part.get("type", "text"), str)
or part_type not in _TEXT_CONTENT_PART_TYPES
):
logger.debug(
"Ignoring kv_transfer_params['prompt_token_ids']: "
"messages have non-text content and are rendered instead."
)
kv_transfer_params.pop("prompt_token_ids")
return data
return data
@model_validator(mode="before")
@classmethod
def check_system_message_content_type(cls, data):
@@ -1117,6 +1157,17 @@ class BatchChatCompletionRequest(OpenAIBaseModel):
"when using `logprob_token_ids`, `logprobs` must be set to true.",
parameter="logprob_token_ids",
)
kv_transfer_params = data.get("kv_transfer_params")
if (
isinstance(kv_transfer_params, dict)
and kv_transfer_params.get("prompt_token_ids") is not None
):
raise VLLMValidationError(
"Batch chat completions do not support "
"`kv_transfer_params['prompt_token_ids']`: one pre-tokenized "
"prompt cannot serve several conversations.",
parameter="kv_transfer_params.prompt_token_ids",
)
response_format = data.get("response_format")
if response_format is not None:
rf_type = (
@@ -207,7 +207,10 @@ class PoolingIOProcessor:
else:
pooling_params = ctx.pooling_params
params_seq = self._params_to_seq(pooling_params, num_requests)
# Clone to avoid modifying the caller's pooling parameters.
params_seq = [
param.clone() for param in self._params_to_seq(pooling_params, num_requests)
]
for param in params_seq:
if param.task is None:
@@ -168,7 +168,7 @@ class PluginWithIOProcessorPlugins(PoolingIOProcessor):
pooling_params = ctx.pooling_params
params_seq: list[PoolingParams] = [
self.io_processor.merge_pooling_params(param)
self.io_processor.merge_pooling_params(param.clone())
for param in self._params_to_seq(
pooling_params,
num_requests,
@@ -381,6 +381,7 @@ class GenerateResponse(BaseModel):
choices: list[GenerateResponseChoice]
usage: UsageInfo | None = Field(default=None)
prompt_logprobs: list[dict[int, Logprob] | None] | None = None
prompt_token_id_logprobs: str | None = None
prompt_token_ids: list[int] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
metrics: PerRequestMetrics | None = None
@@ -138,6 +138,11 @@ class ServingTokens(GenerateBaseServing):
f"sampling_params.n must be at most the server's max_num_seqs "
f"({max_num_seqs}), got {sampling_params.n}."
)
# The stream schema has no field for the scores.
if request.stream and sampling_params.prompt_logprob_token_ids is not None:
return self.create_error_response(
"prompt_logprob_token_ids are not available when stream=true."
)
if self.force_no_detokenize and sampling_params.stop:
# SamplingParams rejects stop with detokenize=False at request
# validation, but this server forces detokenize=False afterwards,
@@ -389,6 +394,11 @@ class ServingTokens(GenerateBaseServing):
choices=choices,
usage=usage,
prompt_logprobs=clamp_prompt_logprobs(final_res.prompt_logprobs),
prompt_token_id_logprobs=(
numpy2base64(final_res.prompt_token_id_logprobs)
if final_res.prompt_token_id_logprobs is not None
else None
),
prompt_token_ids=(
final_res.prompt_token_ids if request.return_token_ids else None
),
+19
View File
@@ -145,8 +145,10 @@ if TYPE_CHECKING:
VLLM_ROCM_USE_AITER_RMSNORM: bool = True
VLLM_ROCM_USE_AITER_MLA: bool = True
VLLM_ROCM_AITER_MLA_ASM_PADDING: Literal["auto", "gluon", "asm"] = "auto"
VLLM_ROCM_AITER_MLA_DCP_VERIFY: Literal["asm", "segmented"] = "segmented"
VLLM_ROCM_USE_AITER_MHA: bool = True
VLLM_ROCM_USE_AITER_FP4_ASM_GEMM: bool = False
VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA: bool = False
VLLM_ROCM_USE_AITER_TRITON_ROPE: bool = False
VLLM_ROCM_USE_AITER_FP8BMM: bool = True
VLLM_ROCM_USE_AITER_FP4BMM: bool = True
@@ -1309,6 +1311,15 @@ environment_variables: dict[str, Callable[[], Any]] = {
"VLLM_ROCM_USE_AITER_MLA": lambda: (
os.getenv("VLLM_ROCM_USE_AITER_MLA", "True").lower() in ("true", "1")
),
# Kernel for causal multi-token (spec-decode) verify steps under decode
# context parallelism on gfx950: "asm" uses AITER's round-robin ASM
# decode, "segmented" the Triton segmented MLA path.
"VLLM_ROCM_AITER_MLA_DCP_VERIFY": env_with_choices(
"VLLM_ROCM_AITER_MLA_DCP_VERIFY",
"segmented",
["asm", "segmented"],
case_sensitive=False,
),
# Small-head (<16) AITER MLA decode kernel selection. Small head counts
# (e.g. Kimi-K3: 12 heads/rank at TP8, 6 at TP16) can decode either through
# the Gluon small-head kernel or through the padded persistent-scheduling
@@ -1333,6 +1344,14 @@ environment_variables: dict[str, Callable[[], Any]] = {
"VLLM_ROCM_USE_AITER_FP4_ASM_GEMM": lambda: (
os.getenv("VLLM_ROCM_USE_AITER_FP4_ASM_GEMM", "False").lower() in ("true", "1")
),
# Whether sparse MLA prefill and decode run on aiter's Triton kernel, which
# reads the KV cache as stored (bf16 or fp8, paged or flat). Used by the
# ROCM_AITER_MLA_SPARSE backend (DeepSeek V3.2, GLM-5.x) and DeepSeek
# V4 / V4.1. gfx950 only. By default is disabled.
"VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA": lambda: (
os.getenv("VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA", "False").lower()
in ("true", "1")
),
# Whether to use aiter rope.
# By default is disabled.
"VLLM_ROCM_USE_AITER_TRITON_ROPE": lambda: (
+19 -13
View File
@@ -7,7 +7,7 @@ import json
import logging
import os
import sys
from collections.abc import Generator, Hashable
from collections.abc import Callable, Generator, Hashable
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import replace
@@ -31,20 +31,24 @@ _FORMAT = (
)
_DATE_FORMAT = "%m-%d %H:%M:%S"
_base_log_record_factory = logging.getLogRecordFactory()
_vllm_process_info: tuple[str, int] | None = None
def _vllm_log_record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord:
"""Add vLLM process metadata to each log record."""
record = _base_log_record_factory(*args, **kwargs)
process_info = _vllm_process_info
pid = os.getpid()
if process_info is None or process_info[1] != pid:
record.vllm_process_name = record.processName
else:
record.vllm_process_name = process_info[0]
return record
class _VllmLogRecordFactory:
"""Add vLLM process metadata while preserving the wrapped record factory."""
def __init__(self, factory: Callable[..., logging.LogRecord]) -> None:
self._factory = factory
def __call__(self, *args: Any, **kwargs: Any) -> logging.LogRecord:
record = self._factory(*args, **kwargs)
process_info = _vllm_process_info
pid = os.getpid()
if process_info is None or process_info[1] != pid:
record.vllm_process_name = record.processName
else:
record.vllm_process_name = process_info[0]
return record
def set_vllm_process_name(process_name: str, *, skip_if_set: bool = False) -> None:
@@ -220,7 +224,9 @@ def _configure_vllm_root_logger(config: "LoggingConfig | None" = None) -> None:
)
if configure_logging:
logging.setLogRecordFactory(_vllm_log_record_factory)
factory = logging.getLogRecordFactory()
if not isinstance(factory, _VllmLogRecordFactory):
logging.setLogRecordFactory(_VllmLogRecordFactory(factory))
logging_config = deepcopy(DEFAULT_LOGGING_CONFIG)
vllm_handler = logging_config["handlers"]["vllm"]
+39 -9
View File
@@ -20,28 +20,38 @@ class ClassificationHeadWithLoRA(ReplicatedLinearWithLoRA):
) -> None:
# Preserve ordinary LoRA A/B support for classification heads.
super().create_lora_weights(max_loras, lora_config, model_config)
self.max_lora_cls_labels = lora_config.max_lora_cls_labels or self.output_size
self.padded_num_labels = max(self.output_size, self.max_lora_cls_labels)
self.full_weight_stacked = torch.zeros(
max_loras,
1,
self.output_size,
self.padded_num_labels,
self.input_size,
dtype=lora_config.lora_dtype,
device=self.device,
)
self.full_bias_stacked = torch.zeros(
max_loras,
self.output_size,
self.padded_num_labels,
dtype=self.base_layer.params_dtype,
device=self.device,
)
self.full_module_enabled = torch.zeros(
max_loras, dtype=torch.bool, device=self.device
)
# Zero marks an unused slot; positive values are unpadded label counts.
self.full_module_num_labels = [0] * max_loras
self._output_lora_indices: tuple[int, ...] = ()
def set_output_mapping(self, slot_indices: tuple[int, ...]) -> None:
self._output_lora_indices = slot_indices
def reset_module_to_save(self, index: int) -> None:
self.full_weight_stacked[index].zero_()
self.full_bias_stacked[index].zero_()
self.full_module_enabled[index] = False
self.full_module_num_labels[index] = 0
def set_module_to_save(
self,
@@ -50,17 +60,33 @@ class ClassificationHeadWithLoRA(ReplicatedLinearWithLoRA):
bias: torch.Tensor | None,
) -> None:
self.reset_module_to_save(index)
self.full_weight_stacked[index, 0].copy_(weight, non_blocking=True)
num_labels = weight.size(0)
self.full_weight_stacked[index, 0, :num_labels].copy_(weight, non_blocking=True)
if bias is not None:
self.full_bias_stacked[index].copy_(bias, non_blocking=True)
self.full_bias_stacked[index, :num_labels].copy_(bias, non_blocking=True)
self.full_module_num_labels[index] = num_labels
self.full_module_enabled[index] = True
def forward(self, input_: torch.Tensor) -> torch.Tensor:
def forward(self, input_: torch.Tensor) -> torch.Tensor | list[torch.Tensor]:
# TODO base_result maybe don't need compute truly.
base_result = super().forward(input_)
output = base_result[0] if isinstance(base_result, tuple) else base_result
base_result = base_result[0] if isinstance(base_result, tuple) else base_result
full_output = self.punica_wrapper.apply_lora_full_linear(
slot_indices = self._output_lora_indices
assert len(slot_indices) == base_result.size(0), (
"Classification rows do not match LoRA request mapping"
)
num_labels = [
self.full_module_num_labels[index] if index >= 0 else 0
for index in slot_indices
]
if not any(num_labels):
return base_result
output = base_result.new_zeros(base_result.size(0), self.padded_num_labels)
output[:, : self.output_size].copy_(base_result)
self.punica_wrapper.apply_lora_full_linear(
output,
input_.to(self.full_weight_stacked.dtype),
self.full_weight_stacked,
@@ -68,8 +94,12 @@ class ClassificationHeadWithLoRA(ReplicatedLinearWithLoRA):
self.full_module_enabled,
)
if full_output is not None:
output = full_output
# Rows without a full head keep the base classifier output size.
num_labels = [size or self.output_size for size in num_labels]
if len(set(num_labels)) == 1:
return output[:, : num_labels[0]]
output = [output[row, :size] for row, size in enumerate(num_labels)]
return output
def _apply_lora_to_output(
+19 -4
View File
@@ -451,6 +451,16 @@ class LoRAModelManager:
self.vocab_size,
)
if self._classification_head is not None:
_, classification_head = self._classification_head
if classification_head.punica_wrapper is punica_wrapper:
classification_head.set_output_mapping(
tuple(
self.lora_index_to_id.index(lora_id) if lora_id > 0 else -1
for lora_id in mapping.prompt_mapping
)
)
def remove_all_adapters(self):
"""Remove all LoRAModels from the manager."""
self._registered_adapters.clear()
@@ -1262,18 +1272,23 @@ class LoRAModelManager:
f"classification head {module_name!r}."
)
expected_weight_shape = (wrapper.output_size, wrapper.input_size)
received_weight_shape = tuple(full_module.weight.shape)
if received_weight_shape != expected_weight_shape:
if (
full_module.weight.ndim != 2
or full_module.weight.size(0) < 1
or full_module.weight.size(0) > wrapper.max_lora_cls_labels
or full_module.weight.size(1) != wrapper.input_size
):
raise ValueError(
f"Full module {saved_module_name!r} for {module_name!r} has "
"an incompatible weight shape: expected "
f"{expected_weight_shape}, received {received_weight_shape}."
f"(1..{wrapper.max_lora_cls_labels}, {wrapper.input_size}), "
f"received {received_weight_shape}."
)
if full_module.bias is None:
return
expected_bias_shape = (wrapper.output_size,)
expected_bias_shape = (full_module.weight.size(0),)
received_bias_shape = tuple(full_module.bias.shape)
if received_bias_shape != expected_bias_shape:
raise ValueError(
@@ -13,6 +13,7 @@ __all__ = [
"hc_head_fused_kernel_cuda",
"mhc_pre_aiter",
"mhc_pre_delayed_aiter",
"mhc_fused_post_pre_delayed_rms_norm_aiter",
"mhc_post_aiter",
"mhc_fused_post_pre_aiter",
"hc_head_fused_aiter",
+79
View File
@@ -207,6 +207,79 @@ def _mhc_pre_delayed_aiter_fake(
)
def mhc_fused_post_pre_delayed_rms_norm_aiter(
residual: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
pre_mix: torch.Tensor | None,
sublayer_out: torch.Tensor | None,
post_layer_mix: torch.Tensor | None,
comb_res_mix: torch.Tensor | None,
norm_weight: torch.Tensor,
norm_eps: float,
residual_out: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
""":func:`mhc_pre_delayed_aiter` with the RMSNorm of the collapse folded in:
``layer_input`` comes back normalised with ``norm_weight`` / ``norm_eps``."""
from vllm._aiter_ops import rocm_aiter_ops
return rocm_aiter_ops.mhc_fused_post_pre_delayed_rms_norm(
residual,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix,
sublayer_out,
post_layer_mix,
comb_res_mix,
norm_weight,
norm_eps,
residual_out,
)
def _mhc_fused_post_pre_delayed_rms_norm_aiter_fake(
residual: torch.Tensor,
fn: torch.Tensor,
hc_scale: torch.Tensor,
hc_base: torch.Tensor,
rms_eps: float,
hc_pre_eps: float,
hc_sinkhorn_eps: float,
hc_post_mult_value: float,
sinkhorn_repeat: int,
pre_mix: torch.Tensor | None,
sublayer_out: torch.Tensor | None,
post_layer_mix: torch.Tensor | None,
comb_res_mix: torch.Tensor | None,
norm_weight: torch.Tensor,
norm_eps: float,
residual_out: torch.Tensor | None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
return _mhc_pre_delayed_aiter_fake(
residual,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
)
def mhc_post_aiter(
x: torch.Tensor,
residual: torch.Tensor,
@@ -335,6 +408,12 @@ direct_register_custom_op(
mutates_args=["residual_out"],
fake_impl=_mhc_pre_delayed_aiter_fake,
)
direct_register_custom_op(
op_name="mhc_fused_post_pre_delayed_rms_norm_aiter",
op_func=mhc_fused_post_pre_delayed_rms_norm_aiter,
mutates_args=["residual_out"],
fake_impl=_mhc_fused_post_pre_delayed_rms_norm_aiter_fake,
)
direct_register_custom_op(
op_name="mhc_post_aiter",
op_func=mhc_post_aiter,
@@ -567,13 +567,26 @@ def _process_weights_marlin(
"""Standard Marlin weight post-processing shared by MARLIN and
BATCHED_MARLIN backends.
Inputs arrive in canonical N-first layout ``[E, N, K_packed]``.
Steps
-----
1. Optional FP8 preprocessing of packed weights / scales.
2. Repack weights via ``gptq_marlin_moe_repack``.
3. Permute scales (and optionally extract INT8 global scales).
4. Permute bias tensors.
1. Transpose canonical N-first to K-first for Marlin.
2. Optional FP8 preprocessing of packed weights / scales.
3. Repack weights via ``gptq_marlin_moe_repack``.
4. Permute scales (and optionally extract INT8 global scales).
5. Permute bias tensors.
"""
# Canonical N-first → K-first for Marlin.
w13_qweight = w13_qweight.transpose(1, 2).contiguous()
w2_qweight = w2_qweight.transpose(1, 2).contiguous()
w13_scales = w13_scales.transpose(1, 2).contiguous()
w2_scales = w2_scales.transpose(1, 2).contiguous()
if w13_qzeros is not None:
w13_qzeros = w13_qzeros.transpose(1, 2).contiguous()
if w2_qzeros is not None:
w2_qzeros = w2_qzeros.transpose(1, 2).contiguous()
is_a_8bit = input_dtype is not None and input_dtype.itemsize == 1
marlin_w13_qweight: torch.Tensor
@@ -934,7 +947,12 @@ def _process_weights_cpu(
torch.Tensor | None, # w13_bias
torch.Tensor | None, # w2_bias
]:
"""CPU INT4 W4A16 weight post-processing."""
"""CPU INT4 W4A16 weight post-processing.
Non-AWQ inputs arrive in canonical N-first layout and are transposed
to K-first internally. AWQ uses a different packing axis and arrives
in its native format.
"""
from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
prepare_int4_moe_layer_for_cpu,
)
@@ -945,15 +963,9 @@ def _process_weights_cpu(
AutoGPTQConfig,
)
# Detect packing format.
# AWQ: qweight is [E, K, 2*N//8] (packed along output/N dim).
# GPTQ: qweight is [E, K//8, 2*N] (packed along input/K dim).
# compressed-tensors: qweight is [E, K//8, 2*N] (packed along input/K dim).
if isinstance(quant_config, AutoAWQConfig):
# AWQ: K is stored unpacked in dim 1.
cpu_quant_algo = ops.CPUQuantAlgo.AWQ
elif isinstance(quant_config, (AutoGPTQConfig, QuantizationArgs)):
# GPTQ / compressed-tensors: K//8 is stored packed in dim 1.
if isinstance(quant_config, AutoGPTQConfig) and quant_config.desc_act:
raise NotImplementedError(
"CPU WNA16 MoE backend does not support GPTQ with "
@@ -961,6 +973,15 @@ def _process_weights_cpu(
"reordering support."
)
cpu_quant_algo = ops.CPUQuantAlgo.GPTQ
# Canonical N-first → K-first for CPU kernel.
w13 = w13.transpose(1, 2).contiguous()
w2 = w2.transpose(1, 2).contiguous()
w13_scale = w13_scale.transpose(1, 2).contiguous()
w2_scale = w2_scale.transpose(1, 2).contiguous()
if w13_qzeros is not None:
w13_qzeros = w13_qzeros.transpose(1, 2).contiguous()
if w2_qzeros is not None:
w2_qzeros = w2_qzeros.transpose(1, 2).contiguous()
else:
raise TypeError(
"CPU WNA16 MoE backend requires AutoAWQConfig, AutoGPTQConfig "
@@ -1030,41 +1051,28 @@ def _process_weights_xpu(
torch.Tensor | None, # w13_bias
torch.Tensor | None, # w2_bias
]:
"""Repack GPTQ-format INT4 MoE weights into the layout
`vllm_xpu_kernels.fused_moe_interface.xpu_fused_moe(is_int4=True)` expects:
"""Repack INT4 MoE weights into the layout
`vllm_xpu_kernels.fused_moe_interface.xpu_fused_moe(is_int4=True)` expects.
w13: [E, 2*N, K] int4 (uint8 storage [E, 2*N, K // 2])
w13_scales: [E, 2*N, K // group_size] params_dtype
w2: [E, K, N] int4 (uint8 storage [E, K, N // 2])
w2_scales: [E, K, N // group_size] params_dtype
Input GPTQ layout from MoERunner.weight_loader:
w13: [E, K // 8, 2*N] int32 (8 nibbles per int32 along the input dim)
w13_scales: [E, K // group_size, 2*N] params_dtype
w2: [E, N // 8, K] int32
w2_scales: [E, N // group_size, K] params_dtype
Transpose dim 1 ↔ dim 2 then view int32 → uint8 to recover sequential
int4-packed bytes along the input dim. Each packed int32 holds 8 nibbles
`(n7<<28)|(n6<<24)|...|(n1<<4)|n0` in ascending K order; on a
little-endian host the int32→uint8 view exposes them as bytes
`[n1<<4|n0, n3<<4|n2, n5<<4|n4, n7<<4|n6]`, i.e. two nibbles per byte
with the lower nibble = lower input-K index. xpu_fused_moe(is_int4=True)
expects this convention; on a big-endian host the byte order reverses
and the kernel would silently miscompute, so we hard-fail.
Inputs arrive in canonical N-first layout ``[E, N, K_packed]`` int32.
The int32 → uint8 view recovers sequential int4-packed bytes along
the input dim. Each packed int32 holds 8 nibbles in ascending K order;
on a little-endian host the view exposes them as two nibbles per byte
with the lower nibble = lower input-K index. xpu_fused_moe(is_int4=True)
expects this convention; big-endian hosts are unsupported.
"""
del layer, quant_config # unused — kept for parity with the marlin helper
if sys.byteorder != "little":
raise NotImplementedError(
"_process_weights_xpu requires a little-endian host: the GPTQ "
"_process_weights_xpu requires a little-endian host: the "
"int32 → uint8 nibble repack relies on LE byte ordering."
)
w13_xpu = w13_qweight.transpose(1, 2).contiguous().view(torch.uint8)
w2_xpu = w2_qweight.transpose(1, 2).contiguous().view(torch.uint8)
w13_scales_xpu = w13_scales.transpose(1, 2).contiguous()
w2_scales_xpu = w2_scales.transpose(1, 2).contiguous()
w13_xpu = w13_qweight.contiguous().view(torch.uint8)
w2_xpu = w2_qweight.contiguous().view(torch.uint8)
w13_scales_xpu = w13_scales.contiguous()
w2_scales_xpu = w2_scales.contiguous()
return (
w13_xpu,
@@ -1315,16 +1323,23 @@ def _process_weights_emulation_gptq(
) -> tuple:
"""Dequantize int4 weights to BF16 for the emulation backend.
Inputs are in GPTQ packed format:
w13: [E, K//8, 2*N] int32 (gate+up proj stacked on dim 2)
w2: [E, N//8, K] int32
w13_scale: [E, K//gs, 2*N] float16
w2_scale: [E, N//gs, K] float16
Inputs arrive in canonical N-first layout and are transposed to
K-first internally for the GPTQ dequantization routines.
Outputs (what TritonExperts expects):
w13_out: [E, 2*N, K] bfloat16
w2_out: [E, K, N] bfloat16
"""
# Canonical N-first → K-first for dequantization.
w13 = w13.transpose(1, 2).contiguous()
w2 = w2.transpose(1, 2).contiguous()
w13_scale = w13_scale.transpose(1, 2).contiguous()
w2_scale = w2_scale.transpose(1, 2).contiguous()
if w13_qzeros is not None:
w13_qzeros = w13_qzeros.transpose(1, 2).contiguous()
if w2_qzeros is not None:
w2_qzeros = w2_qzeros.transpose(1, 2).contiguous()
# w13: packed along K (dim 1), output cols are 2*N (dim 2)
# transpose_output=True yields [E, 2*N, K]
w13_bf16 = _unpack_and_dequant_int4_gptq(
@@ -1435,6 +1450,10 @@ def convert_to_wna16_moe_kernel_format(
):
"""Dispatch weight post-processing to the appropriate per-backend handler.
All non-AWQ frontends must supply weights and scales in N-first
canonical layout ``[E, N_out, K_packed]``. AWQ uses a different
packing axis and is handled by dedicated per-backend helpers.
To add a new backend, implement a ``_process_weights_<name>`` helper and
add a branch here. Backends that rewrite the layer's parameters in place
(e.g. Humming) return ``None``; the caller then skips the param scatter.
@@ -1626,67 +1645,33 @@ def convert_to_wna16_moe_kernel_format(
w2_qzeros,
)
elif backend == WNA16MoEBackend.TRITON:
# Two possible input layouts depending on the quantization source:
#
# MoeWNA16 (uint8): (E, N_out, K // bit8_pack) — N-first
# → just view as uint8 (no-op)
#
# AutoGPTQ/compressed-tensors (int32, K-first):
# (E, K // pack32, N_out)
# → transpose to N-first, then view as uint8 to get
# (E, N_out, K // bit8_pack) [int32 = 4 bytes → 4 uint8s]
# Scales: (E, K // gs, N_out) → transpose → (E, N_out, K // gs)
from vllm.model_executor.layers.quantization.auto_gptq import (
AutoGPTQConfig,
)
# All inputs arrive in canonical N-first format; view as uint8.
w13_uint8 = w13.contiguous().view(torch.uint8)
w2_uint8 = w2.contiguous().view(torch.uint8)
# Repack N-first int32 zero-points to uint8:
# [E, N//pf, K//gs] int32 → [E, N*4//pf, K//gs] uint8
if w13_qzeros is not None and w13_qzeros.dtype == torch.int32:
E13, Np13, Kg13 = w13_qzeros.shape
w13_qzeros = (
w13_qzeros.contiguous()
.view(torch.uint8)
.reshape(E13, Np13, Kg13, 4)
.permute(0, 1, 3, 2)
.reshape(E13, Np13 * 4, Kg13)
.contiguous()
)
if w2_qzeros is not None and w2_qzeros.dtype == torch.int32:
E2, Np2, Kg2 = w2_qzeros.shape
w2_qzeros = (
w2_qzeros.contiguous()
.view(torch.uint8)
.reshape(E2, Np2, Kg2, 4)
.permute(0, 1, 3, 2)
.reshape(E2, Np2 * 4, Kg2)
.contiguous()
)
if isinstance(quant_config, (AutoGPTQConfig, QuantizationArgs)):
# These integrations build in K-first format even when the Triton
# backend is selected. Transpose to N-first first.
w13_uint8 = w13.transpose(1, 2).contiguous().view(torch.uint8)
w2_uint8 = w2.transpose(1, 2).contiguous().view(torch.uint8)
w13_scale = w13_scale.transpose(1, 2).contiguous()
w2_scale = w2_scale.transpose(1, 2).contiguous()
# Zero points from compressed-tensors checkpoints are K-first int32
# with 8 int4 ZPs packed per element: shape (E, K//gs, N//8).
# fused_moe_kernel_gptq_awq expects N-first uint8 with 2 int4 ZPs
# per byte: shape (E, N//2, K//gs), indexed as
# (offs_bn // 2) * stride_bzn + offs_k_group * stride_bzk.
# Conversion steps:
# (E, K//gs, N//8) int32
# → transpose(1,2) → (E, N//8, K//gs) int32
# → view(uint8) → (E, N//8, K//gs*4) [each int32 → 4 bytes]
# → reshape(…,4) → (E, N//8, K//gs, 4) [isolate byte index]
# → permute(0,1,3,2) → (E, N//8, 4, K//gs) [byte index before K]
# → reshape → (E, N//2, K//gs) [kernel expected layout]
# After this, element [e, offs_bn//2, k_group] is the uint8 byte
# holding the two int4 ZPs for output channels offs_bn and offs_bn+1.
if w13_qzeros is not None:
E13, Kg13, Np13 = w13_qzeros.shape
w13_qzeros = (
w13_qzeros.transpose(1, 2)
.contiguous()
.view(torch.uint8)
.reshape(E13, Np13, Kg13, 4)
.permute(0, 1, 3, 2)
.reshape(E13, Np13 * 4, Kg13)
.contiguous()
)
if w2_qzeros is not None:
E2, Kg2, Np2 = w2_qzeros.shape
w2_qzeros = (
w2_qzeros.transpose(1, 2)
.contiguous()
.view(torch.uint8)
.reshape(E2, Np2, Kg2, 4)
.permute(0, 1, 3, 2)
.reshape(E2, Np2 * 4, Kg2)
.contiguous()
)
else:
# MoeWNA16 uses N-first uint8 weights and scales.
w13_uint8 = w13.view(torch.uint8)
w2_uint8 = w2.view(torch.uint8)
return (
w13_uint8,
w2_uint8,
@@ -676,7 +676,7 @@ class RoutedExperts(PluggableLayer):
# Hereafter, `expert_id` is local physical id
# is_transposed: if the dim to shard the weight
# should be flipped. Required by GPTQ, compressed-tensors
# should be flipped. Required by GPTQ/AWQ (K-first format).
# should be whatever dimension intermediate_size_per_partition is
is_transposed = getattr(param, "is_transposed", False)
@@ -18,14 +18,14 @@ where::
"""
import math
from typing import Any, NamedTuple
from typing import NamedTuple
import torch
from torch import nn
from vllm.config import ModelConfig
from vllm.model_executor.custom_op import CustomOp
from vllm.transformers_utils.processor import cached_get_processor, get_processor_config
from vllm.transformers_utils.processor import get_processor_config
from vllm.triton_utils import tl, triton
@@ -144,33 +144,19 @@ class NormParams(NamedTuple):
def _load_norm_params(model_config: ModelConfig) -> NormParams:
"""Resolve the per-channel affine parameters ``(image_mean, image_std,
rescale_factor)`` from the processor config, falling back to the image
processor object."""
model = model_config.model
revision = model_config.revision
rescale_factor)`` from the processor config."""
config = get_processor_config(model_config.model, revision=model_config.revision)
config = config.get("image_processor", config)
config = get_processor_config(model, revision=revision)
# NOTE: do not use cached_image_processor_from_config here — it merges
# mm_processor_kwargs, which mm_device_do_normalize poisons with
# do_normalize=False.
image_processor = cached_get_processor(
model, revision=revision, trust_remote_code=model_config.trust_remote_code
).image_processor
def resolve(key: str) -> Any:
"""Processor config value, falling back to the image_processor."""
if (value := config.get(key)) is not None:
return value
return getattr(image_processor, key, None)
do_rescale = bool(resolve("do_rescale"))
do_normalize = bool(resolve("do_normalize"))
has_norm_params = "image_mean" in config and "image_std" in config
do_normalize = bool(config.get("do_normalize", has_norm_params))
do_rescale = bool(config.get("do_rescale", has_norm_params))
# Parameters whose flag is off are unused; default them to no-ops
# without resolving them.
rescale_factor = resolve("rescale_factor") if do_rescale else 1.0
image_mean = resolve("image_mean") if do_normalize else [0.0] * 3
image_std = resolve("image_std") if do_normalize else [1.0] * 3
rescale_factor = config.get("rescale_factor", 1 / 255) if do_rescale else 1.0
image_mean = config.get("image_mean") if do_normalize else [0.0] * 3
image_std = config.get("image_std") if do_normalize else [1.0] * 3
assert rescale_factor is not None, "rescale_factor is still None after resolution."
assert image_mean is not None, "image_mean is still None after resolution."
@@ -195,6 +181,10 @@ class IdentityInputNorm(nn.Module):
``visual_dtype`` here.
"""
@property
def input_dtype(self) -> torch.dtype | None:
return None
def forward(
self, pixel_values: torch.Tensor, visual_dtype: torch.dtype
) -> torch.Tensor:
@@ -251,6 +241,10 @@ class FusedMMInputNorm(CustomOp):
self.register_buffer("weight", (rescale_factor / std).to(device))
self.register_buffer("bias", (-mean / std).to(device))
@property
def input_dtype(self) -> torch.dtype | None:
return torch.uint8
# ------------------------------------------------------------------
# Internal helpers shared by the platform-specific forward_* methods
# ------------------------------------------------------------------
+48 -4
View File
@@ -59,9 +59,21 @@ def _aiter_mhc_op_accepts_norm(op_name: str) -> bool:
return False
def _has_aiter_mhc_fused_post_pre_delayed_rms_norm() -> bool:
if not HAS_AITER_MHC:
return False
from vllm.platforms.rocm import on_gfx950
# The fused delayed seam kernel is only validated on gfx950.
return on_gfx950()
HAS_AITER_MHC_FUSED = _has_aiter_mhc_fused()
HAS_AITER_MHC_PRE_NORM = _aiter_mhc_op_accepts_norm("mhc_pre")
HAS_AITER_MHC_FUSED_NORM = _aiter_mhc_op_accepts_norm("mhc_fused_post_pre")
HAS_AITER_MHC_FUSED_POST_PRE_DELAYED_RMS_NORM = (
_has_aiter_mhc_fused_post_pre_delayed_rms_norm()
)
def _aiter_mhc_supported(
@@ -388,10 +400,42 @@ class MHCPreDelayedOp(CustomOp):
post_layer_mix: torch.Tensor | None = None,
comb_res_mix: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
# The AITER delayed path drives mhc_pre_gemm_sqrsum against `residual`
# and folds no RMSNorm, so it cannot serve the model-entry broadcast
# (which projects a narrower `x`) or a fused norm. Both are handled by
# TileLang, or by the reference when TileLang is unavailable.
# aiter's fused delayed seam: post-mix, gate projection, and the
# collapse with the carried pre-mix and its RMSNorm. It always applies
# the norm and projects `residual` itself.
if (
HAS_AITER_MHC_FUSED_POST_PRE_DELAYED_RMS_NORM
and x is None
and norm_weight is not None
and _aiter_mhc_supported(residual, norm_weight, supports_norm=True)
):
residual_out = (
torch.empty_like(residual) if sublayer_out is not None else None
)
rest = torch.ops.vllm.mhc_fused_post_pre_delayed_rms_norm_aiter(
residual,
fn,
hc_scale,
hc_base,
rms_eps,
hc_pre_eps,
hc_sinkhorn_eps,
hc_post_mult_value,
sinkhorn_repeat,
pre_mix,
sublayer_out,
post_layer_mix,
comb_res_mix,
norm_weight,
norm_eps,
residual_out,
)
return (residual if residual_out is None else residual_out), *rest
# The unfused AITER delayed path drives mhc_pre_gemm_sqrsum against
# `residual` and folds no RMSNorm, so it cannot serve the model-entry
# broadcast (which projects a narrower `x`) or a fused norm the branch
# above did not take. Both are handled by TileLang, or by the reference
# when TileLang is unavailable.
if (
x is None
and norm_weight is None
@@ -171,16 +171,24 @@ class ClassifierPoolerHead(SequencePoolerHead):
pooled_data = pooled_data.to(self.head_dtype)
if self.classifier is not None:
logits = self.classifier(pooled_data)
logits: SequencePoolerHeadOutput = self.classifier(pooled_data)
else:
logits = pooled_data
# logits shape: [batchsize, num_labels]
# Affine score calibration: activation((logit - mean) / sigma)
if self.logit_mean is not None:
logits = logits - self.logit_mean
logits = (
[value - self.logit_mean for value in logits]
if isinstance(logits, list)
else logits - self.logit_mean
)
if self.logit_sigma is not None:
logits = logits / self.logit_sigma
logits = (
[value / self.logit_sigma for value in logits]
if isinstance(logits, list)
else logits / self.logit_sigma
)
if self.activation is not None:
flags = [p.use_activation for p in pooling_params]
@@ -130,7 +130,7 @@ def pooler_for_classify(
logit_mean=model_config.pooler_config.logit_mean,
logit_sigma=model_config.pooler_config.logit_sigma,
activation=resolve_classifier_act_fn(
model_config, static_num_labels=True, act_fn=act_fn
model_config, static_num_labels=False, act_fn=act_fn
),
)
@@ -626,19 +626,31 @@ class AutoGPTQMoEMethod(FusedMoEMethodBase):
layer.register_parameter("w2_bias", None)
w2_bias = None
# Normalize GPTQ K-first layout to canonical N-first format.
w13 = layer.w13_qweight.data.transpose(1, 2).contiguous()
w2 = layer.w2_qweight.data.transpose(1, 2).contiguous()
w13_scale = layer.w13_scales.data.transpose(1, 2).contiguous()
w2_scale = layer.w2_scales.data.transpose(1, 2).contiguous()
w13_qzeros = getattr(layer, "w13_qzeros", None)
w2_qzeros = getattr(layer, "w2_qzeros", None)
if w13_qzeros is not None:
w13_qzeros = w13_qzeros.data.transpose(1, 2).contiguous()
if w2_qzeros is not None:
w2_qzeros = w2_qzeros.data.transpose(1, 2).contiguous()
converted = convert_to_wna16_moe_kernel_format(
backend=self.wna16_moe_backend,
layer=layer,
quant_config=self.quant_config,
input_dtype=self.input_dtype,
w13=layer.w13_qweight,
w2=layer.w2_qweight,
w13_scale=layer.w13_scales,
w2_scale=layer.w2_scales,
w13=w13,
w2=w2,
w13_scale=w13_scale,
w2_scale=w2_scale,
w13_bias=w13_bias,
w2_bias=w2_bias,
w13_qzeros=getattr(layer, "w13_qzeros", None),
w2_qzeros=getattr(layer, "w2_qzeros", None),
w13_qzeros=w13_qzeros,
w2_qzeros=w2_qzeros,
)
if converted is None:
@@ -112,10 +112,10 @@ class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
WNA16MoEBackend.MARLIN,
WNA16MoEBackend.BATCHED_MARLIN,
]
self.is_transposed = self.wna16_backend not in (
WNA16MoEBackend.FLASHINFER_TRTLLM,
WNA16MoEBackend.HUMMING,
)
# CT checkpoints always load in N-first format [E, N, K_packed].
# Backend-specific transposition is handled in
# convert_to_wna16_moe_kernel_format.
self.is_transposed = False
if self.is_marlin:
assert check_moe_marlin_supports_config(
@@ -141,80 +141,31 @@ class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
num_groups_w2: int | None = None,
num_groups_w13: int | None = None,
) -> tuple[int, int, int]:
"""Get the shape of the weight based on the weight name, number of experts
hidden size, intermediate size per partition, number of groups for w2,
and number of groups for w13. Pass in num_groups_w2 and num_groups_w13
for weight scales/zero_points.
"""Return N-first buffer shape for the given weight/scale/zp tensor.
All CT MoE weights are allocated in the checkpoint's native N-first
layout ``[E, N, K_packed]``. Backend-specific transposition (e.g. to
Marlin's K-first layout) is deferred to
``convert_to_wna16_moe_kernel_format``.
"""
if weight_name in ("w13_scale", "w13_zp"):
assert num_groups_w13 is not None, (
"num_groups_w13 must be provided for weight scales/zero_points"
)
if weight_name in ("w2_scale", "w2_zp"):
assert num_groups_w2 is not None, (
"num_groups_w2 must be provided for weight scales/zero_points"
)
w13_num_shards = 2 if self.moe.is_act_and_mul else 1
shape_map: dict[str, dict[str, tuple[int, int | None, int | None]]] = {
"w13_weight": {
"Flashinfer": (
num_experts,
w13_num_shards * intermediate_size_per_partition,
self._packed_dim(hidden_size),
),
"Marlin": (
num_experts,
self._packed_dim(hidden_size),
w13_num_shards * intermediate_size_per_partition,
),
},
"w13_scale": {
"Flashinfer": (
num_experts,
w13_num_shards * intermediate_size_per_partition,
num_groups_w13,
),
"Marlin": (
num_experts,
num_groups_w13,
w13_num_shards * intermediate_size_per_partition,
),
},
"w13_zp": {
"Marlin": (
num_experts,
num_groups_w13,
self._packed_dim(w13_num_shards * intermediate_size_per_partition),
),
},
"w2_weight": {
"Flashinfer": (
num_experts,
hidden_size,
self._packed_dim(intermediate_size_per_partition),
),
"Marlin": (
num_experts,
self._packed_dim(intermediate_size_per_partition),
hidden_size,
),
},
"w2_scale": {
"Flashinfer": (num_experts, hidden_size, num_groups_w2),
"Marlin": (num_experts, num_groups_w2, hidden_size),
},
"w2_zp": {
"Marlin": (
num_experts,
num_groups_w2,
self._packed_dim(hidden_size),
),
},
w13_n = w13_num_shards * intermediate_size_per_partition
pf = self.packed_factor
shape_map = {
"w13_weight": (num_experts, w13_n, hidden_size // pf),
"w13_scale": (num_experts, w13_n, num_groups_w13),
"w13_zp": (num_experts, w13_n // pf, num_groups_w13),
"w2_weight": (
num_experts,
hidden_size,
intermediate_size_per_partition // pf,
),
"w2_scale": (num_experts, hidden_size, num_groups_w2),
"w2_zp": (num_experts, hidden_size // pf, num_groups_w2),
}
backend_key = "Marlin" if self.is_transposed else "Flashinfer"
shape = shape_map[weight_name][backend_key]
assert shape[1] is not None and shape[2] is not None
return shape[0], shape[1], shape[2]
shape = shape_map[weight_name]
assert isinstance(shape, tuple) and all(isinstance(d, int) for d in shape)
return shape # type: ignore[return-value]
def create_weights(
self,
@@ -225,11 +176,8 @@ class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
params_dtype: torch.dtype,
**extra_weight_attrs,
):
# Will transpose the loaded weight along the
# intermediate and hidden dim sizes. Will
# shard for TP along the transposed dims
extra_weight_attrs.update(
{"is_transposed": self.is_transposed, "quant_method": self.strategy}
{"is_transposed": False, "quant_method": self.strategy}
)
w13_weight = torch.nn.Parameter(
@@ -440,12 +388,10 @@ class CompressedTensorsWNA16MoEMethod(CompressedTensorsMoEMethod):
replace_parameter(layer, "w13_weight_scale", w13_scales)
replace_parameter(layer, "w2_weight_scale", w2_scales)
# CPU fused_experts_cpu and the RDNA3 HIP kernel require zero points
# even for symmetric quant (the oracle synthesizes them).
# CPU fused_experts_cpu requires zero points even for symmetric quant.
# EMULATION bakes ZP into the dequantized bf16 weights — ZP is None.
if (
not self.symmetric
or self.wna16_backend in (WNA16MoEBackend.CPU, WNA16MoEBackend.RDNA3)
not self.symmetric or self.wna16_backend == WNA16MoEBackend.CPU
) and self.wna16_backend != WNA16MoEBackend.EMULATION:
assert w13_qzeros is not None and w2_qzeros is not None
replace_parameter(layer, "w13_weight_zero_point", w13_qzeros)
@@ -635,10 +635,14 @@ class MoeWNA16Method(FusedMoEMethodBase):
tensor = loaded_weight.view(
layer.moe_config.tp_size, -1, loaded_weight.size(1)
)[tp_rank]
# qzeros are packed along the intermediate dim by
# bit8_pack_factor, so the w1/w3 boundary is in packed units
# (equals shard_size // 2 only for 4-bit).
shard_zp_size = shard_size // layer.quant_config.bit8_pack_factor
if shard_id == "w1":
param.data[expert_id, : shard_size // 2] = tensor
param.data[expert_id, :shard_zp_size] = tensor
else:
param.data[expert_id, shard_size // 2 :] = tensor
param.data[expert_id, shard_zp_size:] = tensor
return True if return_success else None
elif "w2_qzeros" in weight_name:
param.data[expert_id] = loaded_weight.view(
@@ -46,8 +46,10 @@ def packed_qk_rope_(xqkv: torch.Tensor, freqs_cis: torch.Tensor) -> None:
freqs_cis: contiguous (seqlen, headdim // 2) complex64 rotary freqs,
read through its interleaved re/im fp32 view.
Bitwise identical to ``ApplyRotaryEmb(enable_fp32_compute=True)`` applied
to Q and K separately, but in one kernel with ~5x less memory traffic.
Matches ``ApplyRotaryEmb(enable_fp32_compute=True)`` applied to Q and K
separately to within one ULP, but in one kernel with ~5x less memory
traffic. Both compute in fp32; the gap is which product the compiler
keeps exact inside the fused multiply-add, which differs per backend.
Requires triton: callers must check HAS_TRITON and use the unfused path
otherwise. Contract violations raise.
+5 -2
View File
@@ -526,6 +526,9 @@ class AriaForConditionalGeneration(nn.Module, SupportsMultiModal):
logits = self.logits_processor(self.lm_head, hidden_states)
return logits
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
def load_weights(
self,
weights: Iterable[tuple[str, torch.Tensor]],
) -> set[str]:
loader = AutoWeightsLoader(self)
loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
+2
View File
@@ -134,6 +134,8 @@ class ColQwen3Model(Qwen3VLForConditionalGeneration, SupportsLateInteraction):
# Mark this as a pooling model so vLLM routes to pooler path
is_pooling_model = True
# Mark as false to avoid collision with the checkpoint's custom code path
supports_mm_device_do_normalize = False
# Override hf_to_vllm_mapper to handle ColQwen3 weight naming.
# NOTE: WeightsMapper applies ALL matching prefix rules sequentially
@@ -1493,7 +1493,7 @@ class DiffusionSampler:
# [tile * W, vocab] copies, so a tile is also bounded by free memory.
widths_np = states.canvas_width_np[decode_slots_np]
order = np.argsort(widths_np, kind="stable")
free = current_platform.mem_get_info()[0] if num_decode > 0 else 0
free = torch.accelerator.get_memory_info()[0] if num_decode > 0 else 0
run_start = 0
while run_start < num_decode:
W = int(widths_np[order[run_start]])
+1 -1
View File
@@ -529,7 +529,7 @@ class FunAudioChatProcessingInfo(BaseProcessingInfo):
return TokenizersBackend.from_pretrained(
self.model_id,
subfolder="speech_tokenizer",
revision=self.ctx.model_config.tokenizer_revision,
revision=self.ctx.model_config.revision,
)
def get_feature_extractor(self) -> WhisperFeatureExtractor:
+13 -4
View File
@@ -846,13 +846,22 @@ class Gemma4SelfDecoderLayers(nn.Module):
# Shared references to modules owned by Gemma4Model — must be
# inside this nn.Module so torch.compile captures them.
self.embed_tokens = embed_tokens
self.normalizer = normalizer
self.embed_tokens_per_layer = embed_tokens_per_layer
self.embed_scale_per_layer = embed_scale_per_layer
self.per_layer_model_projection = per_layer_model_projection
self.per_layer_projection_norm = per_layer_projection_norm
self.per_layer_input_scale = per_layer_input_scale
self.per_layer_projection_scale = per_layer_projection_scale
# Register the shared scalars as buffers so they follow the model on
# .to(device); plain attributes stay on CPU.
self.register_buffer("normalizer", normalizer, persistent=False)
self.register_buffer(
"embed_scale_per_layer", embed_scale_per_layer, persistent=False
)
self.register_buffer(
"per_layer_input_scale", per_layer_input_scale, persistent=False
)
self.register_buffer(
"per_layer_projection_scale", per_layer_projection_scale, persistent=False
)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids) * self.normalizer
@@ -45,6 +45,7 @@ from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
@@ -575,6 +576,7 @@ class InternS1ProForConditionalGeneration(
self.visual = Qwen3_VisionTransformer(
config.vision_config,
norm_eps=getattr(config, "rms_norm_eps", 1e-6),
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
@@ -21,6 +21,7 @@ from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
@@ -496,6 +497,7 @@ class InternS2MobiusForConditionalGeneration(InternS2PreviewForConditionalGenera
config.vision_config,
norm_eps=getattr(config, "rms_norm_eps", 1e-6),
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
+9 -3
View File
@@ -3,7 +3,7 @@
import math
from collections.abc import Iterable, Mapping, Sequence
from typing import Annotated, Literal
from typing import Annotated, Any, Literal, cast
import torch
import torch.nn as nn
@@ -212,8 +212,14 @@ class Mistral3ProcessingInfo(BaseProcessingInfo):
) -> PixtralHFEncoderInfo:
processor = self.get_hf_processor()
size = processor.image_processor.size
merged_kwargs = self.ctx.get_merged_mm_kwargs(mm_processor_kwargs or {})
if override_size := merged_kwargs.get("size"):
merged_mm_kwargs = self._merge_and_resolve_mm_processor_kwargs(
mm_processor_kwargs or {}
)
image_mm_kwargs = cast(
Mapping[str, Any],
merged_mm_kwargs.get("images_kwargs", {}),
)
if override_size := image_mm_kwargs.get("size"):
size = size | override_size
image_size = size["longest_edge"]
+7 -3
View File
@@ -1976,7 +1976,8 @@ class Qwen2_5_VLForConditionalGeneration(
for _ in range(max_batch_size)
]
# Create dummy pixel_values
# Create dummy pixel_values; uint8 when normalization is fused
# on-device. Contents are overwritten before every replay.
patch_embed = self.visual.patch_embed
in_channels = patch_embed.proj.in_channels
patch_size = patch_embed.patch_size
@@ -1985,8 +1986,11 @@ class Qwen2_5_VLForConditionalGeneration(
flattened_patch_size = (
in_channels * temporal_patch_size * patch_size * patch_size
)
dummy_pixel_values = torch.randn(
total_patches, flattened_patch_size, device=device, dtype=dtype
dummy_pixel_values = torch.zeros(
total_patches,
flattened_patch_size,
device=device,
dtype=self.visual.input_norm.input_dtype or dtype,
)
# Override max_seqlen with a safe upper bound for capture.
+137 -21
View File
@@ -28,7 +28,7 @@
import math
from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence
from functools import partial
from typing import Annotated, Any, Literal, TypeAlias
from typing import Annotated, Any, Literal, TypeAlias, cast
import numpy as np
import torch
@@ -865,6 +865,118 @@ class Qwen2VLProcessingInfo(BaseProcessingInfo):
def get_supported_mm_limits(self) -> Mapping[str, int | None]:
return {"image": None, "video": None}
@staticmethod
def _complete_mm_processor_size_aliases(
mm_kwargs: Mapping[str, object],
) -> dict[str, object]:
"""Complete missing Qwen-VL size aliases.
Qwen-VL accepts ``size.shortest_edge`` / ``min_pixels`` and
``size.longest_edge`` / ``max_pixels`` as equivalent controls. When
only one representation is provided with a non-``None`` value, add the
missing equivalent representation. If both are already present, leave
them unchanged even when their values conflict.
Apply this independently to the flat kwargs and to each existing
``images_kwargs`` / ``videos_kwargs`` mapping. Values are not propagated
between these mappings.
"""
def add_missing_size_aliases(
kwargs: Mapping[str, object],
) -> dict[str, object]:
"""Add missing size aliases within a kwargs mapping."""
out_kwargs = dict(kwargs)
# Copy `size` separately because `out_kwargs` is a shallow copy and
# size edges may be added below.
raw_size = cast(
Mapping[str, object] | None,
out_kwargs.get("size"),
)
size_kwargs = {} if raw_size is None else dict(raw_size)
for edge_key, pixel_key in (
("shortest_edge", "min_pixels"),
("longest_edge", "max_pixels"),
):
# Add the pixel alias from `size` when only the size edge is
# present.
if pixel_key not in out_kwargs:
if edge_key in size_kwargs and size_kwargs[edge_key] is not None:
out_kwargs[pixel_key] = size_kwargs[edge_key]
continue
pixel_value = out_kwargs[pixel_key]
# HF treats `min_pixels` / `max_pixels` set to None as no size
# override, so do not propagate them to the equivalent size edge.
if pixel_value is None:
continue
# Add the size edge when only the pixel alias is present.
if edge_key not in size_kwargs:
size_kwargs[edge_key] = pixel_value
out_kwargs["size"] = size_kwargs
return out_kwargs
prepared_mm_kwargs = add_missing_size_aliases(mm_kwargs)
# Complete aliases independently inside existing image/video kwargs;
# flat values are not copied into the nested mappings.
for nested_kwargs_key in ("images_kwargs", "videos_kwargs"):
nested_kwargs = prepared_mm_kwargs.get(nested_kwargs_key)
if isinstance(nested_kwargs, Mapping):
prepared_mm_kwargs[nested_kwargs_key] = add_missing_size_aliases(
nested_kwargs
)
return prepared_mm_kwargs
def _merge_and_resolve_mm_processor_kwargs(
self,
mm_kwargs: Mapping[str, object],
) -> dict[str, Any]:
"""Merge configured and request Qwen-VL ``mm_processor_kwargs``.
Request-side ``size.shortest_edge`` / ``min_pixels`` and
``size.longest_edge`` / ``max_pixels`` aliases are completed before the
merge so request precedence is preserved across equivalent
representations.
"""
# Complete request-side Qwen-VL size aliases before merging with
# configured kwargs.
prepared_mm_kwargs = self._complete_mm_processor_size_aliases(mm_kwargs)
return super()._merge_and_resolve_mm_processor_kwargs(prepared_mm_kwargs)
@staticmethod
def _get_vision_size(
mm_kwargs: Mapping[str, object],
default_size: Mapping[str, int] | None = None,
) -> dict[str, int]:
"""Resolve Qwen-VL vision size kwargs with optional processor defaults.
``size`` overrides any processor defaults, then ``min_pixels`` and
``max_pixels`` override the corresponding size edges.
"""
size = dict(default_size) if default_size is not None else {}
override_size = cast(
Mapping[str, int] | None,
mm_kwargs.get("size"),
)
if override_size is not None:
size.update(override_size)
min_pixels = cast(int | None, mm_kwargs.get("min_pixels"))
if min_pixels is not None:
size["shortest_edge"] = min_pixels
max_pixels = cast(int | None, mm_kwargs.get("max_pixels"))
if max_pixels is not None:
size["longest_edge"] = max_pixels
return size
def get_mm_max_tokens_per_item(
self,
seq_len: int,
@@ -883,7 +995,7 @@ class Qwen2VLProcessingInfo(BaseProcessingInfo):
do_resize: bool = True,
image_processor: Qwen2VLImageProcessor,
mm_kwargs: Mapping[str, object],
modality: str | None = None,
modality: Literal["image", "video"] | None = None,
) -> tuple[ImageSize, int]:
hf_config = self.get_hf_config()
vision_config = hf_config.vision_config
@@ -891,14 +1003,16 @@ class Qwen2VLProcessingInfo(BaseProcessingInfo):
merge_size = vision_config.spatial_merge_size
temporal_patch_size = vision_config.temporal_patch_size
mm_kwargs = self.ctx.get_merged_mm_kwargs(mm_kwargs, modality=modality)
size = image_processor.size
if override_size := mm_kwargs.get("size"):
size = size | override_size
if (override_min_pixels := mm_kwargs.get("min_pixels")) is not None:
size = size | {"shortest_edge": override_min_pixels}
if (override_max_pixels := mm_kwargs.get("max_pixels")) is not None:
size = size | {"longest_edge": override_max_pixels}
if modality is None:
modality = "image"
merged_mm_kwargs = self._merge_and_resolve_mm_processor_kwargs(mm_kwargs)
scope = "images_kwargs" if modality == "image" else "videos_kwargs"
scoped_mm_kwargs = merged_mm_kwargs.get(scope, {})
size = self._get_vision_size(
scoped_mm_kwargs,
default_size=image_processor.size,
)
if do_resize:
resized_height, resized_width = smart_resize(
@@ -986,14 +1100,12 @@ class Qwen2VLProcessingInfo(BaseProcessingInfo):
if max_pixels is None:
image_processor = self.get_image_processor()
mm_kwargs = self.ctx.get_merged_mm_kwargs({}, modality="image")
size = image_processor.size
if override_size := mm_kwargs.get("size"):
size = size | override_size
if (override_min_pixels := mm_kwargs.get("min_pixels")) is not None:
size = size | {"shortest_edge": override_min_pixels}
if (override_max_pixels := mm_kwargs.get("max_pixels")) is not None:
size = size | {"longest_edge": override_max_pixels}
merged_mm_kwargs = self._merge_and_resolve_mm_processor_kwargs({})
image_mm_kwargs = merged_mm_kwargs.get("images_kwargs", {})
size = self._get_vision_size(
image_mm_kwargs,
default_size=image_processor.size,
)
max_pixels = size["longest_edge"]
@@ -1616,7 +1728,8 @@ class Qwen2VLForConditionalGeneration(
for _ in range(max_batch_size)
]
# Create dummy pixel_values.
# Create dummy pixel_values; uint8 when normalization is fused
# on-device. Contents are overwritten before every replay.
patch_embed = self.visual.patch_embed
in_channels = patch_embed.proj.in_channels
patch_size = patch_embed.patch_size
@@ -1625,8 +1738,11 @@ class Qwen2VLForConditionalGeneration(
flattened_patch_size = (
in_channels * temporal_patch_size * patch_size * patch_size
)
dummy_pixel_values = torch.randn(
total_patches, flattened_patch_size, device=device, dtype=dtype
dummy_pixel_values = torch.zeros(
total_patches,
flattened_patch_size,
device=device,
dtype=self.visual.input_norm.input_dtype or dtype,
)
# max_seqlen.item() gets baked into the CUDA graph at capture time.
+3
View File
@@ -39,6 +39,7 @@ from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.layernorm import GemmaRMSNorm as Qwen3_5RMSNorm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
@@ -519,6 +520,7 @@ class Qwen3_5ForConditionalGeneration(Qwen3VLForConditionalGeneration, IsHybrid)
config.vision_config,
norm_eps=getattr(config, "rms_norm_eps", 1e-6),
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
@@ -741,6 +743,7 @@ class Qwen3_5MoeForConditionalGeneration(
config.vision_config,
norm_eps=getattr(config, "rms_norm_eps", 1e-6),
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
@@ -34,7 +34,6 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
VocabParallelEmbedding,
)
from vllm.multimodal.inputs import NestedTensors
from vllm.platforms import current_platform
from vllm.transformers_utils.config import set_default_rope_theta
from vllm.transformers_utils.repo_utils import get_hf_file_bytes
from vllm.v1.attention.backend import AttentionType
@@ -622,15 +621,6 @@ class DFlashQwen3Model(nn.Module):
# --- Grouped RMSNorm K across all layers ([L, num_ctx, nkv, hd]) ---
# The weight is selected per layer by the outermost (layer) index.
all_k_normed = torch.empty_like(all_k)
if current_platform.is_xpu():
for layer_idx in range(all_k.shape[0]):
ops.rms_norm(
all_k_normed[layer_idx],
all_k[layer_idx],
self._k_norm_weights[layer_idx],
self._rms_norm_eps,
)
return all_k_normed
ops.rms_norm(
all_k_normed,
all_k,
+125 -59
View File
@@ -27,7 +27,7 @@
from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping, Sequence
from functools import lru_cache, partial
from itertools import islice
from typing import Any
from typing import Any, Literal
import numpy as np
import torch
@@ -67,6 +67,10 @@ from vllm.model_executor.layers.attention.mm_encoder_attention import (
MMEncoderAttention,
)
from vllm.model_executor.layers.conv import Conv3dLayer
from vllm.model_executor.layers.fusion.mm_input_norm import (
IdentityInputNorm,
build_mm_input_norm,
)
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
RowParallelLinear,
@@ -566,6 +570,7 @@ class Qwen3_VisionTransformer(nn.Module):
vision_config: Qwen3VLVisionConfig,
norm_eps: float = 1e-6,
quant_config: QuantizationConfig | None = None,
input_norm: nn.Module | None = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -605,6 +610,7 @@ class Qwen3_VisionTransformer(nn.Module):
in_channels=vision_config.in_channels,
hidden_size=self.hidden_size,
)
self.input_norm = input_norm if input_norm is not None else IdentityInputNorm()
self.pos_embed = nn.Embedding(self.num_position_embeddings, self.hidden_size)
@@ -858,7 +864,9 @@ class Qwen3_VisionTransformer(nn.Module):
*,
encoder_metadata: dict[str, torch.Tensor] | None = None,
) -> torch.Tensor:
hidden_states = x.to(device=self.device, dtype=self.dtype, non_blocking=True)
hidden_states = self.input_norm(
x.to(device=self.device, non_blocking=True), self.dtype
)
hidden_states = self.patch_embed(hidden_states)
if encoder_metadata is None:
@@ -936,6 +944,16 @@ class Qwen3VLProcessingInfo(Qwen2VLProcessingInfo):
allow_missing_mm_embeddings=self.allow_missing_mm_embeddings,
)
def get_supported_mm_processor_kwargs(self) -> dict[str, set[str]]:
supported = super().get_supported_mm_processor_kwargs()
# vLLM has historically accepted `min_pixels` / `max_pixels` for
# Qwen3-VL video. Include them in the routing schema even though
# Qwen3VLVideoProcessor only accepts the equivalent `size`; they are
# folded into `size` before calling HF.
supported["videos_kwargs"].update({"min_pixels", "max_pixels"})
return supported
def _get_vision_info(
self,
*,
@@ -945,7 +963,7 @@ class Qwen3VLProcessingInfo(Qwen2VLProcessingInfo):
do_resize: bool = True,
image_processor: Qwen2VLImageProcessor | Qwen3VLVideoProcessor,
mm_kwargs: Mapping[str, object],
modality: str | None = None,
modality: Literal["image", "video"] | None = None,
) -> tuple[ImageSize, int]:
is_video = isinstance(image_processor, Qwen3VLVideoProcessor)
@@ -957,14 +975,14 @@ class Qwen3VLProcessingInfo(Qwen2VLProcessingInfo):
if modality is None:
modality = "video" if is_video else "image"
mm_kwargs = self.ctx.get_merged_mm_kwargs(mm_kwargs, modality=modality)
size = image_processor.size
if override_size := mm_kwargs.get("size"):
size = size | override_size
if (override_min_pixels := mm_kwargs.get("min_pixels")) is not None:
size = size | {"shortest_edge": override_min_pixels}
if (override_max_pixels := mm_kwargs.get("max_pixels")) is not None:
size = size | {"longest_edge": override_max_pixels}
merged_mm_kwargs = self._merge_and_resolve_mm_processor_kwargs(mm_kwargs)
scope = "videos_kwargs" if modality == "video" else "images_kwargs"
scoped_mm_kwargs = merged_mm_kwargs.get(scope, {})
size = self._get_vision_size(
scoped_mm_kwargs,
default_size=image_processor.size,
)
if do_resize:
if is_video:
@@ -1022,9 +1040,13 @@ class Qwen3VLProcessingInfo(Qwen2VLProcessingInfo):
) -> int:
video_processor = self.get_video_processor()
mm_kwargs = self.ctx.get_merged_mm_kwargs({}, modality="video")
video_size = mm_kwargs.get("size", video_processor.size)
temporal_patch_size = mm_kwargs.get(
merged_mm_kwargs = self._merge_and_resolve_mm_processor_kwargs({})
video_mm_kwargs = merged_mm_kwargs.get("videos_kwargs", {})
video_size = self._get_vision_size(
video_mm_kwargs,
default_size=video_processor.size,
)
temporal_patch_size = video_mm_kwargs.get(
"temporal_patch_size", video_processor.temporal_patch_size
)
@@ -1154,9 +1176,13 @@ class Qwen3VLDummyInputsBuilder(BaseDummyInputsBuilder[Qwen3VLProcessingInfo]):
video_processor = self.info.get_video_processor()
mm_kwargs = self.info.ctx.get_merged_mm_kwargs({}, modality="video")
video_size = mm_kwargs.get("size", video_processor.size)
temporal_patch_size = mm_kwargs.get(
merged_mm_kwargs = self.info._merge_and_resolve_mm_processor_kwargs({})
video_mm_kwargs = merged_mm_kwargs.get("videos_kwargs", {})
video_size = self.info._get_vision_size(
video_mm_kwargs,
default_size=video_processor.size,
)
temporal_patch_size = video_mm_kwargs.get(
"temporal_patch_size", video_processor.temporal_patch_size
)
@@ -1172,13 +1198,13 @@ class Qwen3VLDummyInputsBuilder(BaseDummyInputsBuilder[Qwen3VLProcessingInfo]):
# over enough frames that the cap is not binding for the dummy.
# This takes precedence over a shrinking num_frames override, which
# would otherwise reintroduce the under-profiling.
if mm_kwargs.get("cap_pixels_per_frame"):
max_video_tokens = mm_kwargs.get(
if video_mm_kwargs.get("cap_pixels_per_frame"):
max_video_tokens = video_mm_kwargs.get(
"max_video_tokens",
getattr(video_processor, "max_video_tokens", 768),
)
patch_size = mm_kwargs.get("patch_size", video_processor.patch_size)
merge_size = mm_kwargs.get("merge_size", video_processor.merge_size)
patch_size = video_mm_kwargs.get("patch_size", video_processor.patch_size)
merge_size = video_mm_kwargs.get("merge_size", video_processor.merge_size)
per_frame_cap = max_video_tokens * (patch_size * merge_size) ** 2
target_num_frames = max(
target_num_frames,
@@ -1340,6 +1366,47 @@ class Qwen3VLMultiModalProcessor(BaseMultiModalProcessor[Qwen3VLProcessingInfo])
if not hf_data:
return self._finalize_hf_mm_data(hf_data, hf_kwargs, passthrough_data)
# Merge and resolve the multimodal processor kwargs once so every HF
# call below starts from the same engine/request state and scoped form.
merged_mm_kwargs = self.info._merge_and_resolve_mm_processor_kwargs(hf_kwargs)
if "images_kwargs" in merged_mm_kwargs:
image_scoped_kwargs = dict(merged_mm_kwargs["images_kwargs"])
# Qwen2VLImageProcessor requires both `size` edges. If a partial size
# override is passed, fill missing edges from the processor defaults
# before any HF call.
if image_scoped_kwargs.keys() & {"size", "min_pixels", "max_pixels"}:
default_image_size = self.info.get_image_processor().size
image_scoped_kwargs["size"] = self.info._get_vision_size(
image_scoped_kwargs,
default_size=default_image_size,
)
merged_mm_kwargs["images_kwargs"] = image_scoped_kwargs
if "videos_kwargs" in merged_mm_kwargs:
video_scoped_kwargs = dict(merged_mm_kwargs["videos_kwargs"])
# Qwen3VLVideoProcessor requires both `size` edges. If a partial size
# override is passed, fill missing edges from the processor defaults
# before any HF call.
if video_scoped_kwargs.keys() & {"size", "min_pixels", "max_pixels"}:
default_video_size = self.info.get_video_processor().size
video_scoped_kwargs["size"] = self.info._get_vision_size(
video_scoped_kwargs,
default_size=default_video_size,
)
# Qwen3VLVideoProcessor does not accept vLLM's min/max pixel
# compatibility kwargs. They have already been folded into `size`,
# so remove them before any HF call, including calls that contain
# only text/images.
video_scoped_kwargs.pop("min_pixels", None)
video_scoped_kwargs.pop("max_pixels", None)
merged_mm_kwargs["videos_kwargs"] = video_scoped_kwargs
# Separate video processing from image processing. Because the videos
# are processed into several image patches
video_input_ids_lst: list[list[int]] = []
@@ -1365,32 +1432,22 @@ class Qwen3VLMultiModalProcessor(BaseMultiModalProcessor[Qwen3VLProcessingInfo])
# used to calculate the timestamps. Make sure that
# do_sample_frames in mm_kwargs is false for presampled videos.
# NOTE: a copy of is created to update do_sample_frames,
# otherwise mm_hash for the object will be incorrect.
video_mm_kwargs: dict[str, Any] = dict(hf_kwargs)
merged = self.info.ctx.get_merged_mm_kwargs(hf_kwargs, modality="video")
if merged.keys() & {"size", "min_pixels", "max_pixels"}:
video_size = dict(self.info.get_video_processor().size)
size_override = merged.get("size")
if size_override is not None:
video_size = video_size | size_override
min_pixels = merged.get("min_pixels")
if min_pixels is not None:
video_size["shortest_edge"] = min_pixels
max_pixels = merged.get("max_pixels")
if max_pixels is not None:
video_size["longest_edge"] = max_pixels
video_mm_kwargs["size"] = video_size
sampled_fps = video_mm_kwargs.get("fps")
# The root copy is shallow, so give each item its own video
# scope before modifying per-video values below.
video_mm_kwargs = dict(merged_mm_kwargs)
video_scoped_kwargs = dict(video_mm_kwargs.get("videos_kwargs", {}))
video_mm_kwargs["videos_kwargs"] = video_scoped_kwargs
sampled_fps = video_scoped_kwargs.get("fps")
if is_list_of(sampled_fps, float):
video_mm_kwargs["fps"] = sampled_fps[item_idx]
sampled_num_frames = video_mm_kwargs.get("num_frames")
video_scoped_kwargs["fps"] = sampled_fps[item_idx]
sampled_num_frames = video_scoped_kwargs.get("num_frames")
if is_list_of(sampled_num_frames, int):
video_mm_kwargs["num_frames"] = sampled_num_frames[item_idx]
if "do_sample_frames" not in video_mm_kwargs:
video_scoped_kwargs["num_frames"] = sampled_num_frames[item_idx]
if "do_sample_frames" not in video_scoped_kwargs:
# qwen_vl_utils already has "do_sample_frames" in
# mm_kwargs, don't overwrite it.
video_mm_kwargs["do_sample_frames"] = metadata.get(
video_scoped_kwargs["do_sample_frames"] = metadata.get(
"do_sample_frames", False
)
@@ -1401,9 +1458,9 @@ class Qwen3VLMultiModalProcessor(BaseMultiModalProcessor[Qwen3VLProcessingInfo])
# Compute timestamps here where we have access to metadata
timestamps = self.info._get_video_second_idx(
metadata=metadata,
do_sample_frames=video_mm_kwargs["do_sample_frames"],
sampled_fps=video_mm_kwargs.get("fps"),
sampled_num_frames=video_mm_kwargs.get("num_frames"),
do_sample_frames=video_scoped_kwargs["do_sample_frames"],
sampled_fps=video_scoped_kwargs.get("fps"),
sampled_num_frames=video_scoped_kwargs.get("num_frames"),
)
timestamps_per_video.append(timestamps)
@@ -1415,8 +1472,11 @@ class Qwen3VLMultiModalProcessor(BaseMultiModalProcessor[Qwen3VLProcessingInfo])
# to prevent HF's BaseVideoProcessor.preprocess() from
# filling in the class default (fps=2) via setdefault(),
# which would conflict with num_frames (mutually exclusive).
if "num_frames" in video_mm_kwargs and "fps" not in video_mm_kwargs:
video_mm_kwargs["fps"] = None
if (
"num_frames" in video_scoped_kwargs
and "fps" not in video_scoped_kwargs
):
video_scoped_kwargs["fps"] = None
video_outputs = self.info.ctx.call_hf_processor(
self.info.get_hf_processor(**video_mm_kwargs),
@@ -1477,11 +1537,14 @@ class Qwen3VLMultiModalProcessor(BaseMultiModalProcessor[Qwen3VLProcessingInfo])
else:
video_outputs = dict()
# fps/num_frames are video-only kwargs already consumed by the loop;
# exclude them so the text/image processor call below never gets a list.
non_video_mm_kwargs = {
k: v for k, v in hf_kwargs.items() if k not in ("fps", "num_frames")
}
# The root copy is shallow, so copy the video scope before removing
# per-video kwargs to avoid mutating `merged_mm_kwargs`.
non_video_mm_kwargs = dict(merged_mm_kwargs)
if "videos_kwargs" in non_video_mm_kwargs:
non_video_scoped_kwargs = dict(non_video_mm_kwargs["videos_kwargs"])
non_video_scoped_kwargs.pop("fps", None)
non_video_scoped_kwargs.pop("num_frames", None)
non_video_mm_kwargs["videos_kwargs"] = non_video_scoped_kwargs
processed_data = self.info.ctx.call_hf_processor(
self.info.get_hf_processor(**non_video_mm_kwargs),
hf_data,
@@ -1813,6 +1876,7 @@ class Qwen3VLForConditionalGeneration(
supports_encoder_tp_data = True
supports_tower_connector_lora = True
supports_mm_device_do_normalize = True
supported_video_pruning_methods = ("evs", "vidcom2")
@@ -1863,6 +1927,7 @@ class Qwen3VLForConditionalGeneration(
config.vision_config,
norm_eps=getattr(config, "rms_norm_eps", 1e-6),
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
@@ -2172,8 +2237,11 @@ class Qwen3VLForConditionalGeneration(
flattened_patch_size = (
in_channels * temporal_patch_size * patch_size * patch_size
)
dummy_pixel_values = torch.randn(
total_patches, flattened_patch_size, device=device, dtype=dtype
dummy_pixel_values = torch.zeros(
total_patches,
flattened_patch_size,
device=device,
dtype=self.visual.input_norm.input_dtype or dtype,
)
# Override max_seqlen with a safe upper bound for capture.
@@ -2307,7 +2375,7 @@ class Qwen3VLForConditionalGeneration(
if image_input["type"] == "image_embeds":
image_embeds = image_input["image_embeds"].type(self.visual.dtype)
else:
pixel_values = image_input["pixel_values"].type(self.visual.dtype)
pixel_values = image_input["pixel_values"]
if self.use_data_parallel:
return run_dp_sharded_mrope_vision_model(
self.visual, pixel_values, grid_thw.tolist(), rope_type="rope_3d"
@@ -2329,9 +2397,7 @@ class Qwen3VLForConditionalGeneration(
if video_input["type"] == "video_embeds":
video_embeds = video_input["video_embeds"].type(self.visual.dtype)
else:
pixel_values_videos = video_input["pixel_values_videos"].type(
self.visual.dtype
)
pixel_values_videos = video_input["pixel_values_videos"]
if self.use_data_parallel:
grid_thw_list = grid_thw.tolist()
return run_dp_sharded_mrope_vision_model(
@@ -36,6 +36,7 @@ from vllm.compilation.decorators import support_torch_compile
from vllm.config import VllmConfig
from vllm.distributed import get_pp_group
from vllm.logger import init_logger
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -254,6 +255,7 @@ class Qwen3VLMoeForConditionalGeneration(
config.vision_config,
norm_eps=getattr(config, "rms_norm_eps", 1e-6),
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
+7 -4
View File
@@ -5,7 +5,7 @@ import itertools
import math
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Final, Generic, Literal, Protocol, TypeAlias, TypeVar
from typing import Generic, Literal, Protocol, TypeAlias, TypeVar
import torch
from transformers import PreTrainedConfig
@@ -24,10 +24,12 @@ from vllm.v1.attention.backends.registry import AttentionBackendEnum
logger = init_logger(__name__)
_C = TypeVar("_C", bound=PreTrainedConfig)
_C_co = TypeVar("_C_co", bound=PreTrainedConfig, covariant=True)
class _RootConfig(Protocol[_C]):
vision_config: _C
class _RootConfig(Protocol[_C_co]):
@property
def vision_config(self) -> _C_co: ...
class VisionEncoderInfo(ABC, Generic[_C]):
@@ -60,7 +62,8 @@ class VisionEncoderInfo(ABC, Generic[_C]):
class VisionLanguageConfig(Protocol):
vision_config: Final[PreTrainedConfig]
@property
def vision_config(self) -> PreTrainedConfig: ...
def get_vision_encoder_info(hf_config: VisionLanguageConfig) -> VisionEncoderInfo:
+4 -3
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import math
from collections.abc import Iterable, Mapping, Sequence
from collections.abc import Callable, Iterable, Mapping, Sequence
from functools import partial
from typing import cast
@@ -317,7 +317,7 @@ class VoxtralForConditionalGeneration(
# update quant config to so that ignored module and target module names
# match the vLLM model names
if hasattr(vllm_config, "quant_config"):
if vllm_config.quant_config is not None:
vllm_config.quant_config = self.maybe_update_quant_config(
vllm_config.quant_config
)
@@ -724,6 +724,7 @@ class VoxtralEncoderModel(nn.Module):
self.config = cast(WhisperConfig, vllm_config.model_config.hf_config)
self.dtype: torch.dtype = vllm_config.model_config.dtype
self.is_causal = getattr(self.config, "is_causal", False)
WhisperEncoderCls: Callable[..., WhisperEncoder | WhisperCausalEncoder]
if self.is_causal:
WhisperEncoderCls = WhisperCausalEncoder
else:
@@ -830,7 +831,7 @@ class VoxtralEncoderModel(nn.Module):
return results
def load_weight(self, weight: tuple[str, torch.Tensor]) -> str:
stacked_params_mapping = [
stacked_params_mapping: list[tuple[str, str, str | int]] = [
# (param_name, shard_name, shard_id)
("qkv_proj", "q_proj", "q"),
("qkv_proj", "k_proj", "k"),
+12 -11
View File
@@ -16,7 +16,6 @@ from mistral_common.tokens.tokenizers.audio import Audio, AudioConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.engine.protocol import StreamingInput
from vllm.inputs import PromptType, TokensPrompt
from vllm.logger import init_logger
from vllm.model_executor.models.interfaces import MultiModalEmbeddings, SupportsRealtime
@@ -26,6 +25,7 @@ from vllm.model_executor.models.voxtral import (
VoxtralMultiModalProcessor,
VoxtralProcessingInfo,
)
from vllm.model_executor.models.whisper_causal import WhisperCausalEncoder
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.parse import MultiModalDataItems
from vllm.multimodal.processing import ProcessorInputs, TimingContext
@@ -56,7 +56,7 @@ class VoxtralRealtimeMultiModalProcessor(VoxtralMultiModalProcessor):
mm_items: MultiModalDataItems,
mm_res: MultiModalProcessingResult,
) -> tuple[list[int], Mapping[str, list[PlaceholderFeaturesInfo]]]:
mm_kwargs = mm_res.kwargs
mm_kwargs = mm_res.kwargs.require_data()
# there are no placeholder audio tokens for streaming
# so we need to build the place placeholder positions manually
@@ -69,7 +69,9 @@ class VoxtralRealtimeMultiModalProcessor(VoxtralMultiModalProcessor):
tokenizer = self.info.get_tokenizer()
audio_config = tokenizer.instruct.audio_encoder.audio_config
num_audio_samples = audios[0]["audio_arrays"].data.shape[0]
audio_array = audios[0]["audio_arrays"].data
assert isinstance(audio_array, (torch.Tensor, np.ndarray))
num_audio_samples = audio_array.shape[0]
length = audio_config.num_audio_tokens(num_audio_samples)
features_info = PlaceholderFeaturesInfo(
@@ -162,7 +164,7 @@ class VoxtralRealtimeBuffer:
for token in tokens:
await self._token_queue.put(token)
async def get_input_stream(self) -> AsyncGenerator[StreamingInput]:
async def get_input_stream(self) -> AsyncGenerator[TokensPrompt]:
for frame_size, num_tokens in self._generate_frame_size_and_num_tokens():
next_tokens = [await self._token_queue.get() for _ in range(num_tokens)]
@@ -188,11 +190,9 @@ class VoxtralRealtimeBuffer:
self._leftover = audio_array[stride:]
yield StreamingInput(
TokensPrompt(
prompt_token_ids=next_tokens,
multi_modal_data={"audio": (frame, None)},
)
yield TokensPrompt(
prompt_token_ids=next_tokens,
multi_modal_data={"audio": (frame, None)},
)
@@ -274,8 +274,8 @@ class VoxtralRealtimeGeneration(VoxtralForConditionalGeneration, SupportsRealtim
token_task = asyncio.create_task(feed_tokens())
try:
async for streaming_input in buffer.get_input_stream():
yield streaming_input.prompt
async for prompt in buffer.get_input_stream():
yield prompt
finally:
audio_task.cancel()
token_task.cancel()
@@ -420,6 +420,7 @@ class VoxtralRealtimeGeneration(VoxtralForConditionalGeneration, SupportsRealtim
seq_lens = [mel.shape[1] for mel in mel_features]
# [total_num_20ms_frames, hidden_size]
assert isinstance(self.whisper_encoder.whisper_encoder, WhisperCausalEncoder)
audio_embeddings = self.whisper_encoder.whisper_encoder.forward_conv(
mel_features
)
+37 -6
View File
@@ -240,13 +240,11 @@ class DeepSeekV4MultiTokenPredictor(nn.Module):
current_step_idx,
)
def compute_logits(
def _pre_head(
self,
mtp_layer: DeepSeekV4MultiTokenPredictorLayer,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
current_step_idx = spec_step_idx % self.num_mtp_layers
mtp_layer = self.layers[str(self.mtp_start_layer_idx + current_step_idx)]
# MTP forward returns the pre-hc_head residual (T, hc_mult * D); apply
# hc_head here so logits are computed from the dense hidden state.
hidden_states = hidden_states.view(
@@ -260,14 +258,38 @@ class DeepSeekV4MultiTokenPredictor(nn.Module):
mtp_layer.rms_norm_eps,
mtp_layer.hc_eps,
)
hidden_states = _MTP_SHARED_HEAD_RMSNORM_KERNEL(
return _MTP_SHARED_HEAD_RMSNORM_KERNEL(
hidden_states,
mtp_layer.shared_head.norm.weight.data,
mtp_layer.shared_head.norm.variance_epsilon,
)
logits = self.logits_processor(mtp_layer.shared_head.head, hidden_states)
def compute_logits(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
current_step_idx = spec_step_idx % self.num_mtp_layers
mtp_layer = self.layers[str(self.mtp_start_layer_idx + current_step_idx)]
logits = self.logits_processor(
mtp_layer.shared_head.head, self._pre_head(mtp_layer, hidden_states)
)
return logits
def get_top_tokens(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
current_step_idx = spec_step_idx % self.num_mtp_layers
mtp_layer = self.layers[str(self.mtp_start_layer_idx + current_step_idx)]
# Vocab-parallel argmax for the greedy draft: per-rank head projection
# + local argmax + a [batch, 2*tp] (value, index) reduce, instead of
# all-gathering the full vocab logits.
return self.logits_processor.get_top_tokens(
mtp_layer.shared_head.head, self._pre_head(mtp_layer, hidden_states)
)
class DeepSeekV4MTP(nn.Module):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
@@ -302,6 +324,15 @@ class DeepSeekV4MTP(nn.Module):
) -> torch.Tensor | None:
return self.model.compute_logits(hidden_states, spec_step_idx)
def get_top_tokens(
self,
hidden_states: torch.Tensor,
spec_step_idx: int = 0,
) -> torch.Tensor:
# Greedy-draft path used when use_local_argmax_reduction is enabled:
# vocab-parallel argmax, no full-vocab logits.
return self.model.get_top_tokens(hidden_states, spec_step_idx)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# Weight name remapping for checkpoint compatibility.
# Maps checkpoint weight paths to model parameter paths.
+178 -31
View File
@@ -35,6 +35,7 @@ from vllm.v1.attention.backends.mla.sparse_swa import (
DeepseekSparseSWAMetadataBuilder,
)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
build_prefill_topk_ragged_indices,
build_ragged_indices_from_dense,
rocm_inv_rope_einsum,
rocm_inverse_rope_rows_,
@@ -103,6 +104,22 @@ def _trust_dsv4_extra_cache_nan_free(
)
def _aiter_sparse_mla_enabled(has_kv_transfer: bool) -> bool:
from vllm._aiter_ops import rocm_aiter_ops
if not rocm_aiter_ops.is_triton_sparse_mla_enabled():
return False
# The aiter kernel does not scrub NaNs, so like the trust check above it
# needs a cache only the canonical writer has touched.
if has_kv_transfer:
logger.warning_once(
"VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA is ignored with a KV "
"connector; DeepSeek V4 keeps the Triton sparse attention."
)
return False
return True
def _build_indptr_from_lengths(lengths: torch.Tensor) -> torch.Tensor:
lengths = lengths.to(dtype=torch.int32).contiguous()
indptr = torch.zeros(lengths.shape[0] + 1, dtype=torch.int32, device=lengths.device)
@@ -446,6 +463,9 @@ class DeepseekV4ROCMAiterMLASparseMetadata(DeepseekV4FlashMLAMetadata):
class DeepseekV4ROCMAiterSparseSWAMetadata(DeepseekSparseSWAMetadata):
decode_swa_ragged_indices: torch.Tensor | None = None
decode_swa_ragged_indptr: torch.Tensor | None = None
# Built only for the aiter prefill, which reads the SWA cache in place.
prefill_swa_ragged_indices: torch.Tensor | None = None
prefill_swa_ragged_indptr: torch.Tensor | None = None
class DeepseekV4ROCMAiterMLASparseMetadataBuilder(DeepseekV4SparseMLAMetadataBuilder):
@@ -565,6 +585,9 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuild
dtype=torch.int32,
device=self.device,
)
self._use_aiter_sparse_mla = _aiter_sparse_mla_enabled(
self.vllm_config.kv_transfer_config is not None
)
def build(
self,
@@ -580,6 +603,23 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuild
replay_start=replay_start,
)
prefill_ragged_indices = None
prefill_ragged_indptr = None
if (
self._use_aiter_sparse_mla
and base.num_prefill_tokens > 0
and base.prefill_swa_indices is not None
and base.prefill_swa_lens is not None
):
# Paged-coordinate rows (image visibility included), so every
# layer's prefill shares one build.
prefill_ragged_indices, prefill_ragged_indptr = (
build_ragged_indices_from_dense(
base.prefill_swa_indices.reshape(base.num_prefill_tokens, -1),
base.prefill_swa_lens,
)
)
ragged_indices = None
ragged_indptr = None
if (
@@ -606,6 +646,8 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekSparseSWAMetadataBuild
**vars(base),
decode_swa_ragged_indices=ragged_indices,
decode_swa_ragged_indptr=ragged_indptr,
prefill_swa_ragged_indices=prefill_ragged_indices,
prefill_swa_ragged_indptr=prefill_ragged_indptr,
)
@@ -623,6 +665,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
"""ROCm sparse MLA attention layer for DeepSeek V4."""
backend_cls = DeepseekV4ROCMAiterMLASparseBackend
_use_aiter_sparse_mla = False
def __init__(self, *args, **kwargs):
vllm_config = args[0] if args else kwargs["vllm_config"]
@@ -648,23 +691,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
else:
# Disable indexer inner overlap.
self.indexer.aux_stream = None
def _enable_multi_stream_overlap(self) -> bool:
"""ROCm multi-stream gates: streams and capture region.
Dict metadata marks piecewise cudagraph, whose eager breaks rebuild
the attention inputs on the owning stream. Forking side streams
there would rely on runtime HIP event sync, which is unreliable in
this overlap on ROCm (event waits can hang), so multi-stream only
runs where the fork/join becomes static graph edges: inside capture,
or with non-dict metadata (full cudagraph or the profile run), which
has no eager breaks. Covers both the HCA and CSA forks.
"""
attn_metadata = get_forward_context().attn_metadata
return self.aux_stream_list is not None and (
torch.cuda.is_current_stream_capturing()
or not isinstance(attn_metadata, dict)
)
self._use_aiter_sparse_mla = _aiter_sparse_mla_enabled(self._has_kv_transfer)
def _run_sequential_pipeline(
self,
@@ -709,7 +736,9 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
device=hidden_states.device,
)
if self._enable_multi_stream_overlap():
if current_platform.enable_multi_stream_overlap(
self.aux_stream_list, get_forward_context().attn_metadata
):
# The ROCm override consumes these sentinels inside the capture
# boundary, moving the stream fan-out ahead of the projections.
self._prepare_and_attn_fn(
@@ -769,7 +798,9 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
# Re-check: forward's gate ran inside a captured segment that
# _prepare_and_attn_eager (MRV1) then broke, making this region eager.
if not self._enable_multi_stream_overlap():
if not current_platform.enable_multi_stream_overlap(
self.aux_stream_list, get_forward_context().attn_metadata
):
self._run_sequential_pipeline(hidden_states, positions, o_padded)
return
@@ -1203,18 +1234,20 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
if attn_metadata is None:
# Warmup dummy run: no real metadata. Reserve the same bf16
# gather workspace _forward_prefill would; the dequantize / topk
# / sparse_fwd kernels are skipped this step.
swa_only = self.compress_ratio <= 1
N = (
0
if swa_only
else (self.max_model_len + self.compress_ratio - 1)
// self.compress_ratio
)
M = N + self.window_size + self.max_num_batched_tokens
current_workspace_manager().get_simultaneous(
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
)
# / sparse_fwd kernels are skipped this step. The aiter prefill
# reads the caches in place and never asks for it.
if not self._use_aiter_sparse_mla:
swa_only = self.compress_ratio <= 1
N = (
0
if swa_only
else (self.max_model_len + self.compress_ratio - 1)
// self.compress_ratio
)
M = N + self.window_size + self.max_num_batched_tokens
current_workspace_manager().get_simultaneous(
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
)
output.zero_()
return
@@ -1325,6 +1358,22 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
topk_ragged_indices = attn_metadata.c128a_decode_topk_ragged_indices
topk_ragged_indptr = attn_metadata.c128a_decode_topk_ragged_indptr
if self._use_aiter_sparse_mla:
assert swa_metadata.decode_swa_ragged_indices is not None
assert swa_metadata.decode_swa_ragged_indptr is not None
self._aiter_sparse_mla(
q,
output,
self.swa_cache_layer.kv_cache,
swa_metadata.decode_swa_ragged_indices,
swa_metadata.decode_swa_ragged_indptr,
kv_cache,
topk_ragged_indices,
topk_ragged_indptr,
)
# The aiter kernel leaves the inverse RoPE to the caller.
return 0
return rocm_sparse_attn_decode(
q=q,
kv_cache=kv_cache,
@@ -1364,6 +1413,17 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
attn_metadata: DeepseekV4ROCMAiterMLASparseMetadata | None,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
) -> None:
if self._use_aiter_sparse_mla:
self._forward_prefill_aiter(
q=q,
compressed_k_cache=compressed_k_cache,
swa_k_cache=swa_k_cache,
output=output,
attn_metadata=attn_metadata,
swa_metadata=swa_metadata,
)
return
swa_only = attn_metadata is None
num_prefills = swa_metadata.num_prefills
@@ -1489,3 +1549,90 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
attn_sink=self.attn_sink,
output=output[query_start:query_end],
)
def _forward_prefill_aiter(
self,
q: torch.Tensor,
compressed_k_cache: torch.Tensor | None,
swa_k_cache: torch.Tensor,
output: torch.Tensor,
attn_metadata: DeepseekV4ROCMAiterMLASparseMetadata | None,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
) -> None:
"""Prefill straight off the paged caches, with no bf16 gather."""
num_decode_tokens = swa_metadata.num_decode_tokens
num_prefill_tokens = swa_metadata.num_prefill_tokens
assert swa_metadata.prefill_swa_ragged_indices is not None
assert swa_metadata.prefill_swa_ragged_indptr is not None
topk_ragged_indices = None
topk_ragged_indptr = None
if attn_metadata is None:
compressed_k_cache = None
else:
assert compressed_k_cache is not None
assert swa_metadata.token_to_req_indices is not None
assert swa_metadata.query_start_loc is not None
assert swa_metadata.seq_lens is not None
assert swa_metadata.is_valid_token is not None
if self.compress_ratio == 4:
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[
num_decode_tokens : num_decode_tokens + num_prefill_tokens
]
else:
topk_indices = attn_metadata.c128a_prefill_topk_indices
assert topk_indices is not None
topk_ragged_indices, topk_ragged_indptr = build_prefill_topk_ragged_indices(
topk_indices,
swa_metadata.token_to_req_indices,
swa_metadata.query_start_loc,
swa_metadata.seq_lens,
swa_metadata.is_valid_token,
attn_metadata.block_table,
block_size=attn_metadata.block_size // self.compress_ratio,
compress_ratio=self.compress_ratio,
num_compressed=(self.max_model_len + self.compress_ratio - 1)
// self.compress_ratio,
token_offset=num_decode_tokens,
num_rows=compressed_k_cache.shape[0] * compressed_k_cache.shape[1],
)
self._aiter_sparse_mla(
q[:num_prefill_tokens],
output[:num_prefill_tokens],
swa_k_cache,
swa_metadata.prefill_swa_ragged_indices,
swa_metadata.prefill_swa_ragged_indptr,
compressed_k_cache,
topk_ragged_indices,
topk_ragged_indptr,
)
def _aiter_sparse_mla(
self,
q: torch.Tensor,
output: torch.Tensor,
swa_k_cache: torch.Tensor,
swa_indices: torch.Tensor,
swa_indptr: torch.Tensor,
compressed_k_cache: torch.Tensor | None,
topk_indices: torch.Tensor | None,
topk_indptr: torch.Tensor | None,
) -> None:
from vllm._aiter_ops import rocm_aiter_ops
# Both fp8 caches are read in place: the SWA window as the main segment,
# the top-k compressed tokens as the extra one.
rocm_aiter_ops.triton_sparse_mla_fwd(
q,
swa_k_cache,
output,
self.scale,
swa_indptr,
swa_indices,
attn_sink=self.attn_sink[: q.shape[1]],
extra_kv_buffer=compressed_k_cache,
extra_kv_indptr=topk_indptr,
extra_kv_indices=topk_indices,
)
+29 -4
View File
@@ -22,7 +22,11 @@ from vllm.model_executor.layers.fused_moe import (
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.mhc import MHCPostOp, MHCPreDelayedOp
from vllm.model_executor.layers.mhc import (
HAS_AITER_MHC_FUSED_POST_PRE_DELAYED_RMS_NORM,
MHCPostOp,
MHCPreDelayedOp,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.vocab_parallel_embedding import (
ParallelLMHead,
@@ -251,6 +255,10 @@ class DeepseekV4DecoderLayer(nn.Module):
)
self.mhc_pre_delayed = MHCPreDelayedOp()
self.mhc_post = MHCPostOp()
# Where aiter's fused seam kernel runs (gfx950), it folds the following
# attn_norm / ffn_norm into its collapse, so the separate norms are
# skipped for the seams it takes.
self.fuse_seam_norm = HAS_AITER_MHC_FUSED_POST_PRE_DELAYED_RMS_NORM
@staticmethod
def _hc_collapse(x: torch.Tensor, pre_mix: torch.Tensor) -> torch.Tensor:
@@ -269,6 +277,11 @@ class DeepseekV4DecoderLayer(nn.Module):
engram_hashes: torch.Tensor | None = None,
engram_mask: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
# Layer 0's attention seam projects the 2-D embedding with the folded
# hc_attn_fn_broadcast instead of the 4-stream residual with hc_attn_fn.
# The fused kernel only takes the latter, so that seam keeps the
# separate attn_norm.
fuse_attn_norm = self.fuse_seam_norm and not (residual is None and x.dim() == 2)
# The reference collapses each sublayer's input with the *previous*
# sublayer's pre-mix: attention uses the pre-mix carried in (identity
# for the first layer), the FFN uses this layer's attention pre-mix.
@@ -303,6 +316,8 @@ class DeepseekV4DecoderLayer(nn.Module):
self.hc_post_alpha,
self.hc_sinkhorn_iters,
pre_mix=pre_mix,
norm_weight=self.attn_norm.weight if self.fuse_seam_norm else None,
norm_eps=self.attn_norm.variance_epsilon,
)
else:
pre_args = (
@@ -328,7 +343,11 @@ class DeepseekV4DecoderLayer(nn.Module):
engram_mask,
)
residual, post_mix, res_mix, x, attn_pre = self.mhc_pre_delayed(
residual, *pre_args, pre_mix=pre_mix
residual,
*pre_args,
pre_mix=pre_mix,
norm_weight=self.attn_norm.weight if self.fuse_seam_norm else None,
norm_eps=self.attn_norm.variance_epsilon,
)
else:
(
@@ -344,8 +363,11 @@ class DeepseekV4DecoderLayer(nn.Module):
sublayer_out=x,
post_layer_mix=post_mix,
comb_res_mix=res_mix,
norm_weight=self.attn_norm.weight if self.fuse_seam_norm else None,
norm_eps=self.attn_norm.variance_epsilon,
)
x = self.attn_norm(x)
if not fuse_attn_norm:
x = self.attn_norm(x)
if self.use_sequence_parallel:
x = sp_all_gather(x)[: positions.shape[0]]
@@ -368,8 +390,11 @@ class DeepseekV4DecoderLayer(nn.Module):
sublayer_out=x,
post_layer_mix=post_mix,
comb_res_mix=res_mix,
norm_weight=self.ffn_norm.weight if self.fuse_seam_norm else None,
norm_eps=self.ffn_norm.variance_epsilon,
)
x = self.ffn_norm(x)
if not self.fuse_seam_norm:
x = self.ffn_norm(x)
x = self.ffn(x, input_ids)
return x, residual, post_mix, res_mix, ffn_pre
+244 -27
View File
@@ -38,6 +38,7 @@ from vllm.v1.attention.backends.mla.sparse_swa import (
DeepseekSparseSWAMetadata,
)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
build_prefill_topk_ragged_indices,
build_ragged_indices_from_dense,
rocm_inv_rope_einsum,
rocm_inverse_rope_mxfp8_rows,
@@ -64,6 +65,22 @@ def _trust_dsv4_extra_cache_nan_free(
)
def _aiter_sparse_mla_enabled(has_kv_transfer: bool) -> bool:
from vllm._aiter_ops import rocm_aiter_ops
if not rocm_aiter_ops.is_triton_sparse_mla_enabled():
return False
# The aiter kernel does not scrub NaNs, so like the trust check above it
# needs a cache only the canonical writer has touched.
if has_kv_transfer:
logger.warning_once(
"VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA is ignored with a KV "
"connector; DeepSeek V4 keeps the Triton sparse attention."
)
return False
return True
def _build_indptr_from_lengths(lengths: torch.Tensor) -> torch.Tensor:
lengths = lengths.to(dtype=torch.int32).contiguous()
indptr = torch.zeros(lengths.shape[0] + 1, dtype=torch.int32, device=lengths.device)
@@ -408,6 +425,9 @@ _TopkRagged = tuple[torch.Tensor, torch.Tensor, torch.Tensor]
class DeepseekV4ROCMAiterSparseSWAMetadata(DeepseekSparseSWAMetadata):
decode_swa_ragged_indices: torch.Tensor | None = None
decode_swa_ragged_indptr: torch.Tensor | None = None
# Built only for the aiter prefill, which reads the SWA cache in place.
prefill_swa_ragged_indices: torch.Tensor | None = None
prefill_swa_ragged_indptr: torch.Tensor | None = None
class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBuilder):
@@ -432,6 +452,9 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBu
dtype=torch.int32,
device=self.device,
)
self._use_aiter_sparse_mla = _aiter_sparse_mla_enabled(
self.vllm_config.kv_transfer_config is not None
)
def build(
self,
@@ -447,6 +470,22 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBu
replay_start=replay_start,
)
prefill_ragged_indices = None
prefill_ragged_indptr = None
if (
self._use_aiter_sparse_mla
and base.num_prefill_tokens > 0
and base.prefill_swa_indices is not None
and base.prefill_swa_lens is not None
):
# Paged-coordinate rows, so every layer's prefill shares one build.
prefill_ragged_indices, prefill_ragged_indptr = (
build_ragged_indices_from_dense(
base.prefill_swa_indices.reshape(base.num_prefill_tokens, -1),
base.prefill_swa_lens,
)
)
ragged_indices = None
ragged_indptr = None
if (
@@ -473,6 +512,8 @@ class DeepseekV4ROCMAiterSparseSWAMetadataBuilder(DeepseekV41SparseSWAMetadataBu
**vars(base),
decode_swa_ragged_indices=ragged_indices,
decode_swa_ragged_indptr=ragged_indptr,
prefill_swa_ragged_indices=prefill_ragged_indices,
prefill_swa_ragged_indptr=prefill_ragged_indptr,
)
@@ -497,6 +538,7 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
backend_cls = DeepseekV4ROCMAiterMLASparseBackend
swa_backend_cls = DeepseekV41ROCMAiterSparseSWABackend
_use_aiter_sparse_mla = False
def __init__(self, *args, **kwargs):
vllm_config = args[0] if args else kwargs["vllm_config"]
@@ -518,6 +560,9 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
# same thing. The source owns one cache per compress ratio, refreshed
# when it runs; consumers below it read through.
self._topk_ragged_cache: dict[int, _TopkRagged] = {}
self._prefill_topk_ragged_cache: dict[
str, tuple[torch.Tensor, torch.Tensor]
] = {}
self._index_source_prefix: str | None = None
if self.compress_ratio > 0:
assert self.index_source_layer_id is not None
@@ -530,6 +575,7 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
"this rank; PP splits inside a v4.1 index-sharing group "
"are not supported."
)
self._use_aiter_sparse_mla = _aiter_sparse_mla_enabled(self._has_kv_transfer)
if self.compressor is None and self.indexer is None:
# Dense layers have nothing to overlap; keep the base serial path.
self.aux_stream_list = None
@@ -615,23 +661,6 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
self.aux_stream_list = aux_streams
return super()._run_parallel_input_projections(hidden_states)
def _enable_multi_stream_overlap(self) -> bool:
"""ROCm multi-stream gates: streams and capture region.
Dict metadata marks piecewise cudagraph, whose eager breaks rebuild
the attention inputs on the owning stream. Forking side streams
there would rely on runtime HIP event sync, which is unreliable in
this overlap on ROCm (event waits can hang), so multi-stream only
runs where the fork/join becomes static graph edges: inside capture,
or with non-dict metadata (full cudagraph or the profile run), which
has no eager breaks.
"""
attn_metadata = get_forward_context().attn_metadata
return self.aux_stream_list is not None and (
torch.cuda.is_current_stream_capturing()
or not isinstance(attn_metadata, dict)
)
def forward(
self,
positions: torch.Tensor,
@@ -641,7 +670,9 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
if (
self.indexer is None
or self._prepare_and_attn_fn == self._prepare_and_attn_eager
or not self._enable_multi_stream_overlap()
or not current_platform.enable_multi_stream_overlap(
self.aux_stream_list, get_forward_context().attn_metadata
)
):
# Sequential fallback: no forks outside the capture region, where
# HIP event sync is unreliable; MRV1 keeps the input prep in its
@@ -930,9 +961,10 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
attn_metadata = forward_context.attn_metadata
if attn_metadata is None:
# Warmup dummy run: no real metadata. Reserve the same bf16
# gather workspace _forward_prefill would; the dequantize / topk
# / sparse_fwd kernels are skipped this step.
# Warmup dummy run: no real metadata. Reserve the workspace
# _forward_prefill would; the dequantize / topk / sparse_fwd kernels
# are skipped this step. The aiter prefill reads the caches in place,
# so it asks only for the bf16 rows of the MXFP8 output.
swa_only = self.compress_ratio == 0
N = (
0
@@ -941,9 +973,14 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
// self.compress_ratio
)
M = N + self.window_size + self.max_num_batched_tokens
current_workspace_manager().get_simultaneous(
*self._prefill_workspace_shapes(M, self.max_num_batched_tokens, q)
shapes = self._prefill_workspace_shapes(
M,
self.max_num_batched_tokens,
q,
gather=not self._use_aiter_sparse_mla,
)
if shapes:
current_workspace_manager().get_simultaneous(*shapes)
if mxfp8_out is None:
output.zero_()
else:
@@ -1102,6 +1139,38 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
num_decode_tokens=num_decode_tokens,
)
if self._use_aiter_sparse_mla:
assert swa_metadata.decode_swa_ragged_indices is not None
assert swa_metadata.decode_swa_ragged_indptr is not None
out = output
if output_mxfp8 is not None:
# The aiter kernel has no MXFP8 epilogue: write bf16 rows, then
# rotate and quantize them as the decode reduce would have.
out = self._mxfp8_bf16_rows(q.shape[0], q)
assert out is not None
self._aiter_sparse_mla(
q,
out,
self.swa_cache_layer.kv_cache,
swa_metadata.decode_swa_ragged_indices,
swa_metadata.decode_swa_ragged_indptr,
kv_cache,
topk_ragged_indices,
topk_ragged_indptr,
)
if output_mxfp8 is not None:
rocm_inverse_rope_mxfp8_rows(
out,
positions,
self.rotary_emb.cos_sin_cache,
self.rope_head_dim,
output_mxfp8[0],
output_mxfp8[1],
)
return q.shape[0]
# The aiter kernel leaves the inverse RoPE to the caller.
return 0
return rocm_sparse_attn_decode(
q=q,
kv_cache=kv_cache,
@@ -1147,6 +1216,19 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
With ``mxfp8_out`` the rows go to a bf16 workspace first and are then
inverse-RoPE'd and quantized into it in one pass.
"""
if self._use_aiter_sparse_mla:
self._forward_prefill_aiter(
q=q,
positions=positions,
compressed_k_cache=compressed_k_cache,
swa_k_cache=swa_k_cache,
output=output,
attn_metadata=attn_metadata,
swa_metadata=swa_metadata,
mxfp8_out=mxfp8_out,
)
return
swa_only = attn_metadata is None
num_prefills = swa_metadata.num_prefills
@@ -1264,15 +1346,17 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
)
def _prefill_workspace_shapes(
self, M: int, num_prefill_tokens: int, q: torch.Tensor
self, M: int, num_prefill_tokens: int, q: torch.Tensor, gather: bool = True
) -> list[tuple[tuple[int, ...], torch.dtype]]:
"""The prefill gather buffer, plus bf16 rows for the MXFP8 output.
One ``get_simultaneous`` call: separate calls alias the same memory.
``gather=False`` leaves out the gather buffer, which the aiter kernel,
reading the caches in place, never needs.
"""
shapes: list[tuple[tuple[int, ...], torch.dtype]] = [
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16)
]
shapes: list[tuple[tuple[int, ...], torch.dtype]] = []
if gather:
shapes.append(((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16))
if _ON_GFX950:
shapes.append(
(
@@ -1281,3 +1365,136 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
)
)
return shapes
def _prefill_topk_ragged(
self,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
attn_metadata: DeepseekV4FlashMLAMetadata,
compressed_k_cache: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Prefill counterpart of ``_decode_topk_ragged``: layers that share an
index source and a compressed cache reuse one build per step."""
assert swa_metadata.token_to_req_indices is not None
assert swa_metadata.query_start_loc is not None
assert swa_metadata.seq_lens is not None
assert swa_metadata.is_valid_token is not None
assert self.topk_indices_buffer is not None
assert self._index_source_prefix is not None
assert self.compressed_cache_prefix is not None
source = self._static_forward_context[self._index_source_prefix]
if source is self:
source._prefill_topk_ragged_cache = {}
cached = source._prefill_topk_ragged_cache.get(self.compressed_cache_prefix)
if cached is not None:
return cached
num_decode_tokens = swa_metadata.num_decode_tokens
num_prefill_tokens = swa_metadata.num_prefill_tokens
built = build_prefill_topk_ragged_indices(
self.topk_indices_buffer[
num_decode_tokens : num_decode_tokens + num_prefill_tokens
],
swa_metadata.token_to_req_indices,
swa_metadata.query_start_loc,
swa_metadata.seq_lens,
swa_metadata.is_valid_token,
attn_metadata.block_table,
block_size=attn_metadata.block_size // self.compress_ratio,
compress_ratio=self.compress_ratio,
num_compressed=(self.max_model_len + self.compress_ratio - 1)
// self.compress_ratio,
token_offset=num_decode_tokens,
num_rows=compressed_k_cache.shape[0] * compressed_k_cache.shape[1],
)
source._prefill_topk_ragged_cache[self.compressed_cache_prefix] = built
return built
def _forward_prefill_aiter(
self,
q: torch.Tensor,
positions: torch.Tensor,
compressed_k_cache: torch.Tensor | None,
swa_k_cache: torch.Tensor,
output: torch.Tensor | None,
attn_metadata: DeepseekV4FlashMLAMetadata | None,
swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata,
mxfp8_out: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> None:
"""Prefill straight off the paged caches, with no bf16 gather.
With ``mxfp8_out`` the kernel writes bf16 rows to the workspace, which
are then inverse-RoPE'd and quantized into it as ``_forward_prefill``
does.
"""
num_prefill_tokens = swa_metadata.num_prefill_tokens
assert swa_metadata.prefill_swa_ragged_indices is not None
assert swa_metadata.prefill_swa_ragged_indptr is not None
topk_indices = None
topk_indptr = None
if attn_metadata is None:
compressed_k_cache = None
else:
assert compressed_k_cache is not None
topk_indices, topk_indptr = self._prefill_topk_ragged(
swa_metadata, attn_metadata, compressed_k_cache
)
if mxfp8_out is not None:
output = self._mxfp8_bf16_rows(num_prefill_tokens, q)
assert output is not None
self._aiter_sparse_mla(
q[:num_prefill_tokens],
output[:num_prefill_tokens],
swa_k_cache,
swa_metadata.prefill_swa_ragged_indices,
swa_metadata.prefill_swa_ragged_indptr,
compressed_k_cache,
topk_indices,
topk_indptr,
)
if mxfp8_out is not None:
rocm_inverse_rope_mxfp8_rows(
output[:num_prefill_tokens],
positions[:num_prefill_tokens],
self.rotary_emb.cos_sin_cache,
self.rope_head_dim,
mxfp8_out[0][:num_prefill_tokens],
mxfp8_out[1][:num_prefill_tokens],
)
def _mxfp8_bf16_rows(self, num_tokens: int, q: torch.Tensor) -> torch.Tensor:
"""bf16 attention rows for the aiter kernel to write when the layer's
output is MXFP8, taken from the workspace the warmup reserved."""
shapes = self._prefill_workspace_shapes(0, num_tokens, q, gather=False)
assert shapes, "an MXFP8 attention output is gfx950-only"
return current_workspace_manager().get_simultaneous(*shapes)[0]
def _aiter_sparse_mla(
self,
q: torch.Tensor,
output: torch.Tensor,
swa_k_cache: torch.Tensor,
swa_indices: torch.Tensor,
swa_indptr: torch.Tensor,
compressed_k_cache: torch.Tensor | None,
topk_indices: torch.Tensor | None,
topk_indptr: torch.Tensor | None,
) -> None:
from vllm._aiter_ops import rocm_aiter_ops
# Both fp8 caches are read in place: the SWA window as the main segment,
# the top-k compressed tokens as the extra one.
rocm_aiter_ops.triton_sparse_mla_fwd(
q,
swa_k_cache,
output,
self.scale,
swa_indptr,
swa_indices,
attn_sink=self.attn_sink[: q.shape[1]],
extra_kv_buffer=compressed_k_cache,
extra_kv_indptr=topk_indptr,
extra_kv_indices=topk_indices,
)
+2 -1
View File
@@ -6,6 +6,7 @@ import torch
from vllm.distributed import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
tensor_model_parallel_all_reduce,
)
from vllm.logger import init_logger
@@ -33,7 +34,7 @@ class ROCmLatentMoERunner(MoERunner):
transform = self.routed_output_transform
up_proj = getattr(transform, "up_proj", None)
tp_size = self.moe_config.tp_size
tp_size = get_tensor_model_parallel_world_size()
self._up_proj_shard_size = 0
self._tail_shardable = (
+6 -1
View File
@@ -376,7 +376,12 @@ class K3DSparkModel(nn.Module):
self,
cache_layers: list[MultiHeadLatentAttention],
) -> bool:
if not hasattr(self, "_layers_share_kv_block_layout"):
key = tuple(cl.kv_cache.data_ptr() for cl in cache_layers)
if getattr(self, "_kv_cache_ptrs_key", None) != key:
assert not torch.cuda.is_current_stream_capturing()
self._kv_cache_ptrs_key = key
if hasattr(self, "_context_cache_ptrs"):
del self._context_cache_ptrs
ref_cache = cache_layers[0].kv_cache
self._layers_share_kv_block_layout = all(
cl.kv_cache.size(1) == ref_cache.size(1)
+10 -5
View File
@@ -502,16 +502,21 @@ def select_indexer_impl_cls(
On Blackwell (SM100) with ``topk_blocks == 16`` (the only width fmha_sm100's
``sparse_topk_select`` kernel supports), the fmha_sm100 score + top-k path is
used for both bf16 and fp8 index caches. Everything else falls back to the
Triton indexer (bf16 only).
Triton indexer, with fp8 restricted to CUDA platforms that advertise fp8
support.
"""
if indexer_kv_dtype in ("mxfp4", "nvfp4"):
raise NotImplementedError(
f"indexer_kv_dtype={indexer_kv_dtype!r} needs the (not-yet-added) "
"CuteDSL indexer impl."
)
is_sm100 = (
current_platform.is_cuda() and current_platform.is_device_capability_family(100)
)
is_cuda = current_platform.is_cuda()
is_fp8 = indexer_kv_dtype in ("fp8", "fp8_e4m3")
if is_fp8 and not (is_cuda and current_platform.supports_fp8()):
raise NotImplementedError(
f"indexer_kv_dtype={indexer_kv_dtype!r} requires CUDA fp8 support."
)
is_sm100 = is_cuda and current_platform.is_device_capability_family(100)
use_msa = (
is_sm100
and topk_blocks == 16
@@ -530,7 +535,7 @@ def select_indexer_impl_cls(
indexer_kv_dtype,
)
return MiniMaxM3IndexerMSAImpl
if indexer_kv_dtype != "bf16":
if indexer_kv_dtype not in ("bf16", "fp8", "fp8_e4m3"):
raise NotImplementedError(
f"indexer_kv_dtype={indexer_kv_dtype!r} is not supported by the "
"Triton indexer impl."
@@ -123,6 +123,10 @@ def _index_block_score_kernel(
order=(1, 0),
)
q = tl.load(q_ptrs, boundary_check=(0,), padding_option="zero")
# FP8 has no mixed-dtype dot with bf16/fp32. Leave bf16 and fp32 loads
# in their stored dtype so fp32 pipeline tests keep full precision.
if q.dtype.is_fp8():
q = q.to(tl.bfloat16)
q_start = prefix_len + pid_q * BLOCK_SIZE_Q
off_q = tl.arange(0, BLOCK_SIZE_Q) + pid_q * BLOCK_SIZE_Q + prefix_len
@@ -146,7 +150,9 @@ def _index_block_score_kernel(
+ off_k[None, :] * stride_ik_pos
+ off_d[:, None] * stride_ik_d,
)
qk = tl.dot(q, k)
if k.dtype.is_fp8():
k = k.to(tl.bfloat16)
qk = tl.dot(q, k, out_dtype=tl.float32)
# apply causal mask as needed
if q_start < i + BLOCK_SIZE_K:
qk = tl.where(off_q[:, None] >= pos[None, :], qk, float("-inf"))
@@ -360,6 +366,8 @@ def _decode_index_score_kernel(
mask=q_mask[None, :],
other=0.0,
) # [D,HQ]
if q.dtype.is_fp8():
q = q.to(tl.bfloat16)
for blk in tl.range(chunk_start_block, chunk_end_block):
page = tl.load(bt_row + blk).to(tl.int64)
pos = blk * BLOCK_SIZE_K + off_k
@@ -373,9 +381,11 @@ def _decode_index_score_kernel(
+ off_k[:, None] * stride_ik_pos
+ off_d * stride_ik_d,
) # [N,D]
# fp32 accumulation is required for the fp8 (e4m3) index cache: q/k are
# loaded in their stored dtype (bf16 or e4m3) and the MMA accumulates in
# fp32 so the per-block max score is exact for the fp8 indexer too.
# Upcast only FP8 cache loads. BF16 operands keep FP8 dot
# instructions out of the fallback path; FP32 accumulation
# preserves score accuracy. BF16/FP32 loads stay as stored.
if k.dtype.is_fp8():
k = k.to(tl.bfloat16)
kq = tl.dot(k, q, out_dtype=tl.float32) # [N,HQ]
kq = tl.where(pos_mask & q_mask[None, :], kq, float("-inf"))
score = tl.max(kq, axis=0) # [HQ]
+2
View File
@@ -14,6 +14,7 @@ from vllm.distributed import get_pp_group
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
QwenGatedDeltaNetAttention,
@@ -897,6 +898,7 @@ class Qwen4ExpForConditionalGeneration(
config.vision_config,
norm_eps=config.text_config.rms_norm_eps,
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
+2 -7
View File
@@ -672,14 +672,9 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
num_decode_tokens: int,
num_prefill_tokens: int,
) -> torch.Tensor:
# ``non_spec_query_start_loc`` covers the non-spec (decode + prefill)
# requests and equals ``query_start_loc`` when spec-decode is inactive.
non_spec_query_start_loc = metadata.non_spec_query_start_loc
if non_spec_query_start_loc is None:
query_start_loc_p = metadata.query_start_loc_p
if query_start_loc_p is None:
raise ValueError("query_start_loc is required for prefill short-conv")
query_start_loc_p = (
non_spec_query_start_loc[-num_prefills - 1 :] - num_decode_tokens
)
# The metadata builder guarantees that the prefill query offsets start
# at 0 and end at num_prefill_tokens. Avoid reading those values here,
# since doing so would force a device-to-host synchronization.
+12 -9
View File
@@ -825,15 +825,18 @@ class QSAKeyStateCache(_QSAStateCache):
)
super().__init__(head_size=storage_head_size, **kwargs)
def bind_kv_cache(self, kv_cache: torch.Tensor) -> None:
super().bind_kv_cache(kv_cache)
qsa_cache = self.kv_cache
self.key_cache = qsa_cache[..., : self.key_head_size]
if self.cache_rope_positions:
position_tail = qsa_cache[..., self.rope_position_offset :]
self.rope_position_cache = position_tail.view(torch.int64)
else:
self.rope_position_cache = None
# Derived on access so `kv_cache` stays the only reference to the bound
# storage: clearing it (e.g. after CUDA graph memory profiling) must free
# the cache, or the freed block stays pinned in the allocator.
@property
def key_cache(self) -> torch.Tensor:
return self.kv_cache[..., : self.key_head_size]
@property
def rope_position_cache(self) -> torch.Tensor | None:
if not self.cache_rope_positions:
return None
return self.kv_cache[..., self.rope_position_offset :].view(torch.int64)
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
# Hold the open group's committed keys plus every row a speculative
+38 -23
View File
@@ -25,16 +25,19 @@ Typical usage inside a transformer decoder layer::
import torch
from torch import nn
import vllm.envs as envs
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
ReplicatedLinear,
)
from vllm.model_executor.models.utils import maybe_prefix
from vllm.platforms import current_platform
from ..common.hyperconnection import (
GroupedGemmaRMSNorm,
HyperConnectionConfig,
)
from .ops.cute_dsl.hc_down_silu import MAX_FUSED_M, hc_down_silu
from .ops.hc import (
grouped_gemma_rmsnorm,
hc_combine,
@@ -58,9 +61,9 @@ class GatedResidual(nn.Module):
injection.
Weights: the norm owns the grouped GemmaRMSNorm affine; the projections
are vLLM Linear modules (merged replicated linear for down+inject), so
GEMM dispatch (e.g. the low-latency skinny GEMM) applies through the
standard quant_method mechanism.
are vLLM Linear modules (merged replicated linear for down+inject).
Eligible down+inject projections use the fused SiLU GEMM; other projections
use their Linear module's GEMM dispatch.
"""
def __init__(
@@ -105,6 +108,12 @@ class GatedResidual(nn.Module):
return_bias=False,
disable_tp=True,
)
weight = self.input_mix_weight_down_block_inject.weight
self._use_hc_down_silu = (
weight.shape[1] % 8 == 0
and weight.dtype == torch.bfloat16
and current_platform.has_device_capability(90)
)
else:
self.input_mix_weight_down = ReplicatedLinear(
self.hyper_hidden_size,
@@ -125,6 +134,30 @@ class GatedResidual(nn.Module):
return_bias=False,
)
def _down_and_inject(
self, xn: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Down projection + SiLU; also returns injection logits if combined."""
if not self.use_combine:
return hc_silu(self.input_mix_weight_down(xn), self.hc_count), None
use_fused = (
self._use_hc_down_silu
and not envs.VLLM_BATCH_INVARIANT
and 1 <= xn.shape[0] <= MAX_FUSED_M
)
if use_fused:
return hc_down_silu(
xn,
self.input_mix_weight_down_block_inject.weight,
self.lora_rank,
self.hc_count,
)
down_and_injection = self.input_mix_weight_down_block_inject(xn)
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
return hc_silu(lora, self.hc_count), injection
def mix(
self, hidden_states: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
@@ -135,16 +168,7 @@ class GatedResidual(nn.Module):
self.hc_count,
)
if self.use_combine:
# produce injection logits for combine
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
down_and_injection = self.input_mix_weight_down_block_inject(xn)
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
else:
lora = self.input_mix_weight_down(xn)
injection = None
lora = hc_silu(lora, self.hc_count)
lora, injection = self._down_and_inject(xn)
gate = self.input_mix_weight_up(lora) # [M, D]
block_input = hc_gate_mix(xn, gate, self.hc_count)
@@ -172,16 +196,7 @@ class GatedResidual(nn.Module):
self.hc_count,
)
if self.use_combine:
# produce injection logits for combine
split_sizes = [self.lora_rank, self.hc_count, self.pad_size]
down_and_injection = self.input_mix_weight_down_block_inject(xn)
lora, injection, _ = down_and_injection.split(split_sizes, dim=-1)
else:
lora = self.input_mix_weight_down(xn)
injection = None
lora = hc_silu(lora, self.hc_count)
lora, injection = self._down_and_inject(xn)
gate = self.input_mix_weight_up(lora) # [M, D]
block_input = hc_gate_mix(xn, gate, self.hc_count)
+13
View File
@@ -13,6 +13,7 @@ from vllm.distributed import get_pp_group
from vllm.model_executor.layers.fused_moe.utils import (
is_model_fused_shared_expert_compatible,
)
from vllm.model_executor.layers.fusion.mm_input_norm import build_mm_input_norm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
QwenGatedDeltaNetAttention,
@@ -78,6 +79,7 @@ from vllm.v1.kv_cache_interface import MambaSpec
from ..config import ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig
from .hyperconnection import GatedResidual, HyperConnectionConfig
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
from .ops.cute_dsl.hc_down_silu import request_hc_down_silu_warmup
from .ple_layer import Qwen4ExpPLELayer
from .qsa import Qwen4ExpQSAAttention
@@ -686,6 +688,16 @@ class Qwen4ExpForCausalLM(
)
self.set_moe_parameters(self.model.layers)
enable_qwen4_exp_low_latency_gemm(self, self.model_config.dtype)
if self.model_config.dtype == torch.bfloat16:
# Precompile the fused HC down+SiLU kernels for every CUDA-graph
# capture size in the fused dispatch range, so no CuTe-DSL JIT
# happens during graph capture.
request_hc_down_silu_warmup(
vllm_config.compilation_config.cudagraph_capture_sizes or (),
self.config.hc_lowrank,
self.config.hc_count,
self.config.hidden_size * self.config.hc_count,
)
@staticmethod
def get_model_state_cls():
@@ -928,6 +940,7 @@ class Qwen4ExpForConditionalGeneration(
config.vision_config,
norm_eps=config.text_config.rms_norm_eps,
quant_config=quant_config,
input_norm=build_mm_input_norm(self.model_config),
prefix=maybe_prefix(prefix, "visual"),
)
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,334 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Adapted from vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_dotprod.py.
Fuses the Qwen4Exp mHC SiLU epilogue (SiLU(x/HC) on columns < rank, passthrough
elsewhere, with the production bf16 rounding boundary) into the FMA kernel.
Output is bf16 instead of fp32.
"""
import cutlass
import cutlass.cute as cute
from cuda.bindings.driver import CUstream
from cutlass import const_expr
def _sigmoid_f32(x):
return cute.math.rcp(1.0 + cute.math.exp(-x), approx=True)
class HcDownSiluFma:
"""BF16 GEMM kernel based on CTA-local FMA dot products, with the mHC SiLU
epilogue fused into the final store.
Computes C[M, N] = A[M, K] @ B[N, K]^T for bf16 inputs, rounds the fp32
accumulator to bf16 (production rounding boundary), then applies
SiLU(x/HC) to columns < ``rank`` and passes columns >= ``rank`` through.
Output is bf16 [M, N].
See the base class docstring in
vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_dotprod.py for the
GEMM structure; only the epilogue differs. The compile key is
``(M, K, threadblock_size, rank, hc)``.
"""
def __init__(
self,
k: int,
threadblock_size: int = 128,
main_vec_width: int = 8,
tail_vec_width: int = 4,
prefetch_pdl_weights: bool = False,
rank: int = 320,
hc: int = 4,
):
self.threadblock_size = threadblock_size
self.main_vec_width = main_vec_width
self.tail_vec_width = tail_vec_width
self.prefetch_pdl_weights = prefetch_pdl_weights
self.rank = rank
self.hc = hc
self.num_warps = threadblock_size // cute.arch.WARP_SIZE
self._init_k_tiles(k)
self.main_prefetch_tiles = min(self.main_tiles, 8)
def _vectorized_elems(self, k_extent: int, vec_width: int) -> int:
vector_tile = vec_width * self.threadblock_size
return (k_extent // vector_tile) * vector_tile
def _init_k_tiles(self, k: int) -> None:
"""Split K into vector loops, scalar rounds, and ragged tail."""
self.k_main_elems = self._vectorized_elems(k, self.main_vec_width)
self.k_after_main = k - self.k_main_elems
self.k_tail_elems = self._vectorized_elems(
self.k_after_main, self.tail_vec_width
)
self.k_done_all = self.k_main_elems + self.k_tail_elems
self.scalar_rem = k - self.k_done_all
self.ks_full = self.scalar_rem // self.threadblock_size
self.ks_part = self.scalar_rem % self.threadblock_size
self.k_scalar_full = self.ks_full * self.threadblock_size
self.k_part_offset = self.k_done_all + self.k_scalar_full
self.main_tiles = self.k_main_elems // (
self.main_vec_width * self.threadblock_size
)
self.tail_tiles = self.k_tail_elems // (
self.tail_vec_width * self.threadblock_size
)
@cute.jit
def _vector_fma(
self,
acc: cute.Tensor,
tA: cute.Tensor,
tB: cute.Tensor,
M: cutlass.Constexpr,
num_tiles: cutlass.Constexpr,
align_bytes: cutlass.Constexpr,
):
for tile in cutlass.range_constexpr(num_tiles):
bt = tB[None, tile]
br = cute.make_rmem_tensor_like(bt)
cute.autovec_copy(bt, br)
br_f32 = br.load().to(cutlass.Float32)
for m in cutlass.range_constexpr(M):
at = tA[m, None, tile]
ar = cute.make_rmem_tensor_like(at)
cute.autovec_copy(at, ar)
vec_width: cutlass.Constexpr = cute.size(ar)
for v in cutlass.range_constexpr(vec_width):
acc[m] = acc[m] + ar[v].to(cutlass.Float32) * br_f32[v]
@cute.jit
def _vector_fma_prefetched(
self,
acc: cute.Tensor,
tA: cute.Tensor,
tB: cute.Tensor,
rB: cute.Tensor,
M: cutlass.Constexpr,
num_tiles: cutlass.Constexpr,
prefetch_tiles: cutlass.Constexpr,
):
for tile in cutlass.range_constexpr(num_tiles):
if const_expr(tile < prefetch_tiles):
br_f32 = rB[tile, None].load().to(cutlass.Float32)
else:
bt = tB[None, tile]
br = cute.make_rmem_tensor_like(bt)
cute.autovec_copy(bt, br)
br_f32 = br.load().to(cutlass.Float32)
for m in cutlass.range_constexpr(M):
at = tA[m, None, tile]
ar = cute.make_rmem_tensor_like(at)
cute.autovec_copy(at, ar)
vec_width: cutlass.Constexpr = cute.size(ar)
for v in cutlass.range_constexpr(vec_width):
acc[m] = acc[m] + ar[v].to(cutlass.Float32) * br_f32[v]
def _make_thread_vector_slice(
self,
gA_vec: cute.Tensor,
gB_vec: cute.Tensor,
tidx: cutlass.Int32,
n_idx: cutlass.Int32,
threadblock_size: cutlass.Constexpr,
):
# (M/N, K_TILE, K_LANE, K_VEC); tidx selects K_LANE.
tA = cute.logical_divide(gA_vec, (None, (None, threadblock_size)))
tB = cute.logical_divide(gB_vec, (None, (None, threadblock_size)))
return tA[None, (None, (tidx, None))], tB[n_idx, (None, (tidx, None))]
def _make_k_slice(
self,
gX: cute.Tensor,
k_offset: cutlass.Constexpr,
k_extent: cutlass.Constexpr,
):
k_layout_extent: cutlass.Constexpr = (
1 if const_expr(k_extent == 0) else k_extent
)
if const_expr(k_offset == 0):
return cute.local_tile(
gX, (cute.size(gX, mode=[0]), k_layout_extent), (0, 0)
)
return cute.local_tile(
cute.domain_offset((0, k_offset), gX),
(cute.size(gX, mode=[0]), k_layout_extent),
(0, 0),
)
@cute.jit
def __call__(
self,
gA: cute.Tensor,
gB: cute.Tensor,
gC: cute.Tensor,
M: cutlass.Constexpr,
K_dim: cutlass.Constexpr,
N_dim: cutlass.Int32,
stream: CUstream,
):
self.kernel(
gA,
gB,
gC,
M,
self.main_vec_width,
self.tail_vec_width,
self.threadblock_size,
self.num_warps,
self.k_main_elems,
self.k_tail_elems,
self.k_done_all,
self.ks_full,
self.ks_part,
self.k_scalar_full,
self.k_part_offset,
self.main_tiles,
self.tail_tiles,
self.rank,
self.hc,
).launch(
grid=[N_dim, 1, 1],
block=[self.threadblock_size, 1, 1],
smem=M * 4 * self.num_warps,
stream=stream,
use_pdl=True,
min_blocks_per_mp=1,
)
@cute.kernel
def kernel(
self,
gA: cute.Tensor,
gB: cute.Tensor,
gC: cute.Tensor,
M: cutlass.Constexpr,
main_vec_width: cutlass.Constexpr,
tail_vec_width: cutlass.Constexpr,
threadblock_size: cutlass.Constexpr,
num_warps: cutlass.Constexpr,
k_main_elems: cutlass.Constexpr,
k_tail_elems: cutlass.Constexpr,
k_done_all: cutlass.Constexpr,
ks_full: cutlass.Constexpr,
ks_part: cutlass.Constexpr,
k_scalar_full: cutlass.Constexpr,
k_part_offset: cutlass.Constexpr,
main_tiles: cutlass.Constexpr,
tail_tiles: cutlass.Constexpr,
rank: cutlass.Constexpr,
hc: cutlass.Constexpr,
):
tidx, _, _ = cute.arch.thread_idx()
n_idx, _, _ = cute.arch.block_idx()
wid = cute.arch.warp_idx()
# One FP32 accumulator per token.
acc = cute.make_rmem_tensor((M,), cutlass.Float32)
acc.fill(0.0)
if const_expr(k_main_elems > 0):
gA_main = self._make_k_slice(gA, 0, k_main_elems)
gB_main = self._make_k_slice(gB, 0, k_main_elems)
gA_vec = cute.logical_divide(gA_main, (None, main_vec_width))
gB_vec = cute.logical_divide(gB_main, (None, main_vec_width))
tA, tB = self._make_thread_vector_slice(
gA_vec, gB_vec, tidx, n_idx, threadblock_size
)
if const_expr(self.prefetch_pdl_weights):
prefetch_tiles: cutlass.Constexpr = self.main_prefetch_tiles
prefetched_b = cute.make_rmem_tensor(
cute.make_layout(
(prefetch_tiles, main_vec_width),
stride=(main_vec_width, 1),
),
cutlass.BFloat16,
)
for tile in cutlass.range_constexpr(prefetch_tiles):
cute.autovec_copy(tB[None, tile], prefetched_b[tile, None])
cute.arch.griddepcontrol_wait()
# 128-bit vectorized main loop
if const_expr(k_main_elems > 0):
if const_expr(self.prefetch_pdl_weights):
self._vector_fma_prefetched(
acc,
tA,
tB,
prefetched_b,
M,
main_tiles,
prefetch_tiles,
)
else:
self._vector_fma(acc, tA, tB, M, main_tiles, 16)
# 64-bit vectorized tail (K remainder after main loop)
if const_expr(k_tail_elems > 0):
gA_tail = self._make_k_slice(gA, k_main_elems, k_tail_elems)
gB_tail = self._make_k_slice(gB, k_main_elems, k_tail_elems)
gA_tail_vec = cute.logical_divide(gA_tail, (None, tail_vec_width))
gB_tail_vec = cute.logical_divide(gB_tail, (None, tail_vec_width))
tA_t, tB_t = self._make_thread_vector_slice(
gA_tail_vec, gB_tail_vec, tidx, n_idx, threadblock_size
)
self._vector_fma(acc, tA_t, tB_t, M, tail_tiles, 8)
# Full scalar rounds use CuTe width-1 tiles; KS_PART is the ragged tail.
if const_expr(ks_full > 0):
gA_scalar = self._make_k_slice(gA, k_done_all, k_scalar_full)
gB_scalar = self._make_k_slice(gB, k_done_all, k_scalar_full)
gA_scalar_vec = cute.logical_divide(gA_scalar, (None, 1))
gB_scalar_vec = cute.logical_divide(gB_scalar, (None, 1))
tA_s, tB_s = self._make_thread_vector_slice(
gA_scalar_vec, gB_scalar_vec, tidx, n_idx, threadblock_size
)
self._vector_fma(acc, tA_s, tB_s, M, ks_full, 2)
# Only threads below KS_PART load the ragged tail.
if const_expr(ks_part > 0):
gA_part = self._make_k_slice(gA, k_part_offset, ks_part)
gB_part = self._make_k_slice(gB, k_part_offset, ks_part)
if tidx < ks_part:
bv2 = gB_part[n_idx, tidx].to(cutlass.Float32)
for m in cutlass.range_constexpr(M):
acc[m] = acc[m] + gA_part[m, tidx].to(cutlass.Float32) * bv2
# Intra-warp shuffle reduction
for m in cutlass.range_constexpr(M):
acc[m] = cute.arch.warp_reduction_sum(acc[m])
# Cross-warp reduction via shared memory
smem_red_layout = cute.make_layout((M, num_warps), stride=(num_warps, 1))
smem = cutlass.utils.SmemAllocator()
sm = smem.allocate_tensor(cutlass.Float32, smem_red_layout, byte_alignment=16)
with cute.arch.elect_one():
for m in cutlass.range_constexpr(M):
sm[m, wid] = acc[m]
# Final reduction, fused mHC SiLU epilogue, and output.
cute.arch.sync_threads()
if tidx == 0:
for m in cutlass.range_constexpr(M):
partials = sm[m, None].load()
total = cutlass.Float32(
partials.reduce(
cute.ReductionOp.ADD,
init_val=cutlass.Float32(0.0),
reduction_profile=0,
)
)
# Production rounding boundary: GEMM output is materialized as
# bf16 before _hc_silu_kernel reads it.
x_bf16 = total.to(cutlass.BFloat16)
if n_idx < rank:
z = x_bf16.to(cutlass.Float32) * (1.0 / hc)
gC[m, n_idx] = (z * _sigmoid_f32(z)).to(cutlass.BFloat16)
else:
gC[m, n_idx] = x_bf16
cute.arch.griddepcontrol_launch_dependents()
@@ -0,0 +1,536 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Adapted from vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py.
Fuses the Qwen4Exp mHC SiLU epilogue (SiLU(x/HC) on columns < rank, passthrough
elsewhere, with the production bf16 rounding boundary) into the split-K kernel,
applied after the cluster reduction where the final fp32 result materializes.
Output is bf16 instead of fp32.
"""
import math
import cutlass
import cutlass.cute as cute
from cuda.bindings.driver import CUstream
from cutlass._mlir import ir as _ir
from cutlass._mlir.dialects import llvm as _llvm
from cutlass.cutlass_dsl import dsl_user_op
from cutlass.pipeline import sm90 as pipeline
# Map a local smem address to the same peer CTA DSMEM offset.
@dsl_user_op
def set_block_rank(smem_ptr, peer_rank, *, loc=None, ip=None):
dsmem_ptr = cute.arch.map_dsmem_ptr(smem_ptr, peer_rank, loc=loc, ip=ip)
return cutlass.Int32(dsmem_ptr.toint(loc=loc, ip=ip))
# Plain DSMEM store; mbarrier helpers do not model this reduction.
@dsl_user_op
def st_shared_remote_f32(remote_addr, val, *, loc=None, ip=None):
i32 = _ir.IntegerType.get_signless(32)
addr_ir = remote_addr.ir_value(loc=loc, ip=ip)
val_ir = val.ir_value(loc=loc, ip=ip)
_llvm.inline_asm(
i32,
[addr_ir, val_ir],
"st.shared::cluster.f32 [$0], $1; mov.u32 $2, 0;",
"r,f,=r",
has_side_effects=True, # keep the inline store ordered
loc=loc,
ip=ip,
)
def _sigmoid_f32(x):
return cute.math.rcp(1.0 + cute.math.exp(-x), approx=True)
class HcDownSiluMma:
"""BF16 GEMM kernel based on clustered split-K MMA, with the mHC SiLU
epilogue fused into the final store.
Computes C[M, N] = A[M, K] @ B[N, K]^T for bf16 inputs, rounds the reduced
fp32 accumulator to bf16 (production rounding boundary), then applies
SiLU(x/HC) to columns < ``rank`` and passes columns >= ``rank`` through.
Output is bf16 [M, N].
See the base class docstring in
vllm/model_executor/kernels/linear/cute_dsl/_ll_bf16_splitk.py for the
GEMM structure; only the epilogue differs. The compile key is
``(split_k, num_stages, tile_n, rank, hc)``.
"""
def __init__(
self,
ab_dtype=cutlass.BFloat16,
acc_dtype=cutlass.Float32,
tile_n: int = 16,
tile_k: int = 256,
num_stages: int = 2,
num_dma_warps: int = 4,
split_k: int = 8,
rank: int = 320,
hc: int = 4,
):
self.ab_dtype = ab_dtype
self.acc_dtype = acc_dtype
self.rank = rank
self.hc = hc
self.tile_m = 16
self.tile_n = tile_n
self.tile_k = tile_k
self.copy_bits = 128
self.num_stages = num_stages
self.split_k = split_k
self.mma_shape = (16, 8, 16) # mma.sync.aligned.m16n8k16
self.atom_layout = (1, 1, 1) # one MMA atom per warp
self.num_dma_warps = num_dma_warps
self.num_mma_warps = 4
self.num_dma_threads = self.num_dma_warps * cute.arch.WARP_SIZE
self.num_mma_threads = self.num_mma_warps * cute.arch.WARP_SIZE
self.num_threads = self.num_dma_threads + self.num_mma_threads
self.num_epilogue_elems = self.tile_m * self.tile_n
self.epilogue_elems_per_thread = self.num_epilogue_elems // self.num_mma_threads
def _make_smem_layout_AB(self, dtype, copy_bits, smem_tiler):
"""Build the staged swizzled SMEM layout for A or B tiles."""
major_size = min(smem_tiler[1], 64)
# Match swizzle span to contiguous K bytes, capped by CuTe 3-bit swizzle.
swizzle_bits = int(math.log2(major_size * dtype.width // copy_bits))
swizzle_bits = min(swizzle_bits, 3)
# Tile the swizzled atom across (M_or_N, K, stages).
layout_atom_outer = cute.make_layout((8, major_size), stride=(major_size, 1))
layout_atom = cute.make_composed_layout(
cute.make_swizzle(swizzle_bits, 3, 3), 0, layout_atom_outer
)
return cute.tile_to_shape(layout_atom, smem_tiler, (0, 1, 2))
def _make_gmem_tiled_copy(self, atom_copy, dtype, copy_bits, num_threads):
"""Build the per-thread cp.async vector-copy layout."""
# Lay threads across K so each lane issues one vector copy.
copy_elems = copy_bits // dtype.width
k_threads = cute.size(self.tile_k) // copy_elems # threads along K
thread_layout = cute.make_layout(
(num_threads // k_threads, k_threads), stride=(k_threads, 1)
)
value_layout = cute.make_layout((1, copy_elems))
return cute.make_tiled_copy_tv(atom_copy, thread_layout, value_layout)
@cute.jit
def _fill_pred(self, pred_flat, coord_tensor, k_tile, dim_limit, K_total):
# Predicate one K tile and keep the stage-broadcast view in sync.
coord_ktile = coord_tensor[None, None, 0, k_tile]
num_vec = pred_flat.shape[0]
num_mn = pred_flat.shape[1]
for v in cutlass.range_constexpr(num_vec):
# pred_flat is (K_VEC, M/N) for one K_TILE.
for j in cutlass.range_constexpr(num_mn):
pred_flat[v, j] = cute.elem_less(
coord_ktile[(0, v), j], (dim_limit, K_total)
)
def _make_pred(self, tXcX, k_tile, dim_limit, K_total):
# pred_flat is (K_VEC, M/N); pred is (K_VEC, M/N, STAGE).
num_vec = tXcX.shape[0][1]
num_mn = cute.size(tXcX, mode=[1])
pred_flat = cute.make_rmem_tensor(
cute.make_layout((num_vec, num_mn), stride=(num_mn, 1)),
cutlass.Boolean,
)
pred = cute.make_tensor(
pred_flat.iterator,
cute.make_layout(
(num_vec, num_mn, cute.size(tXcX, mode=[2])),
stride=(num_mn, 1, 0),
),
)
return pred_flat, pred
@cute.jit
def __call__(
self,
mA: cute.Tensor,
mB: cute.Tensor,
mC: cute.Tensor,
stream: CUstream,
):
bM, bN, bK = self.tile_m, self.tile_n, self.tile_k
copy_bits: cutlass.Constexpr = self.copy_bits
sA_layout = self._make_smem_layout_AB(
mA.element_type, copy_bits, (bM, bK, self.num_stages)
)
sB_layout = self._make_smem_layout_AB(
mB.element_type, copy_bits, (bN, bK, self.num_stages)
)
@cute.struct
class SharedStorage:
a: cute.struct.Align[
cute.struct.MemRange[mA.element_type, cute.cosize(sA_layout)], 16
]
b: cute.struct.Align[
cute.struct.MemRange[mB.element_type, cute.cosize(sB_layout)], 16
]
mbar: cute.struct.Align[
cute.struct.MemRange[cutlass.Int64, self.num_stages * 2], 8
]
atom_g2s = cute.make_copy_atom(
cute.nvgpu.cpasync.CopyG2SOp(
cache_mode=cute.nvgpu.cpasync.LoadCacheMode.GLOBAL
),
mA.element_type,
num_bits_per_copy=copy_bits,
) # cp.async GMEM -> SMEM, bypassing L1
tiled_copy_A = self._make_gmem_tiled_copy(
atom_g2s, mA.element_type, copy_bits, self.num_dma_threads
)
tiled_copy_B = self._make_gmem_tiled_copy(
atom_g2s, mB.element_type, copy_bits, self.num_dma_threads
)
op = cute.nvgpu.warp.MmaF16BF16Op(self.ab_dtype, self.acc_dtype, self.mma_shape)
# Repeat the m16n8k16 atom along N to cover the CTA output tile.
perm_mnk = (
self.atom_layout[0] * self.mma_shape[0],
self.atom_layout[1] * self.mma_shape[1] * (self.tile_n // 8),
self.atom_layout[2] * self.mma_shape[2],
)
tiled_mma = cute.make_tiled_mma(
op, cute.make_layout(self.atom_layout), permutation_mnk=perm_mnk
)
tiler_mn = (bM, bN)
grid_m, grid_n = cute.ceil_div(mC.shape, tiler_mn)
self.kernel(
mA,
mB,
mC,
sA_layout,
sB_layout,
tiled_copy_A,
tiled_copy_B,
tiled_mma,
SharedStorage,
self.rank,
self.hc,
).launch(
grid=[
cute.size(grid_m),
cute.size(grid_n),
self.split_k,
],
block=[self.num_threads, 1, 1],
cluster=[
1,
1,
self.split_k,
], # split-K CTAs form one cluster
stream=stream,
use_pdl=True,
)
@cute.kernel
def kernel(
self,
mA,
mB,
mC,
sA_layout: cute.ComposedLayout,
sB_layout: cute.ComposedLayout,
tiled_copy_A: cute.TiledCopy,
tiled_copy_B: cute.TiledCopy,
tiled_mma: cute.TiledMma,
shared_storage: cutlass.Constexpr,
rank: cutlass.Constexpr,
hc: cutlass.Constexpr,
):
bM, bN, bK = self.tile_m, self.tile_n, self.tile_k
num_stages = self.num_stages
tidx, _, _ = cute.arch.thread_idx()
bid_m, bid_n, bid_z = cute.arch.block_idx()
warp_idx = cute.arch.warp_idx()
lane_id = cute.arch.lane_idx()
num_dma_warps: cutlass.Constexpr = self.num_dma_warps
is_dma_warp = warp_idx < num_dma_warps
dma_tidx = tidx
mma_tidx = tidx - self.num_dma_threads
mma_warp_idx = warp_idx - num_dma_warps
cta_tiler = (bM, bN, bK)
coord = (bid_m, bid_n, None) # all K tiles
# CTA-local tiles.
gA = cute.local_tile(
mA, tiler=cta_tiler, coord=coord, proj=(1, None, 1)
) # skip N
gB = cute.local_tile(
mB, tiler=cta_tiler, coord=coord, proj=(None, 1, 1)
) # skip M
gC = cute.local_tile(
mC, tiler=cta_tiler, coord=coord, proj=(1, 1, None)
) # skip K
mcA = cute.make_identity_tensor(mA.layout.shape)
mcB = cute.make_identity_tensor(mB.layout.shape)
mcC = cute.make_identity_tensor(mC.layout.shape)
# Coordinate modes: cA=(M,K,k_tile), cB=(N,K,k_tile), cC=(M,N).
cA = cute.local_tile(mcA, tiler=cta_tiler, coord=coord, proj=(1, None, 1))
cB = cute.local_tile(mcB, tiler=cta_tiler, coord=coord, proj=(None, 1, 1))
cC = cute.local_tile(mcC, tiler=cta_tiler, coord=coord, proj=(1, 1, None))
# 128-bit cp.async copies require 16-byte aligned GMEM views.
gA = cute.make_tensor(gA.iterator.align(16), gA.layout)
gB = cute.make_tensor(gB.iterator.align(16), gB.layout)
smem = cutlass.utils.SmemAllocator()
storage_ptr = smem.allocate(shared_storage.size_in_bytes(), byte_alignment=16) # type: ignore[attr-defined]
storage = shared_storage(storage_ptr) # type: ignore[call-arg]
sA = storage.a.get_tensor(sA_layout)
sB = storage.b.get_tensor(sB_layout)
# Pipeline cp.async producers into MMA consumers.
producer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, self.num_dma_threads
)
consumer_group = pipeline.CooperativeGroup(
pipeline.Agent.Thread, self.num_mma_threads
)
mainloop_pipeline = pipeline.PipelineCpAsync.create(
barrier_storage=storage.mbar.data_ptr(),
num_stages=num_stages,
producer_group=producer_group,
consumer_group=consumer_group,
)
# Round-robin split-K: split z handles tiles z, z+split_k, ...
K_total = cute.size(mA, mode=[1])
k_tile_count = cute.size(gA, mode=[2])
k_start = bid_z
num_k_tiles = cute.ceil_div(k_tile_count - k_start, self.split_k)
if is_dma_warp:
# DMA warps trade registers for copy throughput.
cute.arch.setmaxregister_decrease(40)
thr_A = tiled_copy_A.get_slice(dma_tidx)
thr_B = tiled_copy_B.get_slice(dma_tidx)
tAgA = thr_A.partition_S(gA)
tAsA = thr_A.partition_D(sA)
tBgB = thr_B.partition_S(gB)
tBsB = thr_B.partition_D(sB)
tAcA = thr_A.partition_S(cA)
tBcB = thr_B.partition_S(cB)
# Build M/K and N/K predicates, broadcast across K-tile copies.
tApA_flat, tApA = self._make_pred(tAcA, k_start, mA.shape[0], K_total)
tBpB_flat, tBpB = self._make_pred(tBcB, k_start, mB.shape[0], K_total)
self._fill_pred(tApA_flat, tAcA, k_start, mA.shape[0], K_total)
self._fill_pred(tBpB_flat, tBcB, k_start, mB.shape[0], K_total)
producer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Producer, num_stages
)
# Prime the first pipeline stage.
mainloop_pipeline.producer_acquire(producer_state)
cute.copy(
tiled_copy_B,
tBgB[None, None, None, k_start],
tBsB[None, None, None, producer_state.index],
pred=tBpB,
)
cute.arch.griddepcontrol_wait()
cute.copy(
tiled_copy_A,
tAgA[None, None, None, k_start],
tAsA[None, None, None, producer_state.index],
pred=tApA,
)
mainloop_pipeline.producer_commit(producer_state)
producer_state.advance()
for k_tile in cutlass.range(
k_start + self.split_k, k_tile_count, self.split_k, unroll=1
):
self._fill_pred(tApA_flat, tAcA, k_tile, mA.shape[0], K_total)
self._fill_pred(tBpB_flat, tBcB, k_tile, mB.shape[0], K_total)
mainloop_pipeline.producer_acquire(producer_state)
cute.copy(
tiled_copy_A,
tAgA[None, None, None, k_tile],
tAsA[None, None, None, producer_state.index],
pred=tApA,
)
cute.copy(
tiled_copy_B,
tBgB[None, None, None, k_tile],
tBsB[None, None, None, producer_state.index],
pred=tBpB,
)
mainloop_pipeline.producer_commit(producer_state)
producer_state.advance()
mainloop_pipeline.producer_tail(producer_state)
else:
# MMA warps with k-phase interleaving
cute.arch.setmaxregister_increase(232) # large MMA fragments
num_mma_warps: cutlass.Constexpr = self.num_mma_warps
thr_mma = tiled_mma.get_slice(lane_id)
tCsA = thr_mma.partition_A(sA)
tCsB = thr_mma.partition_B(sB)
tCgC = thr_mma.partition_C(gC)
tCrA = tiled_mma.make_fragment_A(tCsA[None, None, None, 0])
tCrB = tiled_mma.make_fragment_B(tCsB[None, None, None, 0])
tCrC = tiled_mma.make_fragment_C(tCgC)
tCrC.fill(0.0)
# ldmatrix moves SMEM fragments into MMA registers.
atom_s2r_A = cute.make_copy_atom(
cute.nvgpu.warp.LdMatrix8x8x16bOp(False, 4), mA.element_type
) # non-transposed, x4
atom_s2r_B = cute.make_copy_atom(
cute.nvgpu.warp.LdMatrix8x8x16bOp(False, 4), mB.element_type
)
# SMEM -> register copy path.
tiled_s2r_A = cute.make_tiled_copy_A(atom_s2r_A, tiled_mma)
tiled_s2r_B = cute.make_tiled_copy_B(atom_s2r_B, tiled_mma)
thr_s2r_A = tiled_s2r_A.get_slice(lane_id)
thr_s2r_B = tiled_s2r_B.get_slice(lane_id)
tCsA_v = thr_s2r_A.partition_S(sA) # views, not copies
tCrA_v = thr_s2r_A.retile(tCrA)
tCsB_v = thr_s2r_B.partition_S(sB)
tCrB_v = thr_s2r_B.retile(tCrB)
# Split the MMA K-fragments across the MMA warps.
tCsA_warp_v = cute.logical_divide(tCsA_v, (None, None, num_mma_warps, None))
tCsB_warp_v = cute.logical_divide(tCsB_v, (None, None, num_mma_warps, None))
num_k_blocks = cute.size(tCrA, mode=[2])
k_blocks_per_warp: cutlass.Constexpr = num_k_blocks // num_mma_warps
consumer_state = pipeline.make_pipeline_state(
pipeline.PipelineUserType.Consumer, num_stages
)
# Shape-dynamic split-K count, so this stays a runtime range.
for _ in cutlass.range(num_k_tiles, unroll_full=True):
mainloop_pipeline.consumer_wait(consumer_state)
for ki in cutlass.range_constexpr(k_blocks_per_warp):
cute.copy(
tiled_s2r_A,
tCsA_warp_v[
None, None, (mma_warp_idx, ki), consumer_state.index
],
tCrA_v[None, None, 0],
) # ldmatrix
cute.copy(
tiled_s2r_B,
tCsB_warp_v[
None, None, (mma_warp_idx, ki), consumer_state.index
],
tCrB_v[None, None, 0],
)
cute.gemm(
tiled_mma, tCrC, tCrA[None, None, 0], tCrB[None, None, 0], tCrC
) # mma.sync
mainloop_pipeline.consumer_release(consumer_state)
consumer_state.advance()
# Cluster reduction epilogue.
# Reduce per-warp accumulators within this CTA.
num_elems: cutlass.Constexpr = self.num_epilogue_elems
elems_per_thread: cutlass.Constexpr = self.epilogue_elems_per_thread
# Map MMA threads to linear CTA output elements.
epilogue_thread_layout = cute.make_layout(
(elems_per_thread, self.num_mma_threads),
stride=(self.num_mma_threads, 1),
)
epilogue_slots = cute.make_tensor(0, epilogue_thread_layout)
epilogue_slot_coords = cute.make_identity_tensor((bN, bM))
# Layout: (mma_warp, linear MN element).
smem_red = cute.make_tensor(
cute.arch.alloc_smem(
cutlass.Float32, num_elems * num_mma_warps, alignment=16
),
cute.make_layout((num_mma_warps, num_elems), stride=(num_elems, 1)),
)
smem_warp = cute.make_tensor(
cute.domain_offset((mma_warp_idx, 0), smem_red).iterator,
cute.make_layout((bM, bN), stride=(bN, 1)),
)
tCsC_partial = thr_mma.partition_C(smem_warp)
cute.autovec_copy(tCrC, tCsC_partial)
cute.arch.sync_threads()
# Layout: (split-K rank, linear MN element).
partials = cute.make_tensor(
cute.arch.alloc_smem(
cutlass.Float32, num_elems * self.split_k, alignment=16
),
cute.make_layout((self.split_k, num_elems), stride=(num_elems, 1)),
)
cta_rank = cute.arch.block_idx_in_cluster()
for ei in cutlass.range_constexpr(elems_per_thread):
elem_idx = epilogue_slots[ei, mma_tidx]
local_coord = cute.select(epilogue_slot_coords[elem_idx], mode=[1, 0])
total = cutlass.Float32(0.0)
if cute.elem_less(local_coord, gC.shape):
total = (
smem_red[None, elem_idx]
.load()
.reduce(
cute.ReductionOp.ADD,
init_val=cutlass.Float32(0.0),
reduction_profile=0,
)
)
partials[cta_rank, elem_idx] = total
cute.arch.sync_threads()
# Broadcast this CTA's partials to peer DSMEM.
for ei in cutlass.range_constexpr(elems_per_thread):
elem_idx = epilogue_slots[ei, mma_tidx]
my_slot = cute.domain_offset((cta_rank, elem_idx), partials).iterator
my_val = partials[cta_rank, elem_idx]
for peer in cutlass.range_constexpr(self.split_k):
remote = set_block_rank(my_slot, cutlass.Int32(peer))
st_shared_remote_f32(remote, my_val)
cute.arch.cluster_arrive()
cute.arch.cluster_wait() # peer DSMEM stores are now visible
if mma_tidx == 0:
cute.arch.griddepcontrol_launch_dependents()
cute.arch.sync_threads()
# Reduce split-K partials, apply the fused mHC SiLU epilogue, and
# write the bf16 global output.
for ei in cutlass.range_constexpr(elems_per_thread):
elem_idx = epilogue_slots[ei, mma_tidx]
local_coord = cute.select(epilogue_slot_coords[elem_idx], mode=[1, 0])
global_coord = cC[local_coord]
if cute.elem_less(global_coord, mC.shape):
acc = cutlass.Float32(
partials[None, elem_idx]
.load()
.reduce(
cute.ReductionOp.ADD,
init_val=cutlass.Float32(0.0),
reduction_profile=0,
)
)
# Production rounding boundary: the GEMM result is
# materialized as bf16 before _hc_silu_kernel reads it.
x_bf16 = acc.to(cutlass.BFloat16)
if global_coord[1] < rank:
z = x_bf16.to(cutlass.Float32) * (1.0 / hc)
gC[local_coord] = (z * _sigmoid_f32(z)).to(cutlass.BFloat16)
else:
gC[local_coord] = x_bf16
cute.arch.sync_threads()
@@ -0,0 +1,224 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Adapted from vllm/model_executor/kernels/linear/cute_dsl/ll_bf16.py.
Fused Qwen4Exp mHC down projection + SiLU epilogue, where
columns < lora_rank get ``silu(bf16(acc) / hc_count)``, the hc_count
injection-logit columns pass through as ``bf16(acc)``, and the pad columns
are never computed. Output is bf16 (ll_bf16's fp32-output bonus is given up
to preserve the production rounding boundary).
The GEMM uses an FMA backend for M <= 4 and a split-K MMA backend beyond,
both with PDL. The model uses its Linear module above M=48.
"""
import logging
from collections.abc import Iterable
from functools import lru_cache, partial
from typing import Any, Literal
import torch
from vllm.platforms import current_platform
logger = logging.getLogger(__name__)
# The fused kernel stops winning past M ~ 64 on Qwen3.8-Next-Flash.
MAX_FUSED_M = 48
# Split-K configs tuned on SM100f for Qwen3.8-Flash-Next (K=10240, N=324).
_SM100F_TUNED_SPLITK: dict[int, tuple[int, int, int]] = {
**{m: (6, 5, 8) for m in range(5, 17)},
**{m: (6, 5, 16) for m in range(17, 33)},
**{m: (6, 4, 16) for m in range(33, MAX_FUSED_M + 1)},
}
# FMA: (backend, M, K, threadblock_size); MMA: (backend, split_k, stages, tile_n).
CompileKey = tuple[Literal["fma", "mma"], int, int, int]
class HcDownSiluGemm:
"""Dispatch/compile cache for the fused mHC down+SiLU GEMM."""
def __init__(
self, rank: int, hc: int, k: int, *, prefetch_pdl_weights: bool = False
) -> None:
self.rank = rank
self.hc = hc
self.k = k
self._prefetch_pdl_weights = prefetch_pdl_weights
self._compiled: dict[CompileKey, Any] = {}
self._warmup_m: set[int] = set()
self._warmup_registered = False
def dispatch(self, m: int) -> CompileKey:
if m <= 4 or self.k < 2048:
return ("fma", m, self.k, 128)
return ("mma", *_SM100F_TUNED_SPLITK[m])
def compile(self, compile_key: CompileKey) -> None:
if compile_key in self._compiled:
return
import cutlass.cute as cute
from cutlass import BFloat16
from quack.compile_utils import make_fake_tensor
N = cute.sym_int()
gemm: Any
extra_args: tuple[int, ...]
if compile_key[0] == "mma":
from ._hc_down_silu_mma import HcDownSiluMma
_, split_k, num_stages, tile_n = compile_key
M, K = cute.sym_int(), cute.sym_int()
gemm = HcDownSiluMma(
tile_n=tile_n,
num_stages=num_stages,
split_k=split_k,
rank=self.rank,
hc=self.hc,
)
extra_args = ()
options = "--enable-tvm-ffi"
else:
from ._hc_down_silu_fma import HcDownSiluFma
_, M, K, threadblock_size = compile_key
gemm = HcDownSiluFma(
k=K,
threadblock_size=threadblock_size,
prefetch_pdl_weights=self._prefetch_pdl_weights,
rank=self.rank,
hc=self.hc,
)
extra_args = (M, K, 1) # runtime N placeholder
options = "--enable-tvm-ffi --ptxas-options -maxrregcount=64"
hidden_states = make_fake_tensor(BFloat16, (M, K), divisibility=8)
router_weight = make_fake_tensor(BFloat16, (N, K), divisibility=8)
output = make_fake_tensor(BFloat16, (M, N), divisibility=1)
self._compiled[compile_key] = cute.compile(
gemm,
hidden_states,
router_weight,
output,
*extra_args,
cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True),
options=options,
)
logger.debug("Compiled hc_down_silu: %s", compile_key)
def request_warmup(self, m_values: Iterable[int]) -> None:
m_values = set(m_values)
if not m_values:
return
self._warmup_m.update(m_values)
if self._warmup_registered:
return
from vllm.model_executor.warmup.cutedsl_warmup import (
register_cutedsl_warmup_provider,
)
register_cutedsl_warmup_provider(self)
self._warmup_registered = True
def get_cutedsl_warmup_compile_units(self):
from vllm.model_executor.warmup.cutedsl_warmup import CuTeDSLCompileUnit
return tuple(
CuTeDSLCompileUnit(
name="Qwen4Exp HC down+SiLU GEMM",
key=(
"qwen4-exp-hc-down-silu",
self.rank,
self.hc,
self.k,
self._prefetch_pdl_weights,
compile_key,
),
compile=partial(self.compile, compile_key),
)
for compile_key in dict.fromkeys(
self.dispatch(m) for m in sorted(self._warmup_m)
)
)
def __call__(
self,
hidden_states: torch.Tensor, # [M, K] bf16
router_weight: torch.Tensor, # [N, K] bf16
) -> torch.Tensor: # [M, N] bf16
M = hidden_states.shape[0]
N = router_weight.shape[0]
n_compute = self.rank + self.hc
w_gemm = router_weight[:n_compute]
compile_key = self.dispatch(M)
self.compile(compile_key)
kernel = self._compiled[compile_key]
output = torch.empty(M, N, dtype=torch.bfloat16, device=hidden_states.device)
out_gemm = output[:, :n_compute]
if compile_key[0] == "mma":
kernel(hidden_states, w_gemm, out_gemm)
else:
kernel(hidden_states, w_gemm, out_gemm, n_compute)
return output
@lru_cache
def _get_kernel(
rank: int, hc: int, k: int, prefetch_pdl_weights: bool = False
) -> HcDownSiluGemm:
return HcDownSiluGemm(rank, hc, k, prefetch_pdl_weights=prefetch_pdl_weights)
def hc_down_silu(
x: torch.Tensor,
weight: torch.Tensor,
rank: int,
hc: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Fused Qwen4Exp HC down projection + SiLU.
Args:
x: Normalized hyper-hidden input, [M, K].
weight: Merged down+inject weight, [N, K].
rank: Number of low-rank output columns.
hc: Number of injection-logit output columns.
Returns:
LoRA activations [M, rank] and injection logits [M, hc].
"""
kernel = _get_kernel(rank, hc, weight.shape[1], x.shape[0] == 1)
output = kernel(x, weight)
return output[:, :rank], output[:, rank : rank + hc]
def request_hc_down_silu_warmup(
m_values: Iterable[int], rank: int, hc: int, k: int
) -> None:
"""Precompile the fused kernels for CUDA-graph capture token counts.
Args:
m_values: Token counts the model may capture CUDA graphs for; values
outside the fused dispatch range are ignored.
rank: Number of low-rank output columns.
hc: Number of injection-logit output columns.
k: Input feature size.
"""
if not current_platform.has_device_capability(90) or k % 8 != 0:
return
m_set = {int(m) for m in m_values if 1 <= m <= MAX_FUSED_M}
# M=1 dispatches to the weight-prefetching PDL variant.
_get_kernel(rank, hc, k, True).request_warmup(m_set & {1})
_get_kernel(rank, hc, k).request_warmup(m_set - {1})
__all__ = [
"MAX_FUSED_M",
"hc_down_silu",
"request_hc_down_silu_warmup",
]
+1 -2
View File
@@ -292,10 +292,9 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
token_indices=token_indices_d,
)
query_start_loc = metadata.non_spec_query_start_loc
query_start_loc = metadata.query_start_loc_p
if query_start_loc is None:
raise ValueError("query_start_loc is required for prefill short-conv")
query_start_loc = query_start_loc[-num_prefills - 1 :] - num_decode_tokens
has_initial_states = metadata.has_initial_states_p
if has_initial_states is None:
raise ValueError(
+177 -43
View File
@@ -5,7 +5,7 @@ from collections.abc import Callable, Mapping
from contextlib import contextmanager
from dataclasses import dataclass, field
from functools import cached_property
from typing import TYPE_CHECKING, Any, overload
from typing import TYPE_CHECKING, Any, get_type_hints, overload
import torch
from typing_extensions import TypeVar
@@ -42,46 +42,129 @@ else:
logger = init_logger(__name__)
# HuggingFace processors accept nested ``images_kwargs`` / ``videos_kwargs`` /
# ``audio_kwargs`` in addition to a shared flat namespace. vLLM's token-budget
# and dummy-input code only reads the flat keys, so scoped overrides have to
# be overlaid per modality.
_HF_MODALITY_PROCESSOR_KWARGS = {
"image": "images_kwargs",
"video": "videos_kwargs",
"audio": "audio_kwargs",
}
# HuggingFace processors accept a shared flat namespace in addition to the
# nested processor kwarg scopes ``text_kwargs`` / ``images_kwargs`` /
# ``videos_kwargs`` / ``audio_kwargs``. vLLM recognizes these scopes when
# resolving ``mm_processor_kwargs``.
_HF_PROCESSOR_KWARG_SCOPES = (
"text_kwargs",
"images_kwargs",
"videos_kwargs",
"audio_kwargs",
)
def overlay_modality_mm_kwargs(
kwargs: Mapping[str, object],
modality: str | None,
) -> dict[str, Any]:
"""Overlay HF-style nested processor kwargs onto the flat namespace.
Overlay only the requested modality so a video ``size`` bump does not leak
into the image budget. Flat keys keep their current shared-namespace
behavior when no scoped dict is present.
Args:
kwargs: Merged multi-modal processor kwargs.
modality: Target modality (``image``, ``video``, or ``audio``).
When ``None``, ``kwargs`` is copied without overlay.
Returns:
A new dict with the modality-scoped keys overlaid when present.
def _merge_scoped_mm_processor_value(
flat_value: object,
scoped_value: object,
) -> object:
"""Merge a flat value with an existing, more specific scoped value.
Mappings are merged recursively; otherwise the scoped value replaces the
flat value.
"""
merged = dict(kwargs)
if modality is None:
if isinstance(flat_value, Mapping) and isinstance(scoped_value, Mapping):
# Merge recursively so scoped leaves override matching flat leaves
# without dropping unrelated flat entries.
merged = dict(flat_value)
for key, value in scoped_value.items():
if key in merged:
merged[key] = _merge_scoped_mm_processor_value(merged[key], value)
else:
merged[key] = value
return merged
scoped_key = _HF_MODALITY_PROCESSOR_KWARGS.get(modality)
if scoped_key is None:
return merged
scoped = merged.get(scoped_key)
if not isinstance(scoped, Mapping):
return merged
return merged | dict(scoped)
return scoped_value
def _resolve_mm_processor_kwargs(
kwargs: Mapping[str, object],
supported_mm_processor_kwargs: Mapping[str, set[str]] | None = None,
) -> dict[str, object]:
"""Resolve flat processor kwargs into HuggingFace processor kwarg scopes.
With ``supported_mm_processor_kwargs``, each scope lists the flat keys it
supports. Matching flat keys are routed to every scope that supports them,
existing scoped values take precedence, and keys not supported by any scope
remain flat.
Without ``supported_mm_processor_kwargs``, flat keys already represented in
at least one existing mapping-valued scope are removed from the shared flat
namespace; all other flat keys are left unchanged because there is no
information to determine which scopes should receive them.
"""
resolved = dict(kwargs)
# Without ``supported_mm_processor_kwargs``, remove flat entries already
# represented in at least one existing mapping-valued scope. There is no
# information to route the remaining flat entries.
if supported_mm_processor_kwargs is None:
# Collect all keys represented in existing mapping-valued scopes.
# Non-mapping scope values do not contain scoped kwargs and are left
# untouched.
represented_scoped_keys: set[str] = set()
for scoped_key in _HF_PROCESSOR_KWARG_SCOPES:
scoped_kwargs = resolved.get(scoped_key)
if isinstance(scoped_kwargs, Mapping):
represented_scoped_keys.update(scoped_kwargs)
# Remove flat entries for keys already represented in a scope.
for key in represented_scoped_keys:
if key not in _HF_PROCESSOR_KWARG_SCOPES:
resolved.pop(key, None)
return resolved
# With ``supported_mm_processor_kwargs``, collect the flat kwargs before
# routing each one to the processor kwarg scopes that support it.
flat_kwargs = {
key: value
for key, value in resolved.items()
if key not in _HF_PROCESSOR_KWARG_SCOPES
}
for key, flat_value in flat_kwargs.items():
# Find every processor kwarg scope that supports this flat key. If none
# supports it, keep the key in the shared flat namespace.
supported_scopes = [
scoped_key
for scoped_key in _HF_PROCESSOR_KWARG_SCOPES
if key in supported_mm_processor_kwargs.get(scoped_key, set())
]
if not supported_scopes:
continue
# Add the flat value to each supported destination scope.
for scoped_key in supported_scopes:
# Start from a copy of the existing scoped kwargs, or an empty scope
# if absent.
if scoped_key in resolved:
scoped_kwargs = resolved[scoped_key]
# A scope must be a mapping before keys can be added to it. Do
# not replace an explicit non-mapping value.
if not isinstance(scoped_kwargs, Mapping):
raise TypeError(f"`{scoped_key}` must be a mapping")
scoped_kwargs = dict(scoped_kwargs)
else:
scoped_kwargs = {}
# Add the flat value to this scope. Existing scoped values take
# precedence.
if key in scoped_kwargs:
scoped_kwargs[key] = _merge_scoped_mm_processor_value(
flat_value, scoped_kwargs[key]
)
else:
# Assign the flat value to this scope. For mappings, assign a
# copy so the same mapping object is not shared between the flat
# value and multiple scopes.
scoped_kwargs[key] = (
dict(flat_value) if isinstance(flat_value, Mapping) else flat_value
)
resolved[scoped_key] = scoped_kwargs
# After routing to every destination, remove the flat copy.
resolved.pop(key)
return resolved
@dataclass
@@ -294,19 +377,27 @@ class InputProcessingContext:
self,
kwargs: Mapping[str, object],
*,
modality: str | None = None,
supported_mm_processor_kwargs: Mapping[str, set[str]] | None = None,
) -> dict[str, Any]:
"""Merge configured and request ``mm_processor_kwargs``.
When ``modality`` is set, HF-style nested
``images_kwargs`` / ``videos_kwargs`` / ``audio_kwargs`` are overlaid
onto the flat namespace for vLLM-side reads (token budgets, dummy
inputs). Processor construction and HF ``__call__`` should omit
``modality`` so the nested dicts still reach the HF processor.
When ``supported_mm_processor_kwargs`` is provided, flat keys are matched
against the keys supported by each HuggingFace processor kwarg scope.
Matching flat keys are routed to every scope that supports them and
removed from the shared flat namespace; keys not supported by any scope
remain flat.
Without ``supported_mm_processor_kwargs``, flat keys already represented
in at least one existing mapping-valued scope are removed from the shared
flat namespace; all other flat keys are left unchanged because there is
no information to determine which scopes should receive them.
"""
mm_config = self.model_config.get_multimodal_config()
merged = mm_config.merge_mm_processor_kwargs(kwargs)
return overlay_modality_mm_kwargs(merged, modality)
return _resolve_mm_processor_kwargs(
merged,
supported_mm_processor_kwargs=supported_mm_processor_kwargs,
)
def call_hf_processor(
self,
@@ -380,6 +471,49 @@ class BaseProcessingInfo:
"""
return self.ctx.get_hf_processor(**kwargs)
def get_supported_mm_processor_kwargs(self) -> dict[str, set[str]]:
"""Return supported kwarg names for each HF processor kwargs scope."""
processor = self.get_hf_processor()
processor_kwargs = get_type_hints(processor.valid_processor_kwargs)
supported = {
"text_kwargs": set(processor_kwargs["text_kwargs"].__annotations__),
}
if "image" in self.supported_mm_limits:
supported["images_kwargs"] = set(
processor.image_processor.valid_kwargs.__annotations__
)
if "video" in self.supported_mm_limits:
supported["videos_kwargs"] = set(
processor.video_processor.valid_kwargs.__annotations__
)
if "audio" in self.supported_mm_limits:
supported["audio_kwargs"] = set(
processor_kwargs["audio_kwargs"].__annotations__
)
return supported
@cached_property
def supported_mm_processor_kwargs(self) -> dict[str, set[str]]:
"""Supported kwarg names for each HF processor kwargs scope."""
return self.get_supported_mm_processor_kwargs()
def _merge_and_resolve_mm_processor_kwargs(
self,
mm_kwargs: Mapping[str, object],
) -> dict[str, Any]:
"""Merge configured and request ``mm_processor_kwargs``.
Flat kwargs are routed into the HuggingFace processor kwarg scopes that
support them after the configured/request merge. When a routed flat value
conflicts with an existing scoped value, the scoped value takes precedence.
"""
return self.ctx.get_merged_mm_kwargs(
mm_kwargs,
supported_mm_processor_kwargs=self.supported_mm_processor_kwargs,
)
def get_default_tok_params(self) -> TokenizeParams:
"""Construct the default parameters for tokenization."""
from vllm.renderers import TokenizeParams
+7
View File
@@ -117,6 +117,10 @@ class RequestOutput:
For encoder/decoder models, this is the
decoder input prompt token ids.
prompt_logprobs: The log probabilities to return per prompt token.
prompt_token_id_logprobs: Logprobs of prompt_logprob_token_ids, shaped
[max(prompt_len - 1 - prompt_logprob_start, 0),
len(prompt_logprob_token_ids)]; row i scores them as predictions of
prompt token prompt_logprob_start + i + 1.
outputs: The output sequences of the request.
finished: Whether the whole request is finished.
metrics: Metrics associated with the request.
@@ -148,6 +152,7 @@ class RequestOutput:
num_cached_tokens: int | None = None,
num_cache_creation_tokens: int | None = None,
*,
prompt_token_id_logprobs: np.ndarray | None = None,
kv_transfer_params: dict[str, Any] | None = None,
ec_transfer_params: dict[str, Any] | None = None,
# Forward compatibility, code that uses args added in new release can
@@ -162,6 +167,7 @@ class RequestOutput:
self.prompt = prompt
self.prompt_token_ids = prompt_token_ids
self.prompt_logprobs = prompt_logprobs
self.prompt_token_id_logprobs = prompt_token_id_logprobs
self.outputs = outputs
self.finished = finished
self.metrics = metrics
@@ -215,6 +221,7 @@ class RequestOutput:
f"encoder_prompt={self.encoder_prompt!r}, "
f"encoder_prompt_token_ids={self.encoder_prompt_token_ids}, "
f"prompt_logprobs={self.prompt_logprobs}, "
f"prompt_token_id_logprobs={self.prompt_token_id_logprobs}, "
f"outputs={self.outputs}, "
f"finished={self.finished}, "
f"metrics={self.metrics}, "
+10 -1
View File
@@ -38,6 +38,7 @@ from vllm.entrypoints.openai.chat_completion.protocol import (
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.parser.engine.adapters import ParserEngineToolAdapter
from vllm.parser.metrics import record_tool_parser_invocation
from vllm.parser.utils import count_history_tool_calls
from vllm.reasoning.abs_reasoning_parsers import ReasoningParser
@@ -128,7 +129,15 @@ class Parser:
tokenizer, *args, model_config=model_config, **kwargs
)
if self.__class__.tool_parser_cls is not None:
self._tool_parser = self.__class__.tool_parser_cls(tokenizer, tools)
# Engine-based adapters take the same construction kwargs as
# the reasoning parser (e.g. chat_template_kwargs for per-request
# thinking toggles); legacy ToolParser classes take none.
if issubclass(self.__class__.tool_parser_cls, ParserEngineToolAdapter):
self._tool_parser = self.__class__.tool_parser_cls(
tokenizer, tools, model_config=model_config, **kwargs
)
else:
self._tool_parser = self.__class__.tool_parser_cls(tokenizer, tools)
self._engine_based = (
self._reasoning_parser is None
@@ -20,6 +20,7 @@ from vllm.parser.kimi_k2 import KimiK2Parser
from vllm.parser.minimax_m2 import MinimaxM2Parser
from vllm.parser.mistral import MistralParser
from vllm.parser.nemotron_v3 import NemotronV3Parser
from vllm.parser.plamo3 import Plamo3Parser
from vllm.parser.qwen3 import Qwen3Parser
from vllm.parser.seed_oss import SeedOssParser
@@ -92,3 +93,8 @@ from vllm.parser.seed_oss import SeedOssParser
MistralParserReasoningAdapter,
MistralParserToolAdapter,
) = make_adapters(MistralParser)
(
Plamo3ParserReasoningAdapter,
Plamo3ParserToolAdapter,
) = make_adapters(Plamo3Parser)
+318
View File
@@ -0,0 +1,318 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import functools
import json
from dataclasses import replace
from itertools import groupby
from typing import TYPE_CHECKING
from vllm.entrypoints.generate.base.protocol import (
DeltaFunctionCall,
DeltaMessage,
DeltaToolCall,
)
from vllm.parser.engine.events import EventType, SemanticEvent
from vllm.parser.engine.parser_engine import ParserEngine
from vllm.parser.engine.parser_engine_config import (
ParserEngineConfig,
ParserState,
Transition,
)
if TYPE_CHECKING:
from vllm.entrypoints.openai.chat_completion.protocol import (
ChatCompletionRequest,
)
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
from vllm.tokenizers import TokenizerLike
from vllm.tool_parsers.abstract_tool_parser import Tool
BEGIN_TOOL_REQUESTS = "<|plamo:begin_tool_requests:plamo|>"
END_TOOL_REQUESTS = "<|plamo:end_tool_requests:plamo|>"
BEGIN_TOOL_REQUEST = "<|plamo:begin_tool_request:plamo|>"
END_TOOL_REQUEST = "<|plamo:end_tool_request:plamo|>"
BEGIN_TOOL_NAME = "<|plamo:begin_tool_name:plamo|>"
END_TOOL_NAME = "<|plamo:end_tool_name:plamo|>"
BEGIN_TOOL_ARGUMENTS = (
"<|plamo:begin_tool_arguments:plamo|><|plamo:constrain|>json<|plamo:msg|>"
)
END_TOOL_ARGUMENTS = "<|plamo:end_tool_arguments:plamo|>"
BEGIN_THINK = "<|plamo:begin_think:plamo|>"
END_THINK = "<|plamo:end_think:plamo|>"
EOT = "<|plamo:tag|>"
# PLaMo3 control markers are split into multiple tokenizer tokens. These
# atomic pieces must not be treated as unrelated special tokens by the
# parser-engine drop-token handling.
PLAMO_MARKER_TOKENS = frozenset(
{
"<|plamo:begin_",
"<|plamo:end_",
":plamo|>",
}
)
@functools.cache
def plamo3_config(thinking: bool = True) -> ParserEngineConfig:
if thinking:
reasoning_terminals = {
"THINK_START": BEGIN_THINK,
"THINK_END": END_THINK,
}
reasoning_transitions = {
(ParserState.REASONING, "THINK_START"): Transition(
ParserState.REASONING,
),
(ParserState.CONTENT, "THINK_START"): Transition(
ParserState.REASONING,
(EventType.REASONING_START,),
),
(ParserState.REASONING, "THINK_END"): Transition(
ParserState.CONTENT,
(EventType.REASONING_END,),
),
(ParserState.CONTENT, "THINK_END"): Transition(
ParserState.CONTENT,
(),
),
(ParserState.REASONING, "TOOL_REQUESTS_START"): Transition(
ParserState.TOOL_PREAMBLE,
(EventType.REASONING_END,),
),
}
initial_state = ParserState.REASONING
else:
reasoning_terminals = {}
reasoning_transitions = {}
initial_state = ParserState.CONTENT
return ParserEngineConfig(
name="plamo3",
initial_state=initial_state,
terminals={
**reasoning_terminals,
"TOOL_REQUESTS_START": BEGIN_TOOL_REQUESTS,
"TOOL_REQUESTS_END": END_TOOL_REQUESTS,
"TOOL_REQUEST_START": BEGIN_TOOL_REQUEST,
"TOOL_REQUEST_END": END_TOOL_REQUEST,
"TOOL_NAME_START": BEGIN_TOOL_NAME,
"TOOL_NAME_END": END_TOOL_NAME,
"TOOL_ARGS_START": BEGIN_TOOL_ARGUMENTS,
"TOOL_ARGS_END": END_TOOL_ARGUMENTS,
"EOT": EOT,
},
transitions={
**reasoning_transitions,
(ParserState.CONTENT, "TOOL_REQUESTS_START"): Transition(
ParserState.TOOL_PREAMBLE,
),
(ParserState.TOOL_PREAMBLE, "TOOL_REQUEST_START"): Transition(
ParserState.TOOL_PREAMBLE,
),
(ParserState.TOOL_PREAMBLE, "TOOL_NAME_START"): Transition(
ParserState.TOOL_NAME,
(EventType.TOOL_CALL_START,),
),
(ParserState.TOOL_NAME, "TOOL_NAME_END"): Transition(
ParserState.TOOL_PREAMBLE,
),
(ParserState.TOOL_PREAMBLE, "TOOL_ARGS_START"): Transition(
ParserState.TOOL_ARGS,
),
(ParserState.TOOL_ARGS, "TOOL_ARGS_END"): Transition(
ParserState.TOOL_BETWEEN,
),
(ParserState.TOOL_BETWEEN, "TOOL_REQUEST_END"): Transition(
ParserState.TOOL_PREAMBLE,
(EventType.TOOL_CALL_END,),
),
(ParserState.TOOL_PREAMBLE, "TOOL_REQUESTS_END"): Transition(
ParserState.CONTENT,
),
# EOT is normally consumed by generation stop handling. Keep it
# in the grammar as well so text-only parsing and explicitly
# supplied stop tokens cannot leak it into user-visible output.
(ParserState.REASONING, "EOT"): Transition(
ParserState.CONTENT,
(EventType.REASONING_END,),
),
(ParserState.CONTENT, "EOT"): Transition(ParserState.CONTENT),
(ParserState.TOOL_PREAMBLE, "EOT"): Transition(ParserState.CONTENT),
(ParserState.TOOL_NAME, "EOT"): Transition(ParserState.CONTENT),
(ParserState.TOOL_ARGS, "EOT"): Transition(ParserState.CONTENT),
(ParserState.TOOL_BETWEEN, "EOT"): Transition(ParserState.CONTENT),
},
token_id_terminals={"EOT": EOT, **reasoning_terminals},
drop_whitespace_only_content_before_tools=True,
stream_arg_deltas=True,
strip_content_whitespace_with_tools=False,
strip_trailing_reasoning_whitespace=False,
preserve_tokens=PLAMO_MARKER_TOKENS,
tool_args_json=True,
)
class Plamo3Parser(ParserEngine):
"""PLaMo3 reasoning and tool-call parser backed by ParserEngine."""
def __init__(
self,
tokenizer: TokenizerLike,
tools: list[Tool] | None = None,
**kwargs,
) -> None:
# Configure PLaMo parsing and cache its multi-token reasoning markers.
chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {}
self.thinking_enabled = chat_kwargs.get("enable_thinking", True)
kwargs.setdefault(
"parser_engine_config",
plamo3_config(thinking=self.thinking_enabled),
)
super().__init__(tokenizer, tools, **kwargs)
self._reasoning_start_token_id_sequence: list[int] = list(
tokenizer.encode(BEGIN_THINK, add_special_tokens=False)
)
self._reasoning_end_token_id_sequence: list[int] = list(
tokenizer.encode(END_THINK, add_special_tokens=False)
)
# Token-ID sequences of every terminal literal, for token-level
# unfinished-marker detection.
self._terminal_token_id_sequences: dict[str, tuple[int, ...]] = {
literal: tuple(tokenizer.encode(literal, add_special_tokens=False))
for literal in self.parser_engine_config.terminal_literals
}
def is_reasoning_end(self, input_ids: list[int]) -> bool:
# Detect PLaMo reasoning boundaries that span multiple token IDs.
if not self.thinking_enabled:
return True
start_ids = self._reasoning_start_token_id_sequence
end_ids = self._reasoning_end_token_id_sequence
for i in range(len(input_ids) - 1, -1, -1):
if input_ids[i : i + len(end_ids)] == end_ids:
return True
if input_ids[i : i + len(start_ids)] == start_ids:
return False
if input_ids[i] == self.vocab.get(EOT):
return False
return False
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
# Extract content after PLaMo's multi-token reasoning end marker.
if not self.thinking_enabled:
return input_ids
end_ids = self._reasoning_end_token_id_sequence
for i in range(len(input_ids) - len(end_ids), -1, -1):
if input_ids[i : i + len(end_ids)] == end_ids:
return input_ids[i + len(end_ids) :]
return input_ids
def _strip_unfinished_marker(self, value: str | None) -> str | None:
if not value:
return value
marker_start = value.rfind("<|plamo:")
if marker_start < 0:
return value or None
suffix = value[marker_start:]
# Strip a trailing partial marker at the token-ID level.
suffix_ids = tuple(
self.model_tokenizer.encode(suffix, add_special_tokens=False)
)
if any(
len(seq) > len(suffix_ids) and seq[: len(suffix_ids)] == suffix_ids
for seq in self._terminal_token_id_sequences.values()
):
return value[:marker_start] or None
return value or None
def _coalesce_finished_tool_events(
self, events: list[SemanticEvent]
) -> list[SemanticEvent]:
combined = []
for (kind, _), group in groupby(
events, key=lambda event: (event.type, event.tool_index)
):
chunks = list(group)
if kind not in (EventType.TOOL_NAME, EventType.ARG_VALUE_CHUNK):
combined.extend(chunks)
continue
if kind == EventType.TOOL_NAME and chunks[0].tool_index < 0:
continue
value = "".join(chunk.value for chunk in chunks)
if kind == EventType.TOOL_NAME:
value = self._strip_unfinished_marker(value) or ""
if value:
combined.append(replace(chunks[0], value=value))
return combined
def _events_to_delta(
self,
events: list[SemanticEvent],
finished: bool = False,
) -> DeltaMessage | None:
# Coalesce flushed tool fragments before stripping truncated markers.
if not finished:
return super()._events_to_delta(events)
events = self._coalesce_finished_tool_events(events)
delta = super()._events_to_delta(events, finished=True)
if delta is None:
return None
delta.reasoning = self._strip_unfinished_marker(delta.reasoning)
if not self.skip_tool_parsing:
delta.content = self._strip_unfinished_marker(delta.content)
# The flush emits the remaining (never-streamed) tool-call
# arguments; an empty remainder must match non-streaming
# extraction (_extract_args_json), which normalizes it to '{}'.
for tc in delta.tool_calls or []:
if tc.function is not None and not (tc.function.arguments or "").strip():
tc.function.arguments = "{}"
if delta.reasoning is None and delta.content is None and not delta.tool_calls:
return None
return delta
def _handle_arg_chunk(
self,
event: SemanticEvent,
deltas: list[DeltaToolCall],
) -> None:
# Strip truncated marker suffixes and preserve the first argument delta.
idx = event.tool_index
slot = self._tool_slots[idx]
if (marker_pos := event.value.rfind("<|plamo:")) >= 0:
stripped = event.value[:marker_pos]
try:
json.loads(slot.args + stripped)
except ValueError:
pass
else:
event = replace(event, value=stripped)
name_sent_before = slot.name_sent
super()._handle_arg_chunk(event, deltas)
if event.value and not name_sent_before and slot.name_sent:
deltas.append(
DeltaToolCall(
index=idx,
function=DeltaFunctionCall(arguments=event.value),
)
)
def _extract_args_json(self, raw_args: str, func_name: str) -> str:
# Return the raw arguments as JSON
# since PLaMo3 generates function names and arguments separately.
return raw_args.strip() or "{}"
def extract_reasoning(
self,
model_output: str,
request: ChatCompletionRequest | ResponsesRequest,
) -> tuple[str | None, str | None]:
reasoning, content = super().extract_reasoning(model_output, request)
return self._strip_unfinished_marker(reasoning), content
+10
View File
@@ -1120,6 +1120,16 @@ class Platform:
"""
return False
@classmethod
def enable_multi_stream_overlap(
cls,
aux_stream_list: list[torch.cuda.Stream] | None,
attn_metadata: object,
) -> bool:
"""Whether the current platform should enable multi-stream overlap
for the given aux streams and attention metadata."""
return False
@classmethod
def supports_mx(cls) -> bool:
"""Returns whether the current platform supports MX types."""
+21
View File
@@ -1106,6 +1106,27 @@ class RocmPlatform(Platform):
def is_navi(cls) -> bool:
return "gfx1" in _GCN_ARCH
@classmethod
def enable_multi_stream_overlap(
cls,
aux_stream_list: list[torch.cuda.Stream] | None,
attn_metadata: object,
) -> bool:
"""ROCm multi-stream gates: streams and capture region.
Dict metadata marks piecewise cudagraph, whose eager breaks rebuild
the attention inputs on the owning stream. Forking side streams
there would rely on runtime HIP event sync, which is unreliable in
this overlap on ROCm (event waits can hang), so multi-stream only
runs where the fork/join becomes static graph edges: inside capture,
or with non-dict metadata (full cudagraph or the profile run), which
has no eager breaks.
"""
return aux_stream_list is not None and (
torch.cuda.is_current_stream_capturing()
or not isinstance(attn_metadata, dict)
)
@classmethod
def get_static_graph_wrapper_cls(cls) -> str:
return "vllm.compilation.cuda_graph.CUDAGraphWrapper"
+7 -4
View File
@@ -464,13 +464,16 @@ class XPUPlatform(Platform):
)
cache_config.block_size = new_block_size
logger.info(
"[XPU]Setting attention block size to %d tokens to ensure multiple of %d, "
"set mamba_page_size_padded to %d bytes accordingly, before was %d bytes.",
"[XPU]Setting attention block size to %d tokens to ensure multiple of %d.",
new_block_size,
kernel_block_size,
cache_config.mamba_page_size_padded,
original_mamba_page_size_padded,
)
if original_mamba_page_size_padded is not None:
logger.info(
"[XPU]Scaled mamba_page_size_padded from %d to %d bytes accordingly.",
original_mamba_page_size_padded,
cache_config.mamba_page_size_padded,
)
@classmethod
def support_hybrid_kv_cache(cls) -> bool:
+4
View File
@@ -136,6 +136,10 @@ _REASONING_PARSERS_TO_REGISTER = {
"olmo3_reasoning_parser",
"Olmo3ReasoningParser",
),
"plamo3": (
"plamo3_engine_reasoning_parser",
"Plamo3ParserReasoningAdapter",
),
"muse_glimmer": (
"muse_glimmer_reasoning_parser",
"MuseGlimmerReasoningParser",
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import Plamo3ParserReasoningAdapter
__all__ = ["Plamo3ParserReasoningAdapter"]
+6 -2
View File
@@ -277,8 +277,12 @@ def resolve_chat_template(
if tools is None:
chat_template = _try_get_processor_chat_template(
tokenizer,
revision=model_config.revision,
code_revision=model_config.code_revision,
revision=model_config.tokenizer_revision,
code_revision=(
model_config.code_revision
if model_config.tokenizer == model_config.model
else None
),
trust_remote_code=model_config.trust_remote_code,
)
if chat_template is not None:
+25 -1
View File
@@ -107,11 +107,35 @@ def _reused_prompt_token_ids(request: Any) -> list[int] | None:
Disaggregated serving carries the prefill stage's ids in
``kv_transfer_params`` so the decode stage can skip re-tokenizing. Removing
the key keeps the id list out of the engine's sampling metadata.
Returns None without checking the ids when ``echo`` is set, since echo
needs ``messages`` to be rendered. Otherwise raises VLLMValidationError if
the ids are malformed.
"""
kv = getattr(request, "kv_transfer_params", None)
if not isinstance(kv, dict):
return None
return kv.pop("prompt_token_ids", None) or None
ids = kv.pop("prompt_token_ids", None)
if ids is None:
return None
if getattr(request, "echo", False):
logger.debug(
"Ignoring kv_transfer_params['prompt_token_ids']: "
"echo is set, so messages are rendered instead."
)
return None
# bool is an int subclass, hence the exact type check.
if (
not isinstance(ids, list)
or not ids
or any(type(x) is not int or x < 0 for x in ids)
):
raise VLLMValidationError(
"`kv_transfer_params['prompt_token_ids']` must be a non-empty list "
"of non-negative integers.",
parameter="kv_transfer_params.prompt_token_ids",
)
return ids
class OnlineRenderer:
+68 -1
View File
@@ -289,6 +289,12 @@ class SamplingParams(
prompt_logprobs: int | None = None
"""Number of log probabilities to return per prompt token.
When set to -1, return all `vocab_size` log probabilities."""
prompt_logprob_token_ids: list[int] | None = None
"""Token IDs to score at each scored causal prompt row, where row i scores
them as predictions of prompt token i + 1. The last prompt row is excluded,
so the result has `max(prompt_len - 1 - prompt_logprob_start, 0)` rows."""
prompt_logprob_start: int | None = None
"""First causal prompt row to score; defaults to the first row."""
logprob_token_ids: list[int] | None = None
"""Specific token IDs to return logprobs for. More efficient than
logprobs=-1 when you only need logprobs for a small set of tokens.
@@ -398,6 +404,8 @@ class SamplingParams(
min_tokens: int = 0,
logprobs: int | None = None,
prompt_logprobs: int | None = None,
prompt_logprob_token_ids: list[int] | None = None,
prompt_logprob_start: int | None = None,
detokenize: bool = True,
skip_special_tokens: bool = True,
spaces_between_special_tokens: bool = True,
@@ -464,6 +472,8 @@ class SamplingParams(
min_tokens=min_tokens,
logprobs=logprobs,
prompt_logprobs=prompt_logprobs,
prompt_logprob_token_ids=prompt_logprob_token_ids,
prompt_logprob_start=prompt_logprob_start,
logprob_token_ids=logprob_token_ids,
detokenize=detokenize,
skip_special_tokens=skip_special_tokens,
@@ -550,7 +560,10 @@ class SamplingParams(
# If prefix caching is enabled,
# the output of prompt logprobs may less than n_prompt_tokens,
# we need to skip reading cache at this request.
self.skip_reading_prefix_cache = self.prompt_logprobs is not None
self.skip_reading_prefix_cache = (
self.prompt_logprobs is not None
or self.prompt_logprob_token_ids is not None
)
def _verify_args(self) -> None:
_verify_num_sequences(self.n, "n")
@@ -902,6 +915,56 @@ class SamplingParams(
value=num_prompt_logprobs,
)
# Validate prompt_logprob_token_ids.
if self.prompt_logprob_token_ids is not None:
n = len(self.prompt_logprob_token_ids)
if n == 0:
raise VLLMValidationError(
"prompt_logprob_token_ids must not be empty.",
parameter="prompt_logprob_token_ids",
value=n,
)
if n > max_logprobs:
raise VLLMValidationError(
f"Requested prompt_logprob_token_ids of length {n}, "
f"which is greater than max allowed: {max_logprobs}. "
f"Set max_logprobs (--max-logprobs) to at least {n}.",
parameter="prompt_logprob_token_ids",
value=n,
)
vocab_size = model_config.get_vocab_size()
invalid_token_ids = [
token_id
for token_id in self.prompt_logprob_token_ids
if token_id < 0 or token_id >= vocab_size
]
if invalid_token_ids:
raise VLLMValidationError(
f"token_id(s) {invalid_token_ids} in "
f"prompt_logprob_token_ids contain out-of-vocab token ids. "
f"Vocabulary size: {vocab_size}",
parameter="prompt_logprob_token_ids",
value=invalid_token_ids,
)
if len(set(self.prompt_logprob_token_ids)) != n:
raise VLLMValidationError(
"prompt_logprob_token_ids must not contain duplicates.",
parameter="prompt_logprob_token_ids",
value=self.prompt_logprob_token_ids,
)
if self.prompt_logprob_start is not None and self.prompt_logprob_start < 0:
raise VLLMValidationError(
"prompt_logprob_start must be non-negative.",
parameter="prompt_logprob_start",
value=self.prompt_logprob_start,
)
elif self.prompt_logprob_start is not None:
raise VLLMValidationError(
"prompt_logprob_start requires prompt_logprob_token_ids.",
parameter="prompt_logprob_start",
value=self.prompt_logprob_start,
)
def _validate_stop_token_ids(self, model_config: ModelConfig) -> None:
"""Validate stop_token_ids are within vocabulary range."""
if not self.stop_token_ids:
@@ -969,6 +1032,10 @@ class SamplingParams(
raise ValueError(
"trace_decode_token_ids is not supported with prompt_logprobs."
)
if self.prompt_logprob_token_ids is not None:
raise ValueError(
"trace_decode_token_ids is not supported with prompt_logprob_token_ids."
)
if speculative_config is not None:
raise ValueError(
"trace_decode_token_ids is not supported with speculative decoding."
+4
View File
@@ -166,6 +166,10 @@ _TOOL_PARSERS_TO_REGISTER = {
"olmo3_tool_parser",
"Olmo3PythonicToolParser",
),
"plamo3": (
"plamo3_engine_tool_parser",
"Plamo3EngineToolParser",
),
"muse_glimmer": (
"muse_glimmer_tool_parser",
"MuseGlimmerToolParser",
@@ -0,0 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.parser.engine.registered_adapters import Plamo3ParserToolAdapter
class Plamo3EngineToolParser(Plamo3ParserToolAdapter): # type: ignore[valid-type, misc]
structural_tag_model = "plamo3"
supports_required_and_named = False
+65 -1
View File
@@ -73,7 +73,7 @@ XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset(
"deepseek_v4_1",
}
)
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset({"hermes", "hy_v4", "kimi_k3"})
VLLM_BUILTIN_STRUCTURAL_TAG_MODELS = frozenset({"hermes", "hy_v4", "kimi_k3", "plamo3"})
SUPPORTED_STRUCTURAL_TAG_MODELS = (
XGRAMMAR_BUILTIN_STRUCTURAL_TAG_MODELS | VLLM_BUILTIN_STRUCTURAL_TAG_MODELS
)
@@ -407,6 +407,70 @@ def get_minimax_structural_tag(
return StructuralTag(format=suffix_tag)
_PLAMO3_BEGIN_TOOL_REQUESTS = "<|plamo:begin_tool_requests:plamo|>"
_PLAMO3_END_TOOL_REQUESTS = "<|plamo:end_tool_requests:plamo|>"
_PLAMO3_BEGIN_TOOL_REQUEST = "<|plamo:begin_tool_request:plamo|>"
_PLAMO3_END_TOOL_REQUEST = "<|plamo:end_tool_request:plamo|>"
_PLAMO3_BEGIN_TOOL_NAME = "<|plamo:begin_tool_name:plamo|>"
_PLAMO3_END_TOOL_NAME = "<|plamo:end_tool_name:plamo|>"
_PLAMO3_BEGIN_TOOL_ARGUMENTS = (
"<|plamo:begin_tool_arguments:plamo|><|plamo:constrain|>json<|plamo:msg|>"
)
_PLAMO3_END_TOOL_ARGUMENTS = "<|plamo:end_tool_arguments:plamo|>"
_PLAMO3_EOT = "<|plamo:tag|>"
@register_vllm_structural_tag("plamo3")
def get_plamo3_structural_tag(
tools: list[FunctionToolParam],
builtin_tools: list[BuiltinToolParam],
tool_choice: SimplifiedToolChoice,
reasoning: bool,
token_suffix: str = "",
) -> StructuralTag:
"""Build PLaMo3's explicit tool-request structural tag."""
del builtin_tools, reasoning, token_suffix
request_tags = [
TagFormat(
begin=(
_PLAMO3_BEGIN_TOOL_REQUEST
+ _PLAMO3_BEGIN_TOOL_NAME
+ tool.function.name
+ _PLAMO3_END_TOOL_NAME
+ _PLAMO3_BEGIN_TOOL_ARGUMENTS
),
content=JSONSchemaFormat(
json_schema=get_function_parameters(tool.function)
),
end=_PLAMO3_END_TOOL_ARGUMENTS + _PLAMO3_END_TOOL_REQUEST,
)
for tool in tools
]
requests_tag = TagFormat(
begin=_PLAMO3_BEGIN_TOOL_REQUESTS,
content=TagsWithSeparatorFormat(
tags=request_tags,
separator="",
at_least_one=True,
stop_after_first=tool_choice == "forced",
),
end=[
_PLAMO3_END_TOOL_REQUESTS,
_PLAMO3_END_TOOL_REQUESTS + _PLAMO3_EOT,
],
)
if tool_choice == "auto":
return StructuralTag(
format=TriggeredTagsFormat(
triggers=[_PLAMO3_BEGIN_TOOL_REQUESTS],
tags=[requests_tag],
)
)
return StructuralTag(format=requests_tag)
# ---------------------------------------------------------------------------
# Kimi K3 (XTML channel format)
# ---------------------------------------------------------------------------
+26 -6
View File
@@ -79,6 +79,23 @@ FLASHINFER_CUBINS_REPOSITORY = os.environ.get(
"https://edge.urm.nvidia.com/artifactory/sw-kernelinferencelibrary-public-generic-local/", # noqa: E501
)
_DEFAULT_CUDA_HOME = "/usr/local/cuda"
def _flashinfer_nvcc_path() -> str | None:
"""Return the nvcc FlashInfer's JIT would run, or None if it is missing.
Mirrors ``flashinfer.jit.cpp_ext.get_cuda_path()`` without importing
FlashInfer, whose import initializes CUDA.
"""
cuda_home = os.environ.get("CUDA_HOME") or os.environ.get("CUDA_PATH")
if not cuda_home:
nvcc = shutil.which("nvcc")
cuda_home = (
os.path.dirname(os.path.dirname(nvcc)) if nvcc else _DEFAULT_CUDA_HOME
)
return shutil.which(os.path.join(cuda_home, "bin", "nvcc"))
@functools.cache
def has_flashinfer_cubin() -> bool:
@@ -99,12 +116,15 @@ def has_flashinfer() -> bool:
if importlib.util.find_spec("flashinfer") is None:
logger.debug_once("FlashInfer unavailable since package was not found")
return False
# When not using flashinfer cubin,
# Also check if nvcc is available since it's required to JIT compile flashinfer
if not has_flashinfer_cubin() and shutil.which("nvcc") is None:
logger.debug_once(
"FlashInfer unavailable since nvcc was not found "
"and not using pre-downloaded cubins"
# FlashInfer's JIT runs nvcc and `ninja` (from PATH).
if not has_flashinfer_cubin() and (
_flashinfer_nvcc_path() is None or shutil.which("ninja") is None
):
logger.warning_once(
"FlashInfer kernels are disabled: flashinfer-cubin is not installed "
"and nvcc (CUDA_HOME, CUDA_PATH, PATH or /usr/local/cuda) or ninja "
"(PATH) is missing. Set CUDA_HOME to a CUDA toolkit and put ninja on "
"PATH, or run `flashinfer download-kernels`."
)
return False
return True
+9 -4
View File
@@ -912,10 +912,15 @@ def get_accelerator_view_from_cpu_tensor(cpu_tensor: torch.Tensor) -> torch.Tens
if cpu_tensor.numel() == 0:
return torch.empty(cpu_tensor.shape, dtype=cpu_tensor.dtype, device="xpu")
if not cpu_tensor.is_pinned():
contiguous_cpu = cpu_tensor.contiguous()
pinned = torch.empty_like(contiguous_cpu, pin_memory=True)
pinned.copy_(contiguous_cpu)
cpu_tensor = pinned
pinned = torch.empty_strided(
cpu_tensor.size(),
cpu_tensor.stride(),
dtype=cpu_tensor.dtype,
device="cpu",
pin_memory=True,
)
pinned.copy_(cpu_tensor)
return torch.ops._C.get_xpu_view_from_cpu_tensor(pinned)
return torch.ops._C.get_xpu_view_from_cpu_tensor(cpu_tensor)
elif current_platform.is_cuda_alike():
return torch.ops._C.get_cuda_view_from_cpu_tensor(cpu_tensor)
+3
View File
@@ -54,6 +54,9 @@ class MultipleOf:
def __init__(self, base: int):
self.base = base
def __repr__(self) -> str:
return f"MultipleOf({self.base})"
class AttentionBackend(ABC):
"""Abstract class for attention backends."""
+11 -9
View File
@@ -97,6 +97,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
# Will be disabled if speculative decoding is used
supports_update_block_table: bool = True
needs_causal_conv1d_metadata: bool = True
def __init__(
self,
@@ -603,10 +604,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
if num_computed_tokens is None:
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
query_start_loc_p_cpu = (
common_attn_metadata.query_start_loc_cpu[-num_prefills - 1 :]
- num_decode_tokens
)
query_start_loc_p = (
common_attn_metadata.query_start_loc[-num_prefills - 1 :]
- num_decode_tokens
@@ -615,12 +612,17 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
num_computed_tokens[num_reqs - num_prefills : num_reqs] > 0
)
nums_dict, batch_ptr, token_chunk_offset_ptr = (
compute_causal_conv1d_metadata(
query_start_loc_p_cpu,
device=common_attn_metadata.query_start_loc.device,
if self.needs_causal_conv1d_metadata:
query_start_loc_p_cpu = (
common_attn_metadata.query_start_loc_cpu[-num_prefills - 1 :]
- num_decode_tokens
)
nums_dict, batch_ptr, token_chunk_offset_ptr = (
compute_causal_conv1d_metadata(
query_start_loc_p_cpu,
device=common_attn_metadata.query_start_loc.device,
)
)
)
if self.vllm_config.cache_config.mamba_cache_mode == "all":
assert num_computed_tokens is not None
+258 -23
View File
@@ -3,11 +3,13 @@
import functools
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, Final
import torch
from vllm import envs
from vllm._aiter_ops import rocm_aiter_ops
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
@@ -239,6 +241,78 @@ def _segmented_dcp_verify_supported(dcp_world_size: int, cp_interleave: int) ->
)
# DCP decode routing
#
# With decode context parallelism each rank holds a round-robin shard of the KV
# cache (token t on rank t % dcp_world_size; requires interleave size 1) and
# attends over it with all DCP-gathered query heads. Partial outputs are merged
# across ranks by LSE. Each decode batch takes one route:
#
# * plain: qlen == 1 or a non-causal block. Every query sees every local token.
# * cprr: causal qlen >= _MIN_CPRR_QLEN, gfx950, speculative decoding. AITER's
# round-robin ASM decode rebuilds global positions from g_kv_indptr, cp_rank
# and cp_world_size and applies the causal window in-kernel. Kernels exist only
# at _NATIVE_CPRR_HEADS; other gathered head counts are padded up.
# * segmented: causal qlen > 1 when cprr is not selected or qlen is below
# _MIN_CPRR_QLEN. Each verify token becomes a single-query row whose KV length
# encodes its causal window.
#
# The plain kernel must never serve a causal qlen > 1 block: it applies
# causality on local indices, which is wrong over a round-robin shard.
_NATIVE_CPRR_HEADS: Final = (16, 32, 64, 128)
_MIN_CPRR_QLEN: Final = 3
class _DCPDecodeRoute(Enum):
PLAIN = "plain"
SEGMENTED = "segmented"
CPRR = "cprr"
def _asm_dcp_verify_heads(decode_num_heads: int) -> int:
"""Head count the cprr asm decode runs at, or 0 if it cannot serve this shape."""
if decode_num_heads in _NATIVE_CPRR_HEADS:
return decode_num_heads
for nat in _NATIVE_CPRR_HEADS:
if nat >= decode_num_heads:
return nat
return 0
def _select_dcp_decode_route(
supports_segmented: bool,
causal: bool,
max_qo_len: int,
asm_selected: bool,
) -> _DCPDecodeRoute:
"""Select one DCP decode route for this batch; see DCP decode routing."""
if not causal or max_qo_len <= 1:
return _DCPDecodeRoute.PLAIN
if asm_selected and max_qo_len >= _MIN_CPRR_QLEN:
return _DCPDecodeRoute.CPRR
if supports_segmented:
return _DCPDecodeRoute.SEGMENTED
raise RuntimeError(
"ROCM_AITER_MLA DCP multi-token verify requires either segmented "
"MLA or the round-robin asm decode."
)
def _asm_dcp_verify_configured(
dcp_world_size: int, cp_interleave: int, multi_token_decode: bool
) -> bool:
"""Whether asm cprr DCP verify is reachable in this process.
Requires DCP with interleave size 1, speculative decoding, and gfx950 (the
only arch AITER builds cprr kernels for).
"""
if not (dcp_world_size > 1 and cp_interleave == 1 and multi_token_decode):
return False
from vllm.platforms.rocm import on_gfx950
return bool(on_gfx950())
def _aiter_mla_small_head_mode() -> str:
"""Small-head (<16) MLA decode kernel selection.
@@ -410,8 +484,19 @@ class AiterMLADecodeMetadata(MLACommonDecodeMetadata):
max_qo_len: int | None = None
# Minimum KV length used by Gluon to choose a safe split count.
min_kv_seq_len: int = 1
# Exactly one DCP decode route is selected by the metadata builder.
dcp_route: _DCPDecodeRoute = _DCPDecodeRoute.PLAIN
# Set exactly when this batch routes to segmented DCP verification.
dcp_verify: AiterMLADCPVerifyMetadata | None = None
# cprr only: global per-request page indptr and this rank's position.
g_kv_indptr: torch.Tensor | None = None
cp_world_size: int = 1
cp_rank: int = 0
# Padded head count cprr runs at; 0 when this batch is not on cprr.
asm_decode_num_heads: int = 0
# Must equal the split cap the reduce scratch was sized with, or the kernel
# writes past it and faults.
mla_num_kv_splits: int = 0
# Small-head decode uses Gluon (avoids padding to 16).
use_gluon_decode: bool = False
# Small-head non-DCP multi-token verify uses Gluon's native MTP entry.
@@ -460,6 +545,9 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
# Set from the common metadata every build; a batch is causal unless the
# drafter says otherwise.
_decode_causal: bool = True
# A non-causal draft needs no cross-shard causal window: the ordinary
# mask0 decode returns per-row LSE for the DCP merge.
supports_non_causal_multi_token_dcp: ClassVar[bool] = True
@staticmethod
def _uniform_padded_mtp_qo_len(
@@ -513,15 +601,48 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
parallel_config.decode_context_parallel_size,
parallel_config.cp_kv_cache_interleave_size,
)
asm_dcp_verify_config = (
_asm_dcp_verify_configured(
parallel_config.decode_context_parallel_size,
parallel_config.cp_kv_cache_interleave_size,
multi_token_decode=vllm_config.speculative_config is not None,
)
and envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY == "asm"
)
super().__init__(
kv_cache_spec,
layer_names,
vllm_config,
device,
AiterMLAMetadata,
supports_dcp_with_varlen=supports_segmented_dcp_verify,
supports_dcp_with_varlen=(
supports_segmented_dcp_verify or asm_dcp_verify_config
),
)
self._asm_dcp_verify = False
self._asm_dcp_verify_heads = 0
# The head-count half of the route decision needs self.num_heads, so only
# the config half is known before super().__init__().
if asm_dcp_verify_config:
self._asm_dcp_verify_heads = _asm_dcp_verify_heads(
self.num_heads * self.dcp_world_size
)
if not self._asm_dcp_verify_heads:
raise ValueError(
"VLLM_ROCM_AITER_MLA_DCP_VERIFY=asm, but the round-robin asm "
f"decode has no kernel for {self.num_heads * self.dcp_world_size} "
f"DCP-gathered heads (native counts: {_NATIVE_CPRR_HEADS}). "
"Set VLLM_ROCM_AITER_MLA_DCP_VERIFY=segmented."
)
self._asm_dcp_verify = True
self._supports_segmented_dcp_verify = supports_segmented_dcp_verify
self._mla_max_split_per_batch = 0
if self._asm_dcp_verify:
# Cap on KV splits per batch; at low batch the KV axis is the only
# parallelism. Buffer sizing and every runtime call must see this value.
self._mla_max_split_per_batch = torch.cuda.get_device_properties(
device
).multi_processor_count
self.compilation_config = vllm_config.compilation_config
self.decode_attn_out_dtype = vllm_config.model_config.dtype
@@ -576,6 +697,12 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
self._num_attention_heads = AiterMLAHelper.get_actual_mla_num_heads(
self._decode_num_heads
)
# the cprr kernel exists only at the native head
# counts, so run (and size the persistent schedule) at the padded count.
# 96 is 16-aligned, so get_actual_mla_num_heads leaves it alone and the
# pad has to be applied here explicitly.
if self._asm_dcp_verify:
self._num_attention_heads = self._asm_dcp_verify_heads
kv_cache_dtype_str = getattr(vllm_config.cache_config, "cache_dtype", "auto")
if kv_cache_dtype_str in ("fp8", "fp8_e4m3", "fp8_e5m2"):
kv_cache_dtype_str = "fp8"
@@ -619,6 +746,13 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
kv_dtype,
is_sparse=False,
fast_mode=True,
# Must match max_split_per_batch in get_mla_metadata_v1; without it
# aiter sizes the reduce scratch from capacity (~9 GiB).
**(
dict(max_split_per_batch=self._mla_max_split_per_batch)
if self._asm_dcp_verify
else {}
),
)
self._mla_work_meta_data = torch.empty(
work_meta_data_size, dtype=work_meta_data_type, device=device
@@ -664,6 +798,14 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
device,
)
# Full cudagraphs need a stable address for the cprr global page indptr.
# Zero-initialized; element 0 is the indptr base and is never rewritten.
self._g_kv_indptr_buf: torch.Tensor | None = None
if self._asm_dcp_verify:
self._g_kv_indptr_buf = torch.zeros(
max_num_reqs + 1, dtype=torch.int32, device=device
)
# Persistent buffers for segmented DCP verification. Captured graphs
# require stable addresses while row lengths vary between replays.
self._dcp_verify_buffers: AiterMLADCPVerifyMetadata | None = None
@@ -683,8 +825,11 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
)
if self._supports_segmented_dcp_verify and self._mtp_decode_qlen > 1:
# A DCP rank's shard of the longest sequence bounds every verify
# row, and full graphs need that bound to be constant.
# Allocate even when CPRR is the preferred route: a later
# replay can fall below _MIN_CPRR_QLEN and needs these
# addresses. A DCP rank's shard of the longest sequence
# bounds every verify row, and full graphs need that bound
# to be constant.
num_dcp_partitions = (
self.dcp_world_size * self.cp_kv_cache_interleave_size
)
@@ -1063,6 +1208,12 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
pad_uniform_mtp = padded_mtp_qo_len > 0
seq_lens_for_kernel = seq_lens_device
# the global lengths need the same dummy-row
# treatment as the local ones below, but only for g_kv_indptr -- the
# metadata field keeps the true values, which is what the segmented
# route wants (it derives its own row lens and gives a dummy row
# length 0, correctly).
g_tot_seq_lens = dcp_tot_seq_lens_device
num_kernel_reqs = num_reqs
if pad_uniform_mtp:
qo_lens_device = (
@@ -1074,6 +1225,19 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
seq_lens_for_kernel,
seq_lens_for_kernel.new_full((), max_qo_len),
)
# A dummy row just got a LOCAL length of max_qo_len, so its GLOBAL
# length has to say the same thing or the cprr mask is degenerate:
# global_len 0 puts the row query positions at {-3,-2,-1} while its
# local shard sits at {rank, W+rank, 2W+rank}, so every entry is
# masked and the row softmaxes over nothing. max_qo_len * W is
# exactly the global length whose round-robin shard is max_qo_len
# on every rank.
if g_tot_seq_lens is not None:
g_tot_seq_lens = torch.where(
qo_lens_device > 0,
g_tot_seq_lens,
g_tot_seq_lens.new_full((), max_qo_len * self.dcp_world_size),
)
if self._graph_seq_lens is not None:
self._graph_seq_lens[:num_kernel_reqs].copy_(
@@ -1106,16 +1270,21 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
causal,
self._kv_cache_bytes,
)
use_segmented_dcp_verify = (
self._supports_segmented_dcp_verify and max_qo_len > 1
)
dcp_route = _DCPDecodeRoute.PLAIN
if self.dcp_world_size > 1:
dcp_route = _select_dcp_decode_route(
self._supports_segmented_dcp_verify,
causal,
int(max_qo_len),
self._asm_dcp_verify,
)
# Segmented DCP verify carries its own per-row subpage table, so the
# flat per-token view is dead work for it. Leave the buffer alone and
# hand the metadata None, so a future reader cannot pick up whatever
# the previous batch left behind.
paged_kv_indices = None
if not use_segmented_dcp_verify:
if dcp_route is not _DCPDecodeRoute.SEGMENTED:
if self.compilation_config.cudagraph_mode.has_full_cudagraphs():
self.paged_kv_indices.fill_(-1)
@@ -1169,6 +1338,19 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
else:
qo_indptr = query_start_loc_device[: 1 + num_kernel_reqs]
g_kv_indptr = None
if dcp_route is _DCPDecodeRoute.CPRR and g_tot_seq_lens is not None:
assert self._g_kv_indptr_buf is not None
_ngk = g_tot_seq_lens.shape[0]
g_kv_indptr = self._g_kv_indptr_buf[: _ngk + 1]
g_kv_indptr[1:].copy_(g_tot_seq_lens.cumsum(dim=0, dtype=torch.int32))
# A FULL cudagraph replays at its capture-time request count, so a
# smaller real batch leaves the tail holding the PREVIOUS step's
# cumsum. Flatten it the way paged_kv_indptr is flattened below, so
# padding rows read global_len == 0 and agree with their zero-length
# local shard instead of a stale global length.
self._g_kv_indptr_buf[_ngk + 1 :].fill_(g_kv_indptr[-1])
has_persistent_metadata = False
# Only the asm decode consumes the schedule, so gate on the routing
# rather than on num_heads >= 16, which denies it to a padded rank
@@ -1178,7 +1360,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
use_persistent_metadata = (
not use_gluon_decode
and not use_gluon_verify
and not use_segmented_dcp_verify
and dcp_route is not _DCPDecodeRoute.SEGMENTED
# A padded rank has no bf16 persistent kernel past qlen 4 where the
# gfx950 fold is absent; the non-persistent entry covers it. fp8
# keeps the schedule -- its fold rejects non-persistent outright.
@@ -1218,13 +1400,28 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
uni_qo_len = (
max_qo_len if pad_uniform_mtp or torch.all(qo_len == max_qo_len) else -1
)
cprr_kwargs: dict = {}
is_causal = causal
if self._asm_dcp_verify:
cprr_kwargs = dict(
max_split_per_batch=self._mla_max_split_per_batch,
intra_batch_mode=False,
)
if dcp_route is _DCPDecodeRoute.CPRR:
is_causal = False
cprr_kwargs["is_cp_round_robin"] = True
metadata_num_heads = (
self._asm_dcp_verify_heads
if dcp_route is _DCPDecodeRoute.CPRR
else AiterMLAHelper.get_actual_mla_num_heads(self._decode_num_heads)
)
get_mla_metadata_v1(
qo_indptr,
paged_kv_indptr,
paged_kv_last_page_len,
self._num_attention_heads,
metadata_num_heads,
1,
causal,
is_causal,
self._mla_work_meta_data,
self._mla_work_info_set,
self._mla_work_indptr,
@@ -1238,6 +1435,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
fast_mode=True,
dtype_q=self._mla_q_dtype,
dtype_kv=self._mla_kv_dtype,
**cprr_kwargs,
)
has_persistent_metadata = True
@@ -1261,7 +1459,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
min_kv_seq_len = int(per_req_len.min().item())
dcp_verify = None
if use_segmented_dcp_verify:
if dcp_route is _DCPDecodeRoute.SEGMENTED:
assert dcp_tot_seq_lens_device is not None
dcp_verify = self._build_dcp_verify_row_view(
int(max_qo_len),
@@ -1279,7 +1477,19 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
dcp_tot_seq_lens=dcp_tot_seq_lens_device,
max_qo_len=max_qo_len,
min_kv_seq_len=min_kv_seq_len,
dcp_route=dcp_route,
dcp_verify=dcp_verify,
g_kv_indptr=g_kv_indptr,
cp_world_size=self.dcp_world_size,
cp_rank=self.dcp_rank,
asm_decode_num_heads=(
self._asm_dcp_verify_heads if dcp_route is _DCPDecodeRoute.CPRR else 0
),
mla_num_kv_splits=(
self._mla_max_split_per_batch
if dcp_route is _DCPDecodeRoute.CPRR
else 0
),
use_gluon_decode=use_gluon_decode,
use_gluon_verify=use_gluon_verify,
attn_out_dtype=self.decode_attn_out_dtype,
@@ -2062,8 +2272,10 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
)
return o, None
verify = decode.dcp_verify
if verify is not None:
dcp_route = decode.dcp_route
if dcp_route is _DCPDecodeRoute.SEGMENTED:
verify = decode.dcp_verify
assert verify is not None
if type(q) is tuple:
q_nope, q_pe = q
else:
@@ -2085,11 +2297,6 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
decode.attn_out_dtype,
)
if self.dcp_world_size > 1 and int(decode.max_qo_len) > 1:
raise RuntimeError(
"ROCM_AITER_MLA DCP multi-token verify requires segmented MLA."
)
if type(q) is tuple:
q = torch.cat(q, dim=-1)
@@ -2102,8 +2309,19 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
"ROCM_AITER_MLA decode expected the DCP-gathered query head count "
f"{self._decode_num_heads}, got {q.shape[1]}"
)
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self._decode_num_heads, q)
mla_num_heads = AiterMLAHelper.get_actual_mla_num_heads(self._decode_num_heads)
# cprr has kernels only at native head counts, so pad q up (e.g. 96 ->
# 128). Heads are independent in MLA; the extras are sliced off below.
asm_dcp_heads = decode.asm_decode_num_heads
if asm_dcp_heads > self._decode_num_heads:
mla_num_heads = asm_dcp_heads
mla_padded_q = AiterMLAHelper.get_mla_padded_q(
self._decode_num_heads, q, target_heads=mla_num_heads
)
else:
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self._decode_num_heads, q)
mla_num_heads = AiterMLAHelper.get_actual_mla_num_heads(
self._decode_num_heads
)
o = torch.empty(
B,
mla_num_heads,
@@ -2137,6 +2355,16 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
lse = None
if self.dcp_world_size > 1:
if dcp_route is _DCPDecodeRoute.CPRR:
# cprr only: global positions for the in-kernel causal window.
assert decode.g_kv_indptr is not None
mla_kwargs["g_kv_indptr"] = decode.g_kv_indptr
mla_kwargs["cp_world_size"] = decode.cp_world_size
mla_kwargs["cp_rank"] = decode.cp_rank
# Must match the schedule get_mla_metadata_v1 was built with.
assert decode.mla_num_kv_splits > 0
mla_kwargs["num_kv_splits"] = decode.mla_num_kv_splits
mla_kwargs["intra_batch_mode"] = False
# The vLLM custom-op wrapper exposes only the in-place output and
# drops aiter's final LSE, which the cross-shard merge needs, so go
# through aiter's native entry point on the DCP path.
@@ -2151,6 +2379,7 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
decode.max_qo_len,
sm_scale=self.scale,
return_lse=True,
causal=attn_metadata.causal,
**mla_kwargs,
)
assert lse is not None, (
@@ -2172,7 +2401,13 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
**mla_kwargs,
)
output = AiterMLAHelper.get_mla_unpadded_o(self._decode_num_heads, o)
if lse is not None:
lse = AiterMLAHelper.get_mla_unpadded_lse(self._decode_num_heads, lse)
if asm_dcp_heads > self._decode_num_heads:
# Keep a view: a post-kernel copy races the symm-mem a2a combine.
output = o[:, : self._decode_num_heads]
if lse is not None:
lse = lse[:, : self._decode_num_heads, ...]
else:
output = AiterMLAHelper.get_mla_unpadded_o(self._decode_num_heads, o)
if lse is not None:
lse = AiterMLAHelper.get_mla_unpadded_lse(self._decode_num_heads, lse)
return output, lse
@@ -396,9 +396,11 @@ class ROCMAiterMLASparseMetadataBuilder(
attention_context = vllm_config.compilation_config.static_forward_context
# Sink decode must use AITER's nonpersistent path. In particular,
# gfx942 has no persistent+LSE kernel, and its metadata heuristic
# terminates for HY-V4's TP1 H64 shape.
# terminates for HY-V4's TP1 H64 shape. The Triton sparse MLA kernel
# never reads the persistent metadata either.
self._use_persistent_metadata = all(
getattr(attention_context[name].impl, "sinks", None) is None
and not getattr(attention_context[name].impl, "use_aiter_sparse_mla", False)
for name in layer_names
)
# Bounds the KV-split heuristic (see `_sparse_decode_max_split`).
@@ -716,6 +718,7 @@ class ROCMAiterMLASparseImpl(
is_sparse = True
supports_dense_mha_prefill = False
supports_dcp = False
use_aiter_sparse_mla = False
def __init__(
self,
@@ -765,6 +768,32 @@ class ROCMAiterMLASparseImpl(
(self.q_concat_buffer,) = current_workspace_manager().get_simultaneous(
(q_concat_shape, vllm_config.model_config.dtype),
)
self.qk_rope_head_dim: int = mla_args["qk_rope_head_dim"]
if rocm_aiter_ops.is_triton_sparse_mla_enabled():
reason = self._aiter_sparse_mla_unsupported_reason(vllm_config)
if reason is None:
self.use_aiter_sparse_mla = True
else:
logger.warning_once(
"VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA is set, but %s; "
"using the default sparse MLA path instead.",
reason,
)
def _aiter_sparse_mla_unsupported_reason(
self, vllm_config: VllmConfig
) -> str | None:
model_dtype = vllm_config.model_config.dtype
if model_dtype != torch.bfloat16:
return f"the model dtype is {model_dtype}, not bfloat16"
cache_dtype = self.kv_cache_dtype
if cache_dtype not in ("auto", "bfloat16", "fp8", "fp8_e4m3"):
return f"kv-cache dtype {cache_dtype!r} is neither bfloat16 nor e4m3 fp8"
# Context parallelism merges each rank's partials with a per-token LSE.
if self.dcp_world_size > 1 or self.pcp_world_size > 1:
return "context parallelism is not supported"
return None
def record_logical_topk_ready(self) -> None:
# This impl shares the top-k indices buffer via SharedTopkIndicesBuffer
@@ -975,6 +1004,43 @@ class ROCMAiterMLASparseImpl(
return output, lse
def _forward_mla_aiter(
self,
layer: AttentionLayer,
q: torch.Tensor, # [sq, heads, d_qk], not head-padded
kv_c_and_k_pe_cache: torch.Tensor,
attn_metadata: ROCMAiterMLASparseMetadata,
) -> torch.Tensor:
"""_forward_mla on aiter's Triton sparse MLA kernel.
Reads the same index stream, but needs no q head padding and no
persistent metadata, and its launch depends on shapes only, so it is
CUDA-graph capturable.
"""
num_actual_tokens = attn_metadata.num_actual_tokens
output = torch.empty(
[q.shape[0], self.num_heads, self.kv_lora_rank],
dtype=attn_metadata.attn_out_dtype,
device=q.device,
)
rocm_aiter_ops.triton_sparse_mla_fwd(
q[:num_actual_tokens],
kv_c_and_k_pe_cache.view(-1, 1, 1, q.shape[-1]),
output[:num_actual_tokens],
self.scale,
attn_metadata.paged_kv_indptr,
attn_metadata.paged_kv_indices,
kv_lora_rank=self.kv_lora_rank,
qk_rope_head_dim=self.qk_rope_head_dim,
q_scale=layer._q_scale,
kv_scale=layer._k_scale,
attn_sink=self.sinks,
# triton_convert_req_index_to_global_index writes 0, never -1,
# for an invalid top-k entry, so no slot in the stream is negative.
has_invalid=False,
)
return output
def forward_mqa(
self,
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
@@ -1026,6 +1092,11 @@ class ROCMAiterMLASparseImpl(
original_q_shape = q.shape
q, _ = ops.scaled_fp8_quant(q.view(q.shape[0], -1), layer._q_scale)
q = q.view(original_q_shape)
if self.use_aiter_sparse_mla:
output = self._forward_mla_aiter(
layer, q, kv_c_and_k_pe_cache, attn_metadata
)
return output, None
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self.num_heads, q)
return self._forward_mla(
layer, mla_padded_q, kv_c_and_k_pe_cache, attn_metadata
@@ -83,7 +83,8 @@ class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
@classmethod
def supports_mm_prefix(cls) -> bool:
return True
# Not implemented
return False
@classmethod
def supports_sink(cls) -> bool:
+2 -1
View File
@@ -193,7 +193,8 @@ class RocmAttentionBackend(AttentionBackend):
@classmethod
def supports_mm_prefix(cls) -> bool:
return True
# Not implemented
return False
@classmethod
def supports_sink(cls) -> bool:
+22 -60
View File
@@ -18,7 +18,6 @@ from vllm.v1.attention.backends.mamba_attn import (
)
from vllm.v1.attention.backends.utils import (
NULL_BLOCK_ID,
compute_causal_conv1d_metadata,
mamba_get_block_table_tensor,
)
from vllm.v1.kv_cache_interface import MambaSpec
@@ -108,6 +107,7 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
_cudagraph_support = AttentionCGSupport.UNIFORM_BATCH
reorder_batch_threshold: int = 1
supports_update_block_table = False
needs_causal_conv1d_metadata = False
def __init__(
self,
@@ -281,18 +281,10 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
spec_sequence_masks_cpu, device=query_start_loc.device
)
# For causal_conv1d (non-spec prefill Triton kernel metadata).
nums_dict = None
batch_ptr = None
token_chunk_offset_ptr = None
has_initial_states_p = None
has_initial_states_d = None
num_computed_tokens_p = None
# Original request indices of the non-spec requests, ordered
# [decodes, prefills]. Used to gather per-request data consistently.
non_spec_req_idx_cpu: torch.Tensor | None = None
query_lens = torch.diff(query_start_loc)
# Per-request classification by mask, NOT by position. With
# spec-decode, the front decode group can contain both spec-decode
# requests and plain non-spec single-token decodes. Spec requests are
@@ -317,37 +309,32 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
else 0
)
# Original request indices grouped as
# [spec | non-spec decode | non-spec prefill]; each group keeps the
# original (already reordered) relative order via a stable nonzero.
spec_req_idx_cpu = spec_sequence_masks_cpu.nonzero(as_tuple=True)[0]
decode_req_idx_cpu = decode_mask_cpu.nonzero(as_tuple=True)[0]
prefill_req_idx_cpu = prefill_mask_cpu.nonzero(as_tuple=True)[0]
non_spec_req_idx_cpu = torch.cat((decode_req_idx_cpu, prefill_req_idx_cpu))
spec_req_idx = async_tensor_h2d(spec_req_idx_cpu, device=query_start_loc.device)
assert num_accepted_tokens is not None
non_spec_req_idx: torch.Tensor | None = None
if num_decodes == 0 and num_prefills == 0:
# Pure speculative-decode batch: all real tokens are spec tokens.
spec_token_indx = torch.arange(
num_spec_decode_tokens,
dtype=torch.int32,
device=query_start_loc.device,
)
non_spec_token_indx = torch.empty(
0, dtype=torch.int32, device=query_start_loc.device
)
spec_state_indices_tensor = block_table_tensor[spec_req_idx, 0]
# All real requests are speculative; zero-length padding is trailing.
spec_token_indx = None
non_spec_token_indx = None
spec_state_indices_tensor = block_table_tensor[:num_spec_decodes, 0]
num_accepted_tokens = num_accepted_tokens[:num_spec_decodes]
non_spec_state_indices_tensor = None
spec_query_start_loc = query_start_loc[: num_spec_decodes + 1]
non_spec_query_start_loc = None
non_spec_query_start_loc_cpu = None
else:
# Mixed batch: build a per-token group key consistent with the
# request grouping above (spec=0 | decode=1 | prefill=2) and a
# stable sort, so tokens of each request stay contiguous and in
# request order. This yields spec tokens first, then the non-spec
# [decode, prefill] tokens.
query_lens = torch.diff(query_start_loc)
spec_req_idx_cpu = spec_sequence_masks_cpu.nonzero(as_tuple=True)[0]
decode_req_idx_cpu = decode_mask_cpu.nonzero(as_tuple=True)[0]
prefill_req_idx_cpu = prefill_mask_cpu.nonzero(as_tuple=True)[0]
non_spec_req_idx_cpu = torch.cat((decode_req_idx_cpu, prefill_req_idx_cpu))
spec_req_idx = async_tensor_h2d(
spec_req_idx_cpu, device=query_start_loc.device
)
non_spec_req_idx = async_tensor_h2d(
non_spec_req_idx_cpu, device=query_start_loc.device
)
@@ -360,14 +347,17 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
dtype=torch.int64,
device=query_start_loc.device,
)
req_group[spec_req_idx] = 0
req_group[decode_req_idx] = 1
token_group = torch.repeat_interleave(req_group, query_lens)
req_group.index_fill_(0, spec_req_idx, 0)
req_group.index_fill_(0, decode_req_idx, 1)
token_group = torch.repeat_interleave(
req_group, query_lens, output_size=int(query_start_loc_cpu[-1])
)
token_perm = torch.argsort(token_group, stable=True)
spec_token_indx = token_perm[:num_spec_decode_tokens]
non_spec_token_indx = token_perm[num_spec_decode_tokens:]
spec_state_indices_tensor = block_table_tensor[spec_req_idx, 0]
num_accepted_tokens = num_accepted_tokens[spec_req_idx]
non_spec_state_indices_tensor = block_table_tensor[non_spec_req_idx, 0]
spec_query_start_loc = torch.zeros(
num_spec_decodes + 1,
@@ -385,22 +375,8 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
dim=0,
out=non_spec_query_start_loc[1:],
)
non_spec_query_start_loc_cpu = torch.zeros(
num_decodes + num_prefills + 1, dtype=torch.int32
)
torch.cumsum(
query_lens_cpu[non_spec_req_idx_cpu],
dim=0,
out=non_spec_query_start_loc_cpu[1:],
)
assert num_accepted_tokens is not None
# Accepted-token counts must follow the same request order as the
# speculative state indices.
num_accepted_tokens = num_accepted_tokens[spec_req_idx]
# Compute the conv-state slots for the non-spec decode/prefill split,
# plus the initial-state masks and Triton causal_conv1d metadata.
# Compute the conv-state slots for the non-spec decode/prefill split.
if non_spec_state_indices_tensor is None:
state_indices_tensor = block_table_tensor[:0, 0]
else:
@@ -431,20 +407,9 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
]
has_initial_states_p = num_computed_tokens_p > 0
assert non_spec_query_start_loc is not None
assert non_spec_query_start_loc_cpu is not None
query_start_loc_p = (
non_spec_query_start_loc[num_decodes:] - num_decode_tokens
)
query_start_loc_p_cpu = (
non_spec_query_start_loc_cpu[num_decodes:] - num_decode_tokens
)
if query_start_loc.device.type != "cpu":
nums_dict, batch_ptr, token_chunk_offset_ptr = (
compute_causal_conv1d_metadata(
query_start_loc_p_cpu,
device=query_start_loc.device,
)
)
# Prepare persistent tensors for CUDA graph capture and replay.
# ``m.num_actual_tokens`` is already padded by the model runner.
@@ -509,9 +474,6 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
non_spec_token_indx=non_spec_token_indx,
num_accepted_tokens=num_accepted_tokens,
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
nums_dict=nums_dict,
batch_ptr=batch_ptr,
token_chunk_offset_ptr=token_chunk_offset_ptr,
query_start_loc_p=query_start_loc_p,
query_start_loc_d=query_start_loc_d,
state_indices_tensor_p=state_indices_tensor_p,
+188 -27
View File
@@ -2017,7 +2017,48 @@ def _validate_dsv4_sparse_dims(
@triton.jit
def _pack_dense_prefix_to_ragged_kernel(
def _count_valid_row_entries_kernel(
indices_ptr,
lengths_ptr,
counts_ptr,
indptr_ptr,
indices_stride0,
num_rows_limit,
num_queries,
row_width,
BLOCK_R: tl.constexpr,
BLOCK_W: tl.constexpr,
):
pid = tl.program_id(0)
# The scan fills indptr[1:], so write indptr[0] here and skip a zero fill.
if pid == 0:
tl.store(indptr_ptr, 0)
rows = pid * BLOCK_R + tl.arange(0, BLOCK_R)
row_ok = rows < num_queries
row_len = tl.load(lengths_ptr + rows, mask=row_ok, other=0)
acc = tl.zeros((BLOCK_R,), dtype=tl.int32)
for start in range(0, row_width, BLOCK_W):
cols = start + tl.arange(0, BLOCK_W)
in_row = cols[None, :] < row_width
vals = tl.load(
indices_ptr + rows[:, None] * indices_stride0 + cols[None, :],
mask=row_ok[:, None] & in_row,
other=-1,
).to(tl.int32)
keep = (
row_ok[:, None] & in_row & (cols[None, :] < row_len[:, None]) & (vals >= 0)
)
if num_rows_limit >= 0:
keep = keep & (vals < num_rows_limit)
acc += tl.sum(keep.to(tl.int32), axis=1)
tl.store(counts_ptr + rows, acc, mask=row_ok)
@triton.jit
def _compact_dense_row_to_ragged_kernel(
indices_ptr,
lengths_ptr,
indptr_ptr,
@@ -2025,28 +2066,25 @@ def _pack_dense_prefix_to_ragged_kernel(
indices_stride0,
num_rows_limit,
row_width,
BLOCK_SIZE: tl.constexpr,
BLOCK_W: tl.constexpr,
):
row_idx = tl.program_id(0)
block_idx = tl.program_id(1)
offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
row_len = tl.load(lengths_ptr + row_idx)
if block_idx * BLOCK_SIZE >= row_len:
return
mask = offsets < row_len
safe_offsets = tl.where(offsets < row_width, offsets, 0)
vals = tl.load(
indices_ptr + row_idx * indices_stride0 + safe_offsets,
mask=mask & (offsets < row_width),
other=-1,
).to(tl.int32)
if num_rows_limit >= 0:
vals = tl.where((vals >= 0) & (vals < num_rows_limit), vals, -1)
out_start = tl.load(indptr_ptr + row_idx)
tl.store(out_ptr + out_start + offsets, vals, mask=mask)
written = 0
for start in range(0, row_width, BLOCK_W):
cols = start + tl.arange(0, BLOCK_W)
in_row = cols < row_width
vals = tl.load(
indices_ptr + row_idx * indices_stride0 + cols, mask=in_row, other=-1
).to(tl.int32)
keep = in_row & (cols < row_len) & (vals >= 0)
if num_rows_limit >= 0:
keep = keep & (vals < num_rows_limit)
rank = tl.cumsum(keep.to(tl.int32), axis=0) - 1
tl.store(out_ptr + out_start + written + rank, vals, mask=keep)
written += tl.sum(keep.to(tl.int32), axis=0)
def build_ragged_indices_from_dense(
@@ -2061,10 +2099,40 @@ def build_ragged_indices_from_dense(
)
max_width = indices.shape[1] if indices.ndim == 2 else 0
lengths = lengths.clamp(min=0, max=max_width).contiguous()
# Both kernels bound the row by row_width and row_len, so no clamp needed.
lengths = lengths.contiguous()
indptr = torch.zeros(indices.shape[0] + 1, dtype=torch.int32, device=indices.device)
torch.cumsum(lengths, dim=0, out=indptr[1:])
# Dense rows reserve slots they may not fill, leaving -1 anywhere in the
# first `lengths` entries. Keep only the valid ones, since the consumers
# index the KV pool without checking the sign.
num_queries = indices.shape[0]
# max_width is whatever the caller packed (align(topk + window, 128) for the
# V4.1 indexer) and nothing caps it, so loop the row rather than size the
# block by it.
block = min(triton.next_power_of_2(max_width), 1024) if max_width > 0 else 1
counts = torch.empty(num_queries, dtype=torch.int32, device=indices.device)
indptr = torch.empty(num_queries + 1, dtype=torch.int32, device=indices.device)
if num_queries > 0 and max_width > 0:
# A program per row only gets row_width elements, which is launch
# bound for narrow rows. Tile rows to fill the block.
block_r = max(1, 1024 // block)
_count_valid_row_entries_kernel[(triton.cdiv(num_queries, block_r),)](
indices,
lengths,
counts,
indptr,
indices.stride(0),
int(num_rows),
num_queries,
max_width,
BLOCK_R=block_r,
BLOCK_W=block,
)
else:
counts.zero_()
indptr.zero_()
torch.cumsum(counts, dim=0, out=indptr[1:])
if indices.numel() == 0:
flat = torch.empty(0, dtype=torch.int32, device=indices.device)
@@ -2075,10 +2143,7 @@ def build_ragged_indices_from_dense(
device=indices.device,
)
if flat.numel() > 0:
block_size = 128
_pack_dense_prefix_to_ragged_kernel[
(indices.shape[0], triton.cdiv(max_width, block_size))
](
_compact_dense_row_to_ragged_kernel[(indices.shape[0],)](
indices,
lengths,
indptr,
@@ -2086,7 +2151,7 @@ def build_ragged_indices_from_dense(
indices.stride(0),
int(num_rows),
max_width,
BLOCK_SIZE=block_size,
BLOCK_W=block,
)
return flat, indptr
@@ -4241,3 +4306,99 @@ def rocm_sparse_attn_decode(
if direct_out is None:
output.copy_(attn_out.to(output.dtype))
return output.shape[0] if inv_rope_positions is not None else 0
@triton.jit(do_not_specialize=["token_offset"])
def _prefill_topk_global_slots_kernel(
out_ptr,
lens_ptr,
topk_ptr,
topk_stride,
token_to_req_ptr,
query_start_loc_ptr,
seq_lens_ptr,
is_valid_token_ptr,
block_table_ptr,
block_table_stride,
token_offset,
num_compressed,
TOPK: tl.constexpr,
COMPRESS_RATIO: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
BLOCK_W: tl.constexpr,
):
row = tl.program_id(0)
token = row + token_offset
req = tl.load(token_to_req_ptr + token)
query_start = tl.load(query_start_loc_ptr + req)
query_len = tl.load(query_start_loc_ptr + req + 1) - query_start
pos = tl.load(seq_lens_ptr + req) - query_len + token - query_start
# Only (pos + 1) // ratio compressed tokens exist yet; the rest of the row
# can hold stale indices.
row_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOPK)
row_len = tl.where(tl.load(is_valid_token_ptr + token), row_len, 0)
for start in range(0, TOPK, BLOCK_W):
cols = start + tl.arange(0, BLOCK_W)
live = cols < row_len
local = tl.load(topk_ptr + row * topk_stride + cols, mask=live, other=-1)
valid = live & (local >= 0) & (local < num_compressed)
local = tl.where(valid, local, 0)
block = tl.load(
block_table_ptr + req * block_table_stride + local // BLOCK_SIZE,
mask=valid,
other=0,
)
slot = tl.where(valid, block * BLOCK_SIZE + local % BLOCK_SIZE, -1)
tl.store(out_ptr + row * TOPK + cols, slot, mask=cols < TOPK)
tl.store(lens_ptr + row, row_len)
def build_prefill_topk_ragged_indices(
topk_indices: torch.Tensor,
token_to_req_indices: torch.Tensor,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
is_valid_token: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
compress_ratio: int,
num_compressed: int,
token_offset: int,
num_rows: int = -1,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Map prefill top-k rows to a ragged stream of compressed-cache slots.
``topk_indices`` holds local compressed positions for the prefill tokens,
which sit at ``token_offset`` in the batch; ``token_to_req_indices``,
``query_start_loc``, ``seq_lens`` and ``block_table`` are batch-wide.
``block_size`` is the compressed cache's, i.e. already divided by the ratio.
"""
topk_indices = topk_indices.reshape(topk_indices.shape[0], -1)
num_tokens, width = topk_indices.shape
dense = torch.empty(
(num_tokens, width), dtype=torch.int32, device=topk_indices.device
)
lens = torch.empty(num_tokens, dtype=torch.int32, device=topk_indices.device)
if num_tokens > 0 and width > 0:
_prefill_topk_global_slots_kernel[(num_tokens,)](
dense,
lens,
topk_indices,
topk_indices.stride(0),
token_to_req_indices,
query_start_loc,
seq_lens,
is_valid_token,
block_table,
block_table.stride(0),
token_offset,
num_compressed,
TOPK=width,
COMPRESS_RATIO=compress_ratio,
BLOCK_SIZE=block_size,
BLOCK_W=min(triton.next_power_of_2(width), 1024),
)
else:
lens.zero_()
return build_ragged_indices_from_dense(dense, lens, num_rows=num_rows)
@@ -58,6 +58,13 @@ def flash_attn_maxseqlen_wrapper(
max_seqlen = max_seqlen.item()
q, k, v = (einops.rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v])
if current_platform.is_cuda() and torch.cuda.is_current_stream_capturing():
# workaround for encoder CUDA-graph replay paddings with NaNs edge case
kwargs["out"] = torch.zeros(
q.shape[0], q.shape[1], v.shape[-1], dtype=q.dtype, device=q.device
)
output = flash_attn_varlen_func(
q,
k,
+3 -3
View File
@@ -41,7 +41,7 @@ class RequestQueue(ABC):
pass
@abstractmethod
def prepend_requests(self, requests: "RequestQueue") -> None:
def prepend_requests(self, requests: Iterable[Request]) -> None:
"""Prepend all requests from another queue to the front of this
queue."""
pass
@@ -93,7 +93,7 @@ class FCFSRequestQueue(deque[Request], RequestQueue):
"""Prepend a request to the front of the queue."""
self.appendleft(request)
def prepend_requests(self, requests: RequestQueue) -> None:
def prepend_requests(self, requests: Iterable[Request]) -> None:
"""Prepend all requests from another queue to the front of this
queue.
@@ -163,7 +163,7 @@ class PriorityRequestQueue(RequestQueue):
front. Requests are ordered by (priority, arrival_time)."""
self.add_request(request)
def prepend_requests(self, requests: RequestQueue) -> None:
def prepend_requests(self, requests: Iterable[Request]) -> None:
"""Add all requests from another queue according to priority policy.
Note: In a priority queue, there is no concept of prepending to the

Some files were not shown because too many files have changed in this diff Show More