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

This commit is contained in:
2026-09-28 12:06:52 +07:00
170 changed files with 7605 additions and 1142 deletions
@@ -118,7 +118,7 @@ class RoutingMethodType(IntEnum):
# SigmoidRenorm: Sigmoid -> TopK -> Renormalize (divide by sum of top-K)
SigmoidRenorm = (6,)
# MiniMax2: Sigmoid + Bias -> TopK -> ScaledSumNormalize
# (routeScale=1.0, epsilon=1e-20)
# (routeScale=routed_scaling_factor, epsilon=1e-20)
MiniMax2 = (7,)
# Sigmoid: Sigmoid -> TopK (no renormalization)
Sigmoid = (8,)
@@ -137,7 +137,6 @@ def get_routing_method_type(
renormalize: bool,
num_expert_group: int | None,
has_e_score_bias: bool,
routed_scaling_factor: float | None = 1.0,
) -> RoutingMethodType:
if scoring_func == "sqrtsoftplus":
# DeepSeek V4 uses sqrtsoftplus routing with optional routing bias
@@ -153,9 +152,7 @@ def get_routing_method_type(
return RoutingMethodType.Unspecified
if (num_expert_group or 0) > 0:
return RoutingMethodType.DeepSeekV3
if routed_scaling_factor in (None, 1.0):
return RoutingMethodType.MiniMax2
return RoutingMethodType.Unspecified
return RoutingMethodType.MiniMax2
else:
return RoutingMethodType.Unspecified
@@ -139,7 +139,7 @@ def aiter_triton_kernel_w4a16_moe_forward(
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import (
should_use_cdna4_mx_scale_swizzle,
)
from vllm.platforms.rocm import on_gfx1250
from vllm.platforms.rocm import on_gfx950, on_gfx1250
try:
from aiter.ops.triton.moe.moe_op_gemm_a16w4 import moe_gemm_a16w4
@@ -236,6 +236,12 @@ def aiter_triton_kernel_w4a16_moe_forward(
# kernel indexes a swizzled buffer as if it were linear.
swz = "CDNA4_SCALE" if should_use_cdna4_mx_scale_swizzle() else None
# AITER's gfx950 Gluon a16w4 kernel (default backend="None"/auto-detect
# picks it) calls a Triton-Gluon AMD API that isn't available in vLLM's
# pinned Triton, so force the Triton backend on gfx950. gfx1250 already
# used Gluon before this and is unaffected, so leave it on auto-detect.
a16w4_backend = "triton" if on_gfx950() else None
intermediate = moe_gemm_a16w4(
hidden_states,
w1_data,
@@ -254,6 +260,7 @@ def aiter_triton_kernel_w4a16_moe_forward(
swiglu_add_residual=swiglu_add_residual,
unpadded_N=unpadded_N_w1,
unpadded_K=unpadded_K_w1,
backend=a16w4_backend,
)
out = moe_gemm_a16w4(
@@ -270,6 +277,7 @@ def aiter_triton_kernel_w4a16_moe_forward(
swizzle_mx_scale=swz,
unpadded_N=unpadded_N_w2,
unpadded_K=unpadded_K_w2,
backend=a16w4_backend,
)
return out
@@ -385,10 +385,11 @@ def rocm_aiter_fused_experts(
gate_mode = ""
if activation == MoEActivation.SITU:
# SiTUv2 flydsl (VLLM_ROCM_USE_AITER_MOE_SITUV2=1) uses a4w4
# fp4 activations with separated gate/up weights (AITER #4463);
# default a16w4 SiTU also stays separated.
gate_mode = GateMode.SEPARATED.value
gate_mode = (
GateMode.INTERLEAVE.value
if rocm_aiter_ops.is_fused_moe_situv2_gate_up_interleaved()
else GateMode.SEPARATED.value
)
elif quant_config.use_mxfp4_w4a16:
gate_mode = GateMode.INTERLEAVE.value
elif activation_interleave is not None:
@@ -1596,8 +1596,7 @@ def convert_weight_to_mxfp4_moe_kernel_format(
fp4_dtype = torch.float4_e2m1fn_x2
e8m0_dtype = torch.float8_e8m0fnu
# SiTUv2 flydsl uses separated gate/up layout (a4w4).
guinterleave = False
guinterleave = rocm_aiter_ops.is_fused_moe_situv2_gate_up_interleaved()
w13 = rocm_aiter_ops.shuffle_weight_a16w4(
w13_weight.data.view(fp4_dtype), 16, guinterleave
)
@@ -198,7 +198,6 @@ class CPURouter(BaseRouter):
renormalize=self.renormalize,
num_expert_group=self.num_expert_group,
has_e_score_bias=self.e_score_correction_bias is not None,
routed_scaling_factor=self.routed_scaling_factor,
)
def _compute_routing(
@@ -391,7 +391,6 @@ class FusedTopKBiasRouter(BaseRouter):
renormalize=self.renormalize,
num_expert_group=None,
has_e_score_bias=True,
routed_scaling_factor=self.routed_scaling_factor,
)
def _compute_routing(
@@ -283,7 +283,6 @@ class GroupedTopKRouter(BaseRouter):
renormalize=self.renormalize,
num_expert_group=self.num_expert_group,
has_e_score_bias=self.e_score_correction_bias is not None,
routed_scaling_factor=self.routed_scaling_factor,
)
def _compute_routing(
@@ -188,7 +188,6 @@ def create_fused_moe_router(
renormalize=renormalize,
num_expert_group=groups,
has_e_score_bias=e_score_correction_bias is not None,
routed_scaling_factor=routed_scaling_factor,
)
routing_method_preserved = advertised_routing_method(
@@ -4,10 +4,7 @@
import torch
from vllm.distributed.eplb.eplb_state import EplbLayerState
from vllm.model_executor.layers.fused_moe.config import (
RoutingMethodType,
get_routing_method_type,
)
from vllm.model_executor.layers.fused_moe.config import RoutingMethodType
from vllm.model_executor.layers.fused_moe.fused_moe import (
zero_experts_compute_triton,
)
@@ -53,14 +50,9 @@ class ZeroExpertRouter(BaseRouter):
@property
def routing_method_type(self) -> RoutingMethodType:
return get_routing_method_type(
scoring_func=self.scoring_func,
top_k=self.top_k,
renormalize=self.renormalize,
num_expert_group=None,
has_e_score_bias=True,
routed_scaling_factor=self.routed_scaling_factor,
)
# Zero experts are resolved by this router, which kernels with
# built-in routing (e.g. FlashInfer TRT-LLM) cannot reproduce.
return RoutingMethodType.Unspecified
def _compute_routing(
self,
@@ -0,0 +1,81 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""In-place interleaved RoPE on the Q/K slices of a packed QKV buffer."""
import torch
from vllm.triton_utils import tl, triton
# seqlen is not specialized: image sizes vary per request.
@triton.jit(do_not_specialize=["seqlen"])
def _packed_qk_rope_kernel(
qk_ptr, # (seqlen, 2 * nheads, headdim) strided view of the packed QKV
freqs_ptr, # (seqlen, rotary_dim) fp32 re/im view of the complex freqs
seqlen,
qk_row_stride,
qk_head_stride,
rotary_dim: tl.constexpr,
BLOCK_M: tl.constexpr,
):
BLOCK_K: tl.constexpr = triton.next_power_of_2(rotary_dim)
pid_m = tl.program_id(0)
pid_h = tl.program_id(1)
rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
rk = tl.arange(0, BLOCK_K)
mask_m = rm < seqlen
base = qk_ptr + pid_h * qk_head_stride + rm[:, None] * qk_row_stride
mask_x = mask_m[:, None] & (rk < rotary_dim)[None, :]
x = tl.load(base + rk[None, :], mask=mask_x, other=0.0).to(tl.float32)
f = tl.load(freqs_ptr + rm[:, None] * rotary_dim + rk[None, :], mask=mask_x)
cos, sin = tl.split(tl.reshape(f, (BLOCK_M, BLOCK_K // 2, 2)))
x0, x1 = tl.split(tl.reshape(x, (BLOCK_M, BLOCK_K // 2, 2)))
o0 = x0 * cos - x1 * sin
o1 = x1 * cos + x0 * sin
tl.store(base + rk[None, :], tl.interleave(o0, o1), mask=mask_x)
def packed_qk_rope_(xqkv: torch.Tensor, freqs_cis: torch.Tensor) -> None:
"""Rotate Q and K in place inside a packed QKV buffer.
Args:
xqkv: contiguous (seqlen, 3, nheads, headdim); only the Q and K
slices are rotated.
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.
Requires triton: callers must check HAS_TRITON and use the unfused path
otherwise. Contract violations raise.
"""
assert xqkv.ndim == 4 and xqkv.size(1) == 3, xqkv.shape
assert xqkv.is_contiguous(), xqkv.shape
assert freqs_cis.ndim == 2 and freqs_cis.is_contiguous(), freqs_cis.shape
assert freqs_cis.dtype == torch.complex64, freqs_cis.dtype
seq_length, _, num_heads, head_dim = xqkv.shape
rotary_dim = freqs_cis.size(-1) * 2
assert freqs_cis.size(0) == seq_length, (freqs_cis.shape, xqkv.shape)
assert rotary_dim == head_dim, (freqs_cis.shape, xqkv.shape) # full rotation
qk = xqkv.as_strided(
(seq_length, 2 * num_heads, head_dim),
(3 * num_heads * head_dim, head_dim, 1),
)
BLOCK_M = 4
# seqlen on grid.x: HIP caps gridDim.y at 65535.
grid = (triton.cdiv(seq_length, BLOCK_M), 2 * num_heads)
_packed_qk_rope_kernel[grid](
qk,
freqs_cis.view(torch.float32),
seq_length,
qk.stride(0),
qk.stride(1),
rotary_dim=rotary_dim,
BLOCK_M=BLOCK_M,
num_warps=2 if rotary_dim <= 64 else 4,
)
+7
View File
@@ -377,6 +377,13 @@ def rocm_unquantized_gemm(
weight: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
# dispatch_unquantized_gemm() picks this backend for any ROCm build,
# regardless of the tensor's actual device; the custom op below is only
# registered for the CUDA/HIP dispatch key, so route CPU tensors (e.g.
# from unit tests that build layers without moving them to the GPU)
# through the device-agnostic fallback instead of hard-crashing.
if not x.is_cuda:
return default_unquantized_gemm(layer, x, weight, bias)
return torch.ops.vllm.rocm_unquantized_gemm(x, weight, bias)
@@ -1,10 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable
from collections.abc import Callable
from functools import wraps
from types import FunctionType
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Concatenate, ParamSpec, TypeVar
import torch
@@ -20,13 +19,18 @@ if TYPE_CHECKING:
__all__ = ["set_torchao_reload_attrs", "support_quantized_model_reload_from_hp_weights"]
_P = ParamSpec("_P")
_R = TypeVar("_R")
def set_torchao_reload_attrs(model: torch.nn.Module, model_config: ModelConfig):
model._do_torchao_reload = True
model._model_config = model_config
def support_quantized_model_reload_from_hp_weights(original_load_weights: FunctionType):
def support_quantized_model_reload_from_hp_weights(
original_load_weights: Callable[Concatenate["AutoWeightsLoader", _P], _R],
) -> Callable[Concatenate["AutoWeightsLoader", _P], _R]:
"""Decorator for `load_weights` method for AutoWeightsLoader.load_weights to support
reloading high precision (bfloat16/float16/float32) weight for an already quantized
model, this involves restoring the weights to a high precision weights and
@@ -39,17 +43,16 @@ def support_quantized_model_reload_from_hp_weights(original_load_weights: Functi
@wraps(original_load_weights)
def patched_model_load_weights(
self: "AutoWeightsLoader",
weights: Iterable[tuple[str, torch.Tensor]],
*args,
**kwargs,
):
*args: _P.args,
**kwargs: _P.kwargs,
) -> _R:
model = self.module
if not getattr(model, "_do_torchao_reload", False):
return original_load_weights(self, weights, *args, **kwargs)
return original_load_weights(self, *args, **kwargs)
initialize_layerwise_reload(model)
loaded_weights = original_load_weights(self, weights, *args, **kwargs)
loaded_weights = original_load_weights(self, *args, **kwargs)
finalize_layerwise_reload(model, model._model_config)
return loaded_weights
+16 -7
View File
@@ -30,6 +30,9 @@ from vllm.model_executor.layers.linear import (
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding.common import ApplyRotaryEmb
from vllm.model_executor.layers.rotary_embedding.packed_qk_rope import (
packed_qk_rope_,
)
from vllm.model_executor.models.utils import maybe_prefix
from vllm.model_executor.models.vision import (
is_vit_use_data_parallel,
@@ -37,6 +40,7 @@ from vllm.model_executor.models.vision import (
)
from vllm.platforms import current_platform
from vllm.transformers_utils.configs.kimi_k25 import KimiK25VisionConfig
from vllm.triton_utils import HAS_TRITON
from vllm.utils.torch_utils import async_tensor_h2d
logger = init_logger(__name__)
@@ -451,14 +455,19 @@ class MoonViTEncoderLayer(nn.Module):
)
# xqkv: (seqlen, 3, nheads, headdim)
xqkv = xqkv.view(*qkv_shape)
xq, xk, xv = torch.unbind(xqkv, dim=-3)
_apply_rope_input_validation(xq, rope_freqs_cis)
_apply_rope_input_validation(xk, rope_freqs_cis)
rope_cos = rope_freqs_cis.real.contiguous()
rope_sin = rope_freqs_cis.imag.contiguous()
xq = self.apply_rotary_emb(xq, rope_cos, rope_sin)
xk = self.apply_rotary_emb(xk, rope_cos, rope_sin)
# xq/xk alias xqkv, so the in-place rotation below is visible through
# them; only the fallback needs to rebind.
xq, xk, xv = torch.unbind(xqkv, dim=-3)
if HAS_TRITON:
packed_qk_rope_(xqkv, rope_freqs_cis)
else:
_apply_rope_input_validation(xq, rope_freqs_cis)
_apply_rope_input_validation(xk, rope_freqs_cis)
rope_cos = rope_freqs_cis.real.contiguous()
rope_sin = rope_freqs_cis.imag.contiguous()
xq = self.apply_rotary_emb(xq, rope_cos, rope_sin)
xk = self.apply_rotary_emb(xk, rope_cos, rope_sin)
if max_seqlen is None:
max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max()
+12 -9
View File
@@ -1055,15 +1055,18 @@ class OpenPanguVLForConditionalGeneration(
input_ids: torch.Tensor,
multimodal_embeddings: MultiModalEmbeddings | None = None,
) -> torch.Tensor:
inputs_embeds = self.language_model.embed_input_ids(input_ids)
if multimodal_embeddings is not None:
inputs_embeds = self.embed_input_ids( # type: ignore[call-overload]
input_ids,
inputs_embeds,
multimodal_embeddings,
[self.config.image_token_id, self.config.video_token_id],
)
return inputs_embeds
if multimodal_embeddings is None:
return self.language_model.embed_input_ids(input_ids)
mm_token_ids = input_ids.new_tensor(
[self.config.image_token_id, self.config.video_token_id]
)
is_multimodal = torch.isin(input_ids, mm_token_ids)
return self.embed_input_ids(
input_ids,
multimodal_embeddings,
is_multimodal=is_multimodal,
)
def _process_image_input(
self, image_input: OpenPanguVLImageInputs
+1 -1
View File
@@ -1297,7 +1297,7 @@ class Phi4MMForCausalLM(nn.Module, SupportsLoRA, SupportsMultiModal):
logits = self.logits_processor(self.lm_head, hidden_states)
return logits
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> None:
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
+5 -3
View File
@@ -41,7 +41,7 @@ from vllm.model_executor.models.utils import (
from vllm.sequence import IntermediateTensors
from .bert_with_rope import BertWithRope, JinaRobertaModel
from .interfaces import SupportsCrossEncoding
from .interfaces import SupportsCrossEncoding, SupportsLoRA
from .interfaces_base import attn_type, default_pooling_type
@@ -266,7 +266,7 @@ class BgeM3EmbeddingModel(RobertaEmbeddingModel):
@default_pooling_type(seq_pooling_type="CLS")
class RobertaForSequenceClassification(nn.Module, SupportsCrossEncoding):
class RobertaForSequenceClassification(nn.Module, SupportsCrossEncoding, SupportsLoRA):
"""A model that uses Roberta to provide embedding functionalities.
This class encapsulates the BertModel and provides an interface for
@@ -279,6 +279,7 @@ class RobertaForSequenceClassification(nn.Module, SupportsCrossEncoding):
"""
is_pooling_model = True
packed_modules_mapping = {"qkv_proj": ["query", "key", "value"]}
jina_to_vllm_mapper = WeightsMapper(
orig_to_new_substr={
"emb_ln": "embeddings.LayerNorm",
@@ -295,7 +296,8 @@ class RobertaForSequenceClassification(nn.Module, SupportsCrossEncoding):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
self.padding_idx: int = vllm_config.model_config.hf_config.pad_token_id
self.config = config
self.padding_idx: int = config.pad_token_id
self.num_labels = config.num_labels
self.roberta = BertModel(
+13 -8
View File
@@ -282,10 +282,14 @@ class UltravoxMultiModalProcessor(BaseMultiModalProcessor[UltravoxProcessingInfo
def get_replacement_ultravox(item_idx: int):
if "audio_num_tokens" in out_mm_data:
return [replacement_id] * int(out_mm_data["audio_num_tokens"][item_idx])
audio_num_tokens = out_mm_data["audio_num_tokens"]
assert isinstance(audio_num_tokens, torch.Tensor)
return [replacement_id] * int(audio_num_tokens[item_idx])
start = chunks_start_idx[item_idx]
end = chunks_start_idx[item_idx + 1]
audio_token_len = out_mm_data["audio_token_len"][start:end].sum()
audio_token_lens = out_mm_data["audio_token_len"]
assert isinstance(audio_token_lens, torch.Tensor)
audio_token_len = audio_token_lens[start:end].sum()
return [replacement_id] * int(audio_token_len) # type: ignore
return [
@@ -566,7 +570,8 @@ class UltravoxWhisperEncoder(WhisperEncoder):
) -> torch.Tensor:
return (input_lengths - 1) // 2 + 1
def forward(
# Ultravox requires chunk lengths in addition to Whisper's input features.
def forward( # type: ignore[override]
self,
input_features: torch.Tensor,
audio_lens: torch.Tensor,
@@ -960,12 +965,12 @@ def pad_and_concat_to_dim3(
return features
features = [pad_and_concat_to_dim3(f) for f in features]
tensors = [pad_and_concat_to_dim3(f) for f in features]
max_len = max(f.shape[-1] for f in features)
max_len = max(f.shape[-1] for f in tensors)
# Ensure all features have dim=3
features = [f.view(-1, *f.shape[-2:]) for f in features]
tensors = [f.view(-1, *f.shape[-2:]) for f in tensors]
# Pad and concatenate:
# [[B1, 80, M1], [B2, 80, M2]] -> [B1+B2, 80, max(M1, M2)]
features = [F.pad(f, (0, max_len - f.shape[-1])) for f in features]
return torch.cat(features)
tensors = [F.pad(f, (0, max_len - f.shape[-1])) for f in tensors]
return torch.cat(tensors)
@@ -199,6 +199,7 @@ class UnlimitedOCRMultiModalProcessor(DeepseekOCRMultiModalProcessor):
if isinstance(images, ImageEmbeddingItems):
num_image_tokens = images.get_feature_size(item_idx)
else:
assert isinstance(images, ImageProcessorItems)
size = images.get_image_size(item_idx)
# Disable crop mode for multi-image input.
+8 -7
View File
@@ -35,7 +35,6 @@ if TYPE_CHECKING:
from transformers import PreTrainedConfig
from transformers.conversion_mapping import WeightRenaming
from vllm.config.model import ModelConfig
from vllm.model_executor.layers.quantization import QuantizationConfig
logger = init_logger(__name__)
@@ -337,7 +336,7 @@ class AutoWeightsLoader:
"""
# Add persistent registered buffers.
# Non-persistent buffers are excluded, matching PyTorch state_dict().
non_persistent = getattr(module, "_non_persistent_buffers_set", set())
non_persistent: set[str] = getattr(module, "_non_persistent_buffers_set", set())
for buf_name, buf in module.named_buffers(recurse=False):
if buf_name not in child_params and buf_name not in non_persistent:
child_params[buf_name] = buf
@@ -558,7 +557,7 @@ def maybe_fuse_shared_experts(
def get_spec_layer_idx_from_weight_name(
config: "ModelConfig", weight_name: str
config: "PreTrainedConfig", weight_name: str
) -> int | None:
"""Return the MTP layer index a weight belongs to, or None.
@@ -587,7 +586,7 @@ def get_spec_layer_idx_from_weight_name(
def skip_spec_layers(
weights: Iterable[tuple[str, torch.Tensor]], config: "ModelConfig"
weights: Iterable[tuple[str, torch.Tensor]], config: "PreTrainedConfig"
) -> Iterable[tuple[str, torch.Tensor]]:
"""Drop MTP spec-layer weights (loaded by the MTP head, not the base model).
@@ -629,11 +628,11 @@ def init_vllm_registered_model(
@overload
def flatten_bn(x: torch.Tensor) -> torch.Tensor: ...
def flatten_bn(x: list[torch.Tensor]) -> list[torch.Tensor]: ...
@overload
def flatten_bn(x: list[torch.Tensor]) -> list[torch.Tensor]: ...
def flatten_bn(x: torch.Tensor) -> torch.Tensor: ...
@overload
@@ -973,7 +972,9 @@ def get_draft_quant_config(vllm_config: VllmConfig) -> "QuantizationConfig | Non
The draft model's config if available, None otherwise.
"""
draft_model_config = vllm_config.speculative_config.draft_model_config
speculative_config = vllm_config.speculative_config
assert speculative_config is not None
draft_model_config = speculative_config.draft_model_config
draft_load_config = vllm_config.load_config
return (