Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-20 09:27:57 +09:00
682 changed files with 26127 additions and 5580 deletions
@@ -254,6 +254,233 @@ _BATCH_INVARIANT_MATMUL_TUNED_CONFIGS: dict[
),
),
},
"sm120": {
(12288, 2048): _MatmulShapeConfig( # Qwen3-1.7B gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 5)),
(4, _MatmulMConfig(16, 128, 8, 4)),
(8, _MatmulMConfig(16, 128, 8, 4)),
(16, _MatmulMConfig(16, 128, 4, 4)),
(32, _MatmulMConfig(32, 128, 8, 5)),
(64, _MatmulMConfig(64, 128, 4, 3)),
(256, _MatmulMConfig(64, 64, 4, 4)),
(512, _MatmulMConfig(64, 128, 4, 5)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2048, 6144): _MatmulShapeConfig( # Qwen3-1.7B down_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 32, 8, 5)),
(4, _MatmulMConfig(16, 32, 8, 3)),
(8, _MatmulMConfig(16, 32, 8, 4)),
(16, _MatmulMConfig(16, 32, 4, 5)),
(32, _MatmulMConfig(32, 32, 4, 5)),
(64, _MatmulMConfig(32, 32, 4, 4)),
(256, _MatmulMConfig(64, 64, 4, 5)),
(512, _MatmulMConfig(128, 64, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 64, 8, 4)),
),
),
(4096, 2048): _MatmulShapeConfig( # Qwen3-1.7B qkv_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 64, 4, 4)),
(4, _MatmulMConfig(16, 64, 8, 5)),
(8, _MatmulMConfig(16, 64, 8, 5)),
(16, _MatmulMConfig(16, 64, 8, 3)),
(32, _MatmulMConfig(16, 64, 8, 5)),
(64, _MatmulMConfig(32, 64, 4, 2)),
(256, _MatmulMConfig(64, 128, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(151936, 2048): _MatmulShapeConfig( # Qwen3-1.7B lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 5)),
(4, _MatmulMConfig(16, 128, 4, 4)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(16, 128, 8, 3)),
(32, _MatmulMConfig(32, 128, 8, 3)),
(64, _MatmulMConfig(32, 128, 8, 5)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 8, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2048, 2048): _MatmulShapeConfig( # Qwen3-1.7B o_proj
block_k=32,
m_buckets=(
(1, _MatmulMConfig(16, 128, 4, 3)),
(4, _MatmulMConfig(16, 128, 4, 4)),
(8, _MatmulMConfig(16, 64, 4, 5)),
(16, _MatmulMConfig(32, 32, 8, 4)),
(32, _MatmulMConfig(16, 64, 4, 5)),
(64, _MatmulMConfig(32, 32, 4, 5)),
(256, _MatmulMConfig(128, 32, 4, 5)),
(512, _MatmulMConfig(128, 64, 4, 4)),
(1024, _MatmulMConfig(128, 128, 8, 5)),
(2048, _MatmulMConfig(128, 256, 8, 4)),
),
),
(19456, 2560): _MatmulShapeConfig( # Qwen3-4B gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 4)),
(4, _MatmulMConfig(16, 128, 8, 3)),
(8, _MatmulMConfig(16, 128, 8, 5)),
(16, _MatmulMConfig(16, 128, 8, 5)),
(32, _MatmulMConfig(32, 128, 4, 4)),
(64, _MatmulMConfig(64, 128, 8, 4)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(64, 128, 4, 5)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2560, 9728): _MatmulShapeConfig( # Qwen3-4B down_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 64, 4, 5)),
(4, _MatmulMConfig(16, 64, 4, 4)),
(8, _MatmulMConfig(16, 64, 4, 4)),
(16, _MatmulMConfig(16, 32, 4, 5)),
(32, _MatmulMConfig(32, 32, 4, 3)),
(64, _MatmulMConfig(32, 64, 8, 4)),
(256, _MatmulMConfig(64, 64, 4, 3)),
(512, _MatmulMConfig(64, 128, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(6144, 2560): _MatmulShapeConfig( # Qwen3-4B qkv_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 128, 8, 4)),
(4, _MatmulMConfig(16, 256, 4, 3)),
(8, _MatmulMConfig(16, 128, 4, 5)),
(16, _MatmulMConfig(16, 64, 8, 3)),
(32, _MatmulMConfig(16, 128, 8, 4)),
(64, _MatmulMConfig(64, 64, 4, 5)),
(256, _MatmulMConfig(128, 128, 8, 3)),
(512, _MatmulMConfig(64, 64, 4, 5)),
(1024, _MatmulMConfig(64, 128, 8, 4)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(151936, 2560): _MatmulShapeConfig( # Qwen3-4B lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 5)),
(4, _MatmulMConfig(16, 64, 8, 5)),
(8, _MatmulMConfig(16, 64, 4, 5)),
(16, _MatmulMConfig(16, 64, 4, 5)),
(32, _MatmulMConfig(32, 64, 4, 5)),
(64, _MatmulMConfig(64, 64, 4, 5)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 8, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(2560, 4096): _MatmulShapeConfig( # Qwen3-4B o_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 3)),
(4, _MatmulMConfig(16, 64, 8, 4)),
(8, _MatmulMConfig(16, 64, 8, 5)),
(16, _MatmulMConfig(16, 64, 4, 4)),
(32, _MatmulMConfig(16, 32, 4, 4)),
(64, _MatmulMConfig(16, 64, 8, 3)),
(256, _MatmulMConfig(64, 64, 8, 3)),
(512, _MatmulMConfig(64, 128, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(24576, 4096): _MatmulShapeConfig( # Qwen3-8B gate_up_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 256, 8, 3)),
(4, _MatmulMConfig(16, 256, 8, 3)),
(8, _MatmulMConfig(16, 256, 8, 3)),
(16, _MatmulMConfig(16, 256, 8, 3)),
(32, _MatmulMConfig(32, 256, 8, 3)),
(64, _MatmulMConfig(64, 256, 4, 3)),
(256, _MatmulMConfig(64, 128, 4, 5)),
(512, _MatmulMConfig(128, 128, 4, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(4096, 12288): _MatmulShapeConfig( # Qwen3-8B down_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 64, 4, 5)),
(4, _MatmulMConfig(16, 64, 4, 5)),
(8, _MatmulMConfig(16, 64, 4, 4)),
(16, _MatmulMConfig(16, 32, 4, 4)),
(32, _MatmulMConfig(32, 32, 8, 5)),
(64, _MatmulMConfig(32, 64, 4, 5)),
(256, _MatmulMConfig(64, 128, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
(6144, 4096): _MatmulShapeConfig( # Qwen3-8B qkv_proj
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 4)),
(4, _MatmulMConfig(16, 128, 8, 4)),
(8, _MatmulMConfig(16, 128, 4, 4)),
(16, _MatmulMConfig(16, 64, 4, 5)),
(32, _MatmulMConfig(16, 128, 8, 5)),
(64, _MatmulMConfig(64, 64, 4, 4)),
(256, _MatmulMConfig(128, 128, 8, 3)),
(512, _MatmulMConfig(64, 64, 4, 5)),
(1024, _MatmulMConfig(128, 64, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(151936, 4096): _MatmulShapeConfig( # Qwen3-8B lm_head
block_k=64,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 5)),
(4, _MatmulMConfig(16, 64, 8, 5)),
(8, _MatmulMConfig(16, 64, 4, 5)),
(16, _MatmulMConfig(16, 64, 4, 5)),
(32, _MatmulMConfig(32, 64, 4, 5)),
(64, _MatmulMConfig(32, 128, 8, 5)),
(256, _MatmulMConfig(128, 128, 4, 3)),
(512, _MatmulMConfig(128, 128, 8, 3)),
(1024, _MatmulMConfig(128, 128, 4, 3)),
(2048, _MatmulMConfig(128, 128, 4, 3)),
),
),
(4096, 4096): _MatmulShapeConfig( # Qwen3-8B o_proj
block_k=128,
m_buckets=(
(1, _MatmulMConfig(16, 64, 8, 4)),
(4, _MatmulMConfig(16, 64, 4, 3)),
(8, _MatmulMConfig(16, 32, 4, 4)),
(16, _MatmulMConfig(16, 32, 4, 3)),
(32, _MatmulMConfig(16, 64, 4, 5)),
(64, _MatmulMConfig(64, 32, 8, 4)),
(256, _MatmulMConfig(64, 128, 4, 3)),
(512, _MatmulMConfig(64, 64, 4, 3)),
(1024, _MatmulMConfig(64, 128, 4, 3)),
(2048, _MatmulMConfig(64, 128, 4, 3)),
),
),
},
}
_TUNED_MATMUL_CONFIGS_FOR_DEVICE: dict[tuple[int, int], _MatmulShapeConfig] | None = (
@@ -265,6 +492,8 @@ _TUNED_MATMUL_CONFIGS_RESOLVED = False
def _get_tuned_matmul_arch_family(capability: DeviceCapability | None) -> str | None:
if capability is None:
return None
if capability.major == 12:
return "sm120"
if capability.major == 10:
return "blackwell"
if capability.major == 9:
@@ -66,9 +66,10 @@ def _store_candidates_kernel(
cols = tl.program_id(1) * TILE + tl.arange(0, TILE)
value = tl.load(values + row * k + cols, cols < k, other=-float("inf"))
index = tl.load(indices + row * k + cols, cols < k, other=-1)
# NaN scores can occur during warmup; only -inf denotes padding.
tl.store(
output + row * out_stride_row + cols * out_stride_col,
tl.where(value > -float("inf"), index, -1),
tl.where(value != -float("inf"), index, -1),
cols < OUT_K,
)
@@ -73,7 +73,7 @@ def check_deep_select_layout(num_sparse_cols: int, topk_tokens: int) -> None:
_INT32_BIG = tl.constexpr(2**31 - 1)
@triton.jit
@triton.jit(do_not_specialize_on_alignment=["end_ptr"])
def _expand_candidates_kernel(
cand_ptr,
cand_stride,
@@ -186,6 +186,8 @@ from vllm.model_executor.kernels.linear.scaled_mm.b12x import (
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8BlockScaledMMKernel,
CPUFp8PerTensorScaledMMLinearKernel,
CPUFp8W8A8BlockScaledMMKernel,
CPUFP8W8A8ScaledMMLinearKernel,
CPUInt8ScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.cutlass import (
@@ -436,6 +438,7 @@ _POSSIBLE_FP8_KERNELS: dict[PlatformEnum, list[type[FP8ScaledMMLinearKernel]]] =
ChannelWiseTorchFP8ScaledMMLinearKernel,
],
PlatformEnum.CPU: [
CPUFP8W8A8ScaledMMLinearKernel,
CPUFp8PerTensorScaledMMLinearKernel,
PerTensorTorchFP8ScaledMMLinearKernel,
ChannelWiseTorchFP8ScaledMMLinearKernel,
@@ -468,6 +471,7 @@ _POSSIBLE_FP8_BLOCK_KERNELS: dict[
TritonFp8BlockScaledMMKernel,
],
PlatformEnum.CPU: [
CPUFp8W8A8BlockScaledMMKernel, # W8A8 preferred; falls back to W8A16 below
CPUFp8BlockScaledMMKernel,
],
PlatformEnum.XPU: [
@@ -864,6 +868,7 @@ def choose_mp_linear_kernel(
can_implement, failure_reason = kernel.can_implement(config)
if can_implement:
logger.info_once("Using %s for mixed-precision linear", kernel.__name__)
return kernel
else:
failure_reasons.append(
@@ -27,6 +27,10 @@ class Mxfp8LinearKernel(ABC):
Marlin, emulation).
"""
supports_pre_processed_weights: bool = False
"""True if ``process_weights_after_loading`` only rewrites parameters, so
weights exported by the weight cache daemon can be used as-is."""
def __init__(self, c: Mxfp8LinearLayerConfig) -> None:
assert self.can_implement(c)[0]
assert self.is_supported()[0]
@@ -16,6 +16,8 @@ from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig
class EmulationMxfp8LinearKernel(Mxfp8LinearKernel):
"""Software emulation fallback for MXFP8 (dequant to BF16)."""
supports_pre_processed_weights = True
@classmethod
def is_supported(
cls, compute_capability: int | None = None
@@ -27,6 +27,8 @@ from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig
class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel):
"""MXFP8 W8A8 GEMM via FlashInfer CUTLASS (SM100+)."""
supports_pre_processed_weights = True
@classmethod
def is_supported(
cls, compute_capability: int | None = None
@@ -117,6 +119,8 @@ class FlashInferCutlassMxfp8LinearKernel(Mxfp8LinearKernel):
class FlashInferCutedslMxfp8LinearKernel(Mxfp8LinearKernel):
"""MXFP8 W8A8 GEMM via FlashInfer CuTe-DSL (SM100/SM103)."""
supports_pre_processed_weights = True
@classmethod
def is_supported(
cls, compute_capability: int | None = None
@@ -119,6 +119,18 @@ def _mxfp8_dot_scaled_linear(
return out
# Triton 3.8 enables TRITON_HIP_USE_ASYNC_COPY by default on gfx950; its extra LDS
# buffer leaves no room for num_stages=3 at BLOCK_K=256.
# TODO(rasmith)(Rohan138): Remove the 3.8 check once
# https://github.com/vllm-project/vllm/pull/50605 merges.
_BK256_STAGES = 3
if triton.__version__.startswith("3.8") and current_platform.is_rocm():
from vllm.platforms.rocm import on_gfx950
if on_gfx950():
_BK256_STAGES = 2
def _select_cfg(M, N, K):
"""(BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages) — graph-tuned on gfx950.
@@ -166,7 +178,7 @@ def _select_cfg(M, N, K):
# 3.6; on triton 3.7 its large BLOCK_M register/LDS footprint spills or hits
# "out of resources", so use 128x128x256 -- within the known-good footprint.)
if M >= 4096 and K >= 1024 and K % 256 == 0 and occ >= 256:
return 128, 128, 256, 8, 3
return 128, 128, 256, 8, _BK256_STAGES
return 128, 128, 128, 8, 3
# large-K (K >= 2048). BLOCK_K is K-divisibility-guarded (the K-loop is unmasked):
# served large-K is 2048/6144 (%256==0), but fall back to 128 (always divides, since
@@ -186,7 +198,7 @@ def _select_cfg(M, N, K):
# Covers the qkv-class local N=1536 (TP=8 qkv / TP=4 shared_gate_up) and the deep-K
# / very-large-M shapes.
if K % 256 == 0 and (1280 < N <= 1536 or (occ >= 128 and (K >= 4096 or M >= 4096))):
return 128, 128, 256, 8, 3
return 128, 128, 256, 8, _BK256_STAGES
# small local-N (e.g. TP=8 shared_gate_up N=768): a 64-wide BLOCK_N doubles the
# N-tile count -> better CU fill than 128x128 at this mid-large M (~1.4x there).
if N <= 1024 and K % 256 == 0:
@@ -200,6 +212,8 @@ _DOT_SCALED_K_ALIGN = 128
class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
"""Native CDNA4 (gfx950) MXFP8 linear via Triton ``tl.dot_scaled``."""
supports_pre_processed_weights = True
@classmethod
def is_supported(
cls, compute_capability: int | None = None
@@ -10,6 +10,7 @@ from vllm.model_executor.kernels.linear.scaled_mm.BlockScaledMMLinearKernel impo
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8BlockScaledMMKernel,
CPUFp8PerTensorScaledMMLinearKernel,
CPUFP8W8A8ScaledMMLinearKernel,
CPUInt8ScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.cutlass import (
@@ -69,5 +70,6 @@ __all__ = [
"Fp8BlockScaledMMLinearKernel",
"CPUFp8BlockScaledMMKernel",
"CPUFp8PerTensorScaledMMLinearKernel",
"CPUFP8W8A8ScaledMMLinearKernel",
"XPUFp8BlockScaledMMKernel",
]
@@ -270,12 +270,17 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
# Skip the base class process (FP8 padding / fnuz normalization)
# which is GPU-oriented. Instead, VNNI-prepack weights for AMX.
params = self._get_layer_params(layer)
packed_weight = torch.ops._C.convert_weight_packed(params.weight)
replace_parameter(
layer,
params.WEIGHT,
torch.nn.Parameter(packed_weight, requires_grad=False),
)
# MLA's kv_b_proj (see `_cpu_skip_gemm_dispatch`): MLA reads this
# weight to derive W_UK/W_UV, so keep the checkpoint [N, K] layout and
# let the kernel pack on the fly instead.
if not getattr(layer, "_cpu_skip_gemm_dispatch", False):
packed_weight = torch.ops._C.convert_weight_packed(params.weight)
replace_parameter(
layer,
params.WEIGHT,
torch.nn.Parameter(packed_weight, requires_grad=False),
)
# Re-wrap scale as a plain Parameter so the kernel can read it
# without weight-loader metadata interfering.
@@ -320,7 +325,7 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
list(self.weight_group_shape),
bias,
x.dtype,
True, # is_vnni (weight already prepacked)
not getattr(layer, "_cpu_skip_gemm_dispatch", False), # is_vnni
)
return out.reshape(x.shape[:-1] + (out.size(-1),)) if x.dim() > 2 else out
@@ -430,3 +435,294 @@ class CPUFp8PerTensorScaledMMLinearKernel(FP8ScaledMMLinearKernel):
raise NotImplementedError(
"CPUFp8PerTensorScaledMMLinearKernel overrides apply_weights directly."
)
class CPUFp8W8A8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
"""FP8 W8A8 block-quantized GEMM with dynamic per-token activation quant on CPU."""
# Activation quant is done inside fp8_scaled_mm_with_quant;
# the base class must not apply a second quant step.
apply_input_quant = False
@classmethod
def is_supported(
cls, compute_capability: int | None = None
) -> tuple[bool, str | None]:
if not current_platform.is_cpu():
return False, "requires CPU platform."
if not torch.cpu._is_amx_tile_supported():
return False, "requires AMX tile support (Sapphire Rapids or newer)."
if not ops.cpu_has_amx_fp8():
return False, (
"requires native AMX-FP8 hardware; falls back "
"to CPUFp8BlockScaledMMKernel (W8A16) otherwise."
)
return True, None
@classmethod
def can_implement(
cls, config: FP8ScaledMMLinearLayerConfig
) -> tuple[bool, str | None]:
# Same block-shape requirements as the W8A16 sibling kernel.
weight_gs = config.weight_quant_key.scale.group_shape
if weight_gs.col <= 0 or weight_gs.col != 128:
return False, (
"CPU FP8 W8A8 block kernel requires K-dimension block size of 128, "
f"got {weight_gs.col}."
)
if weight_gs.row <= 0 or weight_gs.row % 32 != 0:
return False, (
"CPU FP8 W8A8 block kernel requires N-dimension block size to be "
f"a positive multiple of 32, got {weight_gs.row}."
)
if config.out_dtype not in (torch.bfloat16, torch.float32):
return False, "Only bfloat16/float32 output dtype supported."
n = config.weight_shape[0]
if n % 32 != 0:
# float8_linear_prepack_cpu tiles N in chunks of 32 and cannot
# handle a remainder tile smaller than that.
return False, f"requires weight output dim (N={n}) to be a multiple of 32."
return True, None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
"""Prepack block-quantized FP8 weight for W8A8 AMX BRGEMM.
For block-quant FP8 models weight is stored as [N, K] (NOT transposed,
unlike non-block FP8 where vLLM stores [K, N]).
float8_linear_prepack_cpu expects:
weight: [N, K]
scales: [N, G] where G = K / block_k
weight_scale_inv from the checkpoint has shape [ceil(N/block_n), G],
so we expand rows from ceil(N/block_n) to N via repeat_interleave.
"""
params = self._get_layer_params(layer)
weight = params.weight # [N, K]
# MLA's kv_b_proj (see `_cpu_skip_gemm_dispatch`): MLA reads this
# weight to derive W_UK/W_UV, so keep the checkpoint [N, K] layout and
# its block scales; apply_weights falls back to the W8A16 op.
if getattr(layer, "_cpu_skip_gemm_dispatch", False):
return
weight_scale = (
params.weight_scale_inv
if params.weight_scale_inv is not None
else params.weight_scale
) # [ceil(N/block_n), ceil(K/block_k)]
assert weight_scale is not None, "FP8 W8A8 block kernel requires weight scale."
N = weight.shape[0]
block_n = self.weight_group_shape.row # e.g. 128
# Expand scale rows: [ceil(N/block_n), G] → [N, G]
if weight_scale.size(0) != N:
weight_scale_expanded = weight_scale.repeat_interleave(block_n, dim=0)[
:N, :
].contiguous()
else:
weight_scale_expanded = weight_scale.contiguous()
packed_weight, packed_scales = torch.ops._C.float8_linear_prepack_cpu(
weight, weight_scale_expanded.to(torch.float32)
)
scale_attr = (
params.WEIGHT_SCALE_INV
if params.weight_scale_inv is not None
else params.WEIGHT_SCALE
)
replace_parameter(
layer,
params.WEIGHT,
torch.nn.Parameter(packed_weight, requires_grad=False),
)
replace_parameter(
layer,
scale_attr,
torch.nn.Parameter(packed_scales, requires_grad=False),
)
def apply_weights(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor:
params = self._get_layer_params(layer)
weight_scale = (
params.weight_scale_inv
if params.weight_scale_inv is not None
else params.weight_scale
)
x_2d = x.reshape(-1, x.shape[-1]) if x.dim() > 2 else x
if getattr(layer, "_cpu_skip_gemm_dispatch", False):
# Unpacked weight: fp8_scaled_mm_with_quant has no is_vnni option,
# so fall back to the W8A16 op (BF16 activation, block-scaled FP8
# weight) for this layer.
out = torch.ops._C.fp8_scaled_mm_cpu(
x_2d,
params.weight,
weight_scale,
list(self.weight_group_shape),
bias,
x.dtype,
False, # is_vnni
)
return out.reshape(x.shape[:-1] + (out.size(-1),)) if x.dim() > 2 else out
# act_scales=None + channelwise=True → dynamic per-token activation quant
out = ops.fp8_scaled_mm_with_quant(
x_2d,
None,
True,
params.weight,
weight_scale,
bias,
x.dtype,
)
return out.reshape(x.shape[:-1] + (out.size(-1),)) if x.dim() > 2 else out
def apply_block_scaled_mm(
self,
A: torch.Tensor,
B: torch.Tensor,
As: torch.Tensor,
Bs: torch.Tensor,
) -> torch.Tensor:
raise NotImplementedError(
"CPUFp8W8A8BlockScaledMMKernel overrides apply_weights directly."
)
class CPUFP8W8A8ScaledMMLinearKernel(FP8ScaledMMLinearKernel):
"""FP8 W8A8 GEMM with dynamic per-token activation quantization on CPU."""
@classmethod
def is_supported(
cls, compute_capability: int | None = None
) -> tuple[bool, str | None]:
if not current_platform.is_cpu():
return False, "requires CPU platform."
if not torch.cpu._is_amx_tile_supported():
return False, "requires AMX tile support (Sapphire Rapids or newer)."
if not ops.cpu_has_amx_fp8():
return False, (
"requires native AMX-FP8 hardware (Diamond Rapids); falls back "
"to the Torch FP8 kernels otherwise."
)
return True, None
@classmethod
def can_implement(
cls, config: FP8ScaledMMLinearLayerConfig
) -> tuple[bool, str | None]:
if config.out_dtype not in (torch.bfloat16, torch.float16, torch.float32):
return False, "Only bfloat16/float16/float32 output dtype supported."
# Reject block-quantized weights — those go to CPUFp8BlockScaledMMKernel
weight_gs = config.weight_quant_key.scale.group_shape
if weight_gs.col > 0 and weight_gs.row > 0:
return False, "Block-quantized weights not handled by FP8 W8A8 kernel."
n = config.weight_shape[0]
if n % 32 != 0:
# float8_linear_prepack_cpu tiles N in chunks of 32 and cannot
# handle a remainder tile smaller than that.
return False, f"requires weight output dim (N={n}) to be a multiple of 32."
return True, None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
"""Prepack weights with float8_linear_prepack_cpu (VNNI + block layout)."""
w_name, ws_name, xs_name, _ = self.layer_param_names
weight = getattr(layer, w_name)
weight_scale = getattr(layer, ws_name)
# vLLM stores linear weight as [K, N], while the CPU prepack op expects [N, K].
N = weight.shape[-1]
# Ensure scale is 2D [N, G]
ws = weight_scale
if ws is None:
raise RuntimeError("FP8 W8A8 kernel requires weight scale.")
ws = ws.to(torch.float32)
# Fused modules may carry per-shard scales (e.g. QKV/MLP shards).
# Expand those to per-output-channel scales before prepack.
if (
len(getattr(layer, "logical_widths", [])) > 1
and ws.dim() <= 1
and ws.numel() == len(layer.logical_widths)
):
ws = convert_to_channelwise(ws.reshape(-1), layer.logical_widths)
if ws.dim() == 0:
ws = ws.view(1, 1).expand(N, 1)
elif ws.dim() == 1:
if ws.numel() == 1:
ws = ws.view(1, 1).expand(N, 1)
elif ws.numel() == N:
ws = ws.unsqueeze(1) # [N] -> [N, 1]
else:
raise RuntimeError(
"FP8 W8A8 kernel got unsupported 1D weight scale shape: "
f"{tuple(ws.shape)} for N={N}."
)
# Align scale rows to output channels N.
if ws.size(0) != N:
if ws.size(0) == 1:
ws = ws.expand(N, ws.size(1)).contiguous()
else:
raise RuntimeError(
"FP8 W8A8 kernel got mismatched weight scale rows: "
f"ws_rows={ws.size(0)}, expected N={N}."
)
w_2d = weight.t().contiguous() # [N, K]
packed_weight, packed_scales = torch.ops._C.float8_linear_prepack_cpu(w_2d, ws)
replace_parameter(
layer,
w_name,
torch.nn.Parameter(packed_weight, requires_grad=False),
)
replace_parameter(
layer,
ws_name,
torch.nn.Parameter(packed_scales, requires_grad=False),
)
def apply_weights(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor:
w_name, ws_name, xs_name, _ = self.layer_param_names
weight = getattr(layer, w_name)
weight_scale = getattr(layer, ws_name)
# For static quantization, use pre-computed activation scale
act_scales = getattr(layer, xs_name, None) if xs_name else None
x_2d = x.reshape(-1, x.shape[-1]) if x.dim() > 2 else x
# channelwise=True: per-token (per-row) quantization when act_scales is None
# channelwise=False: per-tensor quantization when act_scales is provided
channelwise = act_scales is None
out = ops.fp8_scaled_mm_with_quant(
x_2d,
act_scales,
channelwise,
weight,
weight_scale,
bias,
x.dtype,
)
return out.reshape(x.shape[:-1] + (out.size(-1),)) if x.dim() > 2 else out
def apply_scaled_mm(self, A, B, out_dtype, As, Bs, bias=None, **kwargs):
raise NotImplementedError(
"CPUFP8W8A8ScaledMMLinearKernel uses apply_weights directly."
)
+8 -2
View File
@@ -129,8 +129,11 @@ class SiluAndMul(CustomOp):
super().__init__(compile_native=compile_native)
if (
current_platform.is_cuda_alike()
or current_platform.is_cpu()
or current_platform.is_xpu()
or (
current_platform.is_cpu()
and current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC
)
):
self.op = torch.ops._C.silu_and_mul
@@ -424,8 +427,11 @@ class GeluAndMul(CustomOp):
raise ValueError(f"Unknown approximate mode: {approximate}")
if (
current_platform.is_cuda_alike()
or current_platform.is_cpu()
or current_platform.is_xpu()
or (
current_platform.is_cpu()
and current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC
)
):
if approximate == "none":
self.op = torch.ops._C.gelu_and_mul
@@ -1055,7 +1055,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
mqa_q_nope,
self.impl._w_uk_packed, # type: ignore[attr-defined]
True,
None,
self.impl._w_scale, # type: ignore[attr-defined]
)
mqa_ql_nope = mqa_ql_nope.transpose(0, 1)
else:
@@ -1401,7 +1401,7 @@ class MLAAttention(nn.Module, AttentionLayerBase):
x,
self.impl._w_uv_packed, # type: ignore[attr-defined]
True,
None,
self.impl._w_scale, # type: ignore[attr-defined]
)
else:
# Multiply + Transpose (N, B, L) x (N, L, V)->(N, B, V)->(B, N, V)
@@ -35,6 +35,7 @@ from vllm.platforms import current_platform
from vllm.utils.import_utils import (
has_deep_ep,
has_deep_ep_v2,
has_moonep,
has_mori,
has_nixl_ep,
)
@@ -103,6 +104,13 @@ if current_platform.is_cuda_alike():
NIXL_EP_QUANT_BLOCK_SHAPE,
NixlEPPrepareAndFinalize,
)
if has_moonep():
from .prepare_finalize.moonep import (
MOONEP_DEFAULT_NUM_PREFETCH_SLOTS,
MOONEP_DEFAULT_NUM_SMS,
MOONEP_DEFAULT_TOKEN_PADDING,
MoonEPPrepareAndFinalize,
)
def get_ep_all2all_manager(
@@ -279,6 +287,28 @@ def maybe_make_prepare_finalize(
sp_size=moe.moe_parallel_config.sp_size,
)
elif moe.use_moonep_kernels:
all_to_all_args = dict(
max_num_tokens_per_dp_rank=moe.max_num_tokens,
token_hidden_size=moe.hidden_dim,
num_topk=moe.experts_per_token,
num_global_experts=moe.num_experts,
num_prefetch_slots=MOONEP_DEFAULT_NUM_PREFETCH_SLOTS,
token_padding=MOONEP_DEFAULT_TOKEN_PADDING,
num_sms=MOONEP_DEFAULT_NUM_SMS,
)
handle = all2all_manager.get_handle(all_to_all_args)
# The [E+B] weight layout is picked up from the experts (their
# process_weights_after_loading hook) once the layer has loaded and
# converted its weights.
prepare_finalize = MoonEPPrepareAndFinalize(
buffer_pool=handle,
max_tokens_per_rank=moe.max_num_tokens,
num_dispatchers=all2all_manager.world_size,
num_global_experts=moe.num_experts,
)
elif moe.use_mori_kernels:
assert quant_config is not None
@@ -1085,6 +1085,10 @@ class FusedMoEParallelConfig:
def use_deepep_v2_kernels(self):
return self.use_all2all_kernels and self.all2all_backend == "deepep_v2"
@property
def use_moonep_kernels(self):
return self.use_all2all_kernels and self.all2all_backend == "moonep"
@staticmethod
def flatten_tp_across_dp_and_pcp(
tp_size: int, dp_size: int, dp_rank: int, pcp_size: int, pcp_rank: int
@@ -1309,6 +1313,8 @@ class FusedMoEConfig:
# Set by __post_init__
intermediate_size_per_partition: int = -1
# Use the allocated width as the checkpoint TP stride, including for scales.
tp_shard_with_padding: bool = False
rocm_aiter_fmoe_enabled: bool = False
aiter_fmoe_shared_expert_enabled: bool = False
@@ -1471,6 +1477,10 @@ class FusedMoEConfig:
def use_deepep_v2_kernels(self):
return self.moe_parallel_config.use_deepep_v2_kernels
@property
def use_moonep_kernels(self):
return self.moe_parallel_config.use_moonep_kernels
@property
def needs_round_robin_routing_tables(self):
return self.moe_parallel_config.needs_round_robin_routing_tables
@@ -393,12 +393,13 @@ def _fwd_kernel_ep_gather(
source_token_index = tl.load(
input_index + cur_token * input_index_stride0 + topk_index
)
source_token_index_i64 = source_token_index.to(tl.int64)
acc_weight = tl.load(
recv_topk_weight + cur_token * recv_topk_weight_stride0 + topk_index
)
tmp = tl.load(
input_tensor
+ source_token_index * input_tensor_stride0
+ source_token_index_i64 * input_tensor_stride0
+ cur_block * BLOCK_D
+ off_d
)
@@ -11,6 +11,7 @@ import math
import torch
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm._aiter_ops import rocm_aiter_ops
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.experts.mxfp8_emulation_moe import (
@@ -24,41 +25,6 @@ _AITER_SWIGLU_ALPHA = 1.702
_AITER_SWIGLU_BETA = 1.0
def is_aiter_mxfp8_moe_available() -> bool:
"""True when the FlyDSL MXFP8 MoE can run here: gfx950, the ``flydsl``
package is importable, AND the installed aiter carries the mxfp8 FlyDSL
2-stage support from ROCm/aiter#3811.
``flydsl`` and ``aiter`` are separate packages, so ``is_flydsl_available()``
(flydsl pkg + arch) is necessary but not sufficient: an older aiter without
#3811 still ships the flydsl pkg and the ``aiter.ops.flydsl`` module but a
broken/missing ``per_1x32 + fp8`` 2-stage path. Without this extra gate a
nightly lacking #3811 would wrongly select FlyDSL instead of falling back to
the native Triton dot_scaled path. #3811 added no probe-able public symbol,
so detect the ``minimax_m3_mxfp8`` tuned config it shipped. Every check fails
closed (returns False -> triton dot_scaled), which is always safe."""
if not (current_platform.is_rocm() and current_platform.supports_mx()):
return False
try:
import os
import aiter
from aiter.ops.flydsl.utils import is_flydsl_available
if not is_flydsl_available():
return False
return os.path.exists(
os.path.join(
os.path.dirname(aiter.__file__),
"configs",
"model_configs",
"minimax_m3_mxfp8_tuned_fmoe.csv",
)
)
except Exception:
return False
class AiterMxfp8Experts(Mxfp8TritonExpertsBase):
"""MXFP8 MoE through AITER's FlyDSL two-stage grouped GEMM (gfx950)."""
@@ -79,10 +45,7 @@ class AiterMxfp8Experts(Mxfp8TritonExpertsBase):
@staticmethod
def _supports_current_device() -> bool:
# Device capability only (gfx950 / MX-capable ROCm). The flydsl package
# check lives in is_supported_config so a missing package is reported
# distinctly from an unsupported device.
return current_platform.is_rocm() and current_platform.supports_mx()
return current_platform.supports_mx() and rocm_aiter_ops.is_fused_moe_enabled()
@staticmethod
def _supports_parallel_config(moe_parallel_config) -> bool:
@@ -95,12 +58,6 @@ class AiterMxfp8Experts(Mxfp8TritonExpertsBase):
is_supported, reason = super().is_supported_config(
cls, moe_config, weight_key, activation_key, activation_format
)
# _supports_current_device() only gates on the device; surface a clear
# reason when the device is fine but the flydsl package is missing.
if is_supported and not is_aiter_mxfp8_moe_available():
return False, (
"kernel requires the aiter flydsl package, which is not installed"
)
if (
is_supported
and moe_config.activation != MoEActivation.SWIGLUOAI_UNINTERLEAVE
@@ -15,6 +15,7 @@ from vllm._custom_ops import (
convert_weight_packed_scale_zp,
cpu_fused_moe,
cpu_fused_moe_int8,
cpu_has_amx_fp8,
cpu_prepack_moe_weight,
cpu_prepack_moe_weight_int8,
fused_experts_cpu,
@@ -467,6 +468,7 @@ class CPUExpertsFp8(mk.FusedMoEExpertsModular):
RoutingMethodType.Default,
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.DeepSeekV3,
RoutingMethodType.DeepseekV4,
RoutingMethodType.DeepSeekV3,
]
@@ -950,6 +952,29 @@ class CPUExpertsInt4(mk.FusedMoEExpertsModular):
# ===========================================================================
def prepare_int8_moe_layer_for_cpu(
w13: torch.Tensor,
w2: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Prepack INT8 MoE weights for the current CPU architecture."""
# SMMLA packing for AArch64
if current_platform.get_cpu_architecture() == CpuArchEnum.ARM:
return (
cpu_prepack_moe_weight_int8(w13, "neon"),
cpu_prepack_moe_weight_int8(w2, "neon"),
)
# VSX packing for POWER
if current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC:
return (
cpu_prepack_moe_weight_int8(w13, "vsx"),
cpu_prepack_moe_weight_int8(w2, "vsx"),
)
# VNNI packing for x86
packed_w13 = torch.ops._C.convert_weight_packed(w13)
packed_w2 = torch.ops._C.convert_weight_packed(w2)
return packed_w13, packed_w2
class CPUExpertsInt8(mk.FusedMoEExpertsModular):
"""CPU INT8 W8A8 per-channel weight / dynamic per-token activation
modular MoE experts."""
@@ -1283,6 +1308,160 @@ class ArmCPUExpertsInt8(mk.FusedMoEExpertsModular):
)
class PowerCPUExpertsInt8(mk.FusedMoEExpertsModular):
"""POWER VSX INT8 MoE with per-token activation and channelwise weight quant."""
@property
def expects_unquantized_inputs(self) -> bool:
return True
@staticmethod
def activation_format() -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
@staticmethod
def is_supported_config(
cls: type[mk.FusedMoEExperts],
moe_config: FusedMoEConfig,
weight_key: QuantKey | None,
activation_key: QuantKey | None,
activation_format: mk.FusedMoEActivationFormat,
) -> tuple[bool, str | None]:
supported, reason = mk.FusedMoEExpertsModular.is_supported_config(
cls,
moe_config,
weight_key,
activation_key,
activation_format,
)
if not supported:
return supported, reason
if moe_config.in_dtype not in (torch.float32, torch.bfloat16):
return False, "kernel requires float32 or bfloat16 activations"
if moe_config.hidden_dim % 16 != 0:
return False, "kernel requires hidden dim divisible by 16"
if moe_config.intermediate_size_per_partition % 16 != 0:
return False, "kernel requires intermediate dim divisible by 16"
return True, None
@staticmethod
def _supports_current_device() -> bool:
return (
current_platform.is_cpu()
and current_platform.get_cpu_architecture() == CpuArchEnum.POWERPC
and hasattr(torch.ops._C, "cpu_fused_moe_int8")
)
@staticmethod
def _supports_no_act_and_mul() -> bool:
return False
@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
return activation in (
MoEActivation.SILU,
MoEActivation.SWIGLUOAI,
MoEActivation.GELU,
MoEActivation.GELU_TANH,
)
@staticmethod
def _supports_parallel_config(
moe_parallel_config: FusedMoEParallelConfig,
) -> bool:
return not moe_parallel_config.use_ep
@staticmethod
def _supports_quant_scheme(
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
return (weight_key, activation_key) == (
kInt8StaticChannelSym,
kInt8DynamicTokenSym,
)
@staticmethod
def _supports_routing_method(
routing_method: RoutingMethodType,
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
return routing_method in [
RoutingMethodType.Default,
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
]
@staticmethod
def _supports_router_logits_dtype(
router_logits_dtype: torch.dtype | None,
routing_method: RoutingMethodType,
) -> bool:
return True
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
w13 = cpu_prepack_moe_weight_int8(layer.w13_weight, "vsx")
w2 = cpu_prepack_moe_weight_int8(layer.w2_weight, "vsx")
replace_parameter(layer, "w13_weight", w13)
replace_parameter(layer, "w2_weight", w2)
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# cpu_fused_moe_int8 manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
) -> None:
# The modular prepare step applies router weights to the input when
# apply_router_weight_on_input is enabled.
assert self.w1_scale is not None
assert self.w2_scale is not None
cpu_fused_moe_int8(
output,
hidden_states,
w1,
w2,
self.w1_scale,
self.w2_scale,
self.w1_bias,
self.w2_bias,
topk_weights,
topk_ids,
activation.value,
"vsx",
skip_weighted=apply_router_weight_on_input,
)
class ZenCPUExpertsInt8(mk.FusedMoEExpertsModular):
"""AMD Zen INT8 MoE with per-token activation and channelwise weight
quantization, dispatched through zentorch."""
@@ -1435,3 +1614,218 @@ class ZenCPUExpertsInt8(mk.FusedMoEExpertsModular):
self._w1_scale_bf16,
self._w2_scale_bf16,
)
# ===========================================================================
# FP8 W8A8 MoE
# ===========================================================================
def prepare_fp8_w8a8_moe_layer_for_cpu(
w13: torch.Tensor,
w2: torch.Tensor,
w13_scale: torch.Tensor,
w2_scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Prepack FP8 W8A8 MoE weights for CPU kernel."""
E = w13.size(0)
packed_w13_list = []
packed_w13_scale_list = []
for i in range(E):
w1_exp = w13[i] # [2N, K] FP8
ws_exp = w13_scale[i] # [2N, K/128] or [2N_blocks, K/128]
# Align scale rows to weight rows if necessary (for block-128 checkpoints
# where scale may have fewer rows: [2N/128, K/128] → [2N, K/128])
if ws_exp.size(0) < w1_exp.size(0):
repeat_factor = w1_exp.size(0) // ws_exp.size(0)
ws_exp = torch.repeat_interleave(ws_exp, repeat_factor, dim=0)
ws_exp = ws_exp[: w1_exp.size(0), :].contiguous()
pw, ps = torch.ops._C.float8_linear_prepack_cpu(w1_exp, ws_exp)
packed_w13_list.append(pw)
packed_w13_scale_list.append(ps)
packed_w13 = torch.stack(packed_w13_list)
packed_w13_scale = torch.stack(packed_w13_scale_list)
# w2 uses the W8A16 path (BF16 activation × FP8 weight), VNNI packed
packed_w2 = torch.ops._C.convert_weight_packed(w2)
return packed_w13, packed_w13_scale, packed_w2, w2_scale
class CPUExpertsFp8W8A8(mk.FusedMoEExpertsModular):
"""CPU FP8 W8A8 block-quantized modular MoE experts."""
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
):
super().__init__(moe_config, quant_config)
@property
def expects_unquantized_inputs(self) -> bool:
# Receives BF16 hidden states; quantization to FP8 is done inside apply()
return True
@staticmethod
def activation_format() -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
@staticmethod
def _supports_current_device() -> bool:
# Requires native AMX-FP8 hardware.
return current_platform.is_cpu() and cpu_has_amx_fp8()
@staticmethod
def _supports_no_act_and_mul() -> bool:
return False
@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
return activation == MoEActivation.SILU
@staticmethod
def _supports_parallel_config(
moe_parallel_config: FusedMoEParallelConfig,
) -> bool:
return True
@staticmethod
def _supports_quant_scheme(
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
# Block-quantized FP8.
return (weight_key, activation_key) == (
kFp8Static128BlockSym,
kFp8Dynamic128Sym,
)
@staticmethod
def _supports_routing_method(
routing_method: RoutingMethodType,
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
return routing_method in [
RoutingMethodType.Default,
RoutingMethodType.Renormalize,
RoutingMethodType.RenormalizeNaive,
RoutingMethodType.DeepSeekV3,
RoutingMethodType.DeepseekV4,
]
@staticmethod
def _supports_router_logits_dtype(
router_logits_dtype: torch.dtype | None,
routing_method: RoutingMethodType,
) -> bool:
return True
def moe_problem_size(
self,
a1: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_ids: torch.Tensor,
) -> tuple[int, int, int, int, int]:
# float8_linear_prepack_cpu blocks w1 into [E, Nc, Kc, block_k, block_n],
# not the (E, N, K) layout the base implementation assumes -- N isn't
# recoverable from that shape, so read it from moe_config instead.
E = w1.shape[0]
K = a1.size(-1)
N = (
self.moe_config.intermediate_size_per_partition
* self.moe_config.w13_num_shards
)
M = a1.size(0) if a1.dim() == 2 else a1.size(1)
topk = topk_ids.size(1)
return E, M, N, K, topk
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# fused_experts_cpu manages its own scratch space.
return (0,), (0,), (M, K)
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
) -> None:
if apply_router_weight_on_input:
# fused_experts_cpu always applies topk_weights internally on
# combine; MoEPrepareAndFinalizeNoDPEPModular.prepare() would
# also pre-apply it to hidden_states, double-weighting the
# output. Not needed by any CPU FP8 model today.
raise NotImplementedError(
"CPUExpertsFp8W8A8 does not support apply_router_weight_on_input=True."
)
block_shape = (
list(self.quant_config.block_shape)
if self.quant_config.block_shape
else (
[
self.quant_config._w1.shape.row,
self.quant_config._w1.shape.col,
]
if self.quant_config._w1.shape is not None
else None
)
)
# Quantize hidden_states (BF16) → FP8 with per-token scales
hidden_states_2d = hidden_states.reshape(-1, hidden_states.shape[-1])
x_fp8, x_scales = torch.ops._C.quantize_fp8e4m3_vec(
hidden_states_2d, True, None
)
fused_experts_cpu(
output,
x_fp8,
w1,
w2,
topk_weights,
topk_ids,
CPUQuantMethod.FP8_W8A8,
self.w1_scale, # w1_scale
self.w2_scale, # w2_scale
None, # w1_zero
None, # w2_zero
block_shape, # block_size
None, # w1_bias
None, # w2_bias
None, # alpha
None, # limit
True, # is_vnni
x_scales, # a1_scale: per-token FP8 activation scales
)
@@ -50,6 +50,21 @@ from vllm.utils.import_utils import has_deep_gemm
logger = init_logger(__name__)
def _fp8_workspace_shape(
num_rows: int, num_columns: int, workspace_dtype: torch.dtype
) -> tuple[int, int]:
"""Size an FP8 byte buffer stored in a workspace of another dtype."""
bytes_per_workspace_element = workspace_dtype.itemsize
fp8_columns_per_workspace_element = (
bytes_per_workspace_element // torch.float8_e4m3fn.itemsize
)
assert bytes_per_workspace_element % torch.float8_e4m3fn.itemsize == 0
return (
num_rows,
-(-num_columns // fp8_columns_per_workspace_element),
)
def _valid_deep_gemm_shape(M: int, N: int, K: int) -> bool:
align = get_mk_alignment_for_contiguous_layout()[0]
return align <= M and N % align == 0 and K % align == 0
@@ -216,7 +231,14 @@ class DeepGemmExperts(mk.FusedMoEExpertsModular):
assert M_sum % align_used == 0
activation_out_dim = self.adjust_N_for_activation(N, activation)
workspace1 = (M_sum, max(activation_out_dim, K))
# workspace1 is allocated in the activation dtype by the workspace
# manager, but is only ever viewed and used as FP8 in apply(). Size it
# by bytes instead of reserving one BF16/FP16 element per FP8 element.
workspace1 = _fp8_workspace_shape(
M_sum,
max(activation_out_dim, K),
self.workspace_dtype(self.moe_config.in_dtype),
)
workspace2 = (M_sum, max(N, K))
output = (M, K)
return (workspace1, workspace2, output)
@@ -480,7 +502,14 @@ class DeepGemmFP4Experts(mk.FusedMoEExpertsModular):
assert M_sum % align_used == 0
activation_out_dim = self.adjust_N_for_activation(N, activation)
workspace1 = (M_sum, max(activation_out_dim, K))
# workspace1 holds the permuted and requantized FP8 activations. The
# workspace manager allocates it in the model activation dtype, so
# account for the dtype sizes rather than overallocating BF16/FP16.
workspace1 = _fp8_workspace_shape(
M_sum,
max(activation_out_dim, K),
self.workspace_dtype(self.moe_config.in_dtype),
)
workspace2 = (M_sum, max(N, K))
output = (M, K)
return (workspace1, workspace2, output)
@@ -0,0 +1,220 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""MoonEP experts: grouped GEMM over MoonEP's expert-grouped activations.
MoonEP dispatch delivers tokens already contiguous per weight row
(``[NvS, H]`` in ``cu_seqlens[E+B]`` segment order), so the expert compute
is three grouped GEMMs over those segments with no permute/unpermute:
gate = grouped_mm(x, w_gate[E+B]) # [NvS, I]
up = grouped_mm(x, w_up[E+B]) # [NvS, I]
act = silu(gate) * up * route_weight # route weights applied here
out = grouped_mm(act, w_down[E+B]) # [NvS, H]
Rows ``[E, E+B)`` are the redundant-expert prefetch slots that
``MoonEPPrepareAndFinalize`` fills before ``apply`` runs. Empty segments
(including unused prefetch slots) are skipped by the grouped GEMM.
Weight layout: MoonEP's ``prefetch_weight`` requires each projection to be
its own contiguous ``[E+B, ., .]`` tensor, so gate and up are separate
tensors rather than vLLM's interleaved ``[E, 2I, H]`` ``w13``. The modular
kernel passes ``w1``/``w2`` from the layer (``w1`` is the gate tensor); the
full layout is picked up from the layer in ``process_weights_after_loading``
and shared with ``MoonEPPrepareAndFinalize`` via ``post_init_setup``.
"""
import torch
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.config import (
FusedMoEConfig,
FusedMoEParallelConfig,
FusedMoEQuantConfig,
)
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
from vllm.platforms import current_platform
def moonep_grouped_gemm(
a: torch.Tensor,
w: torch.Tensor,
cu_seqlens: torch.Tensor,
) -> torch.Tensor:
"""``out[seg_g] = a[seg_g] @ w[g].T`` for each ``cu_seqlens`` segment.
Args:
a: ``[NvS, K]`` activations in segment order.
w: ``[G, N, K]`` weights (vLLM ``[E, N, K]`` convention).
cu_seqlens: ``[G]`` int32 cumulative segment end offsets.
Returns:
``[NvS, N]``; rows past ``cu_seqlens[-1]`` are zero-filled.
"""
return torch._grouped_mm(a, w.transpose(1, 2), offs=cu_seqlens)
class MoonEPExperts(mk.FusedMoEExpertsModular):
"""Grouped-GEMM experts over MoonEP's ``[NvS, H]`` layout (BF16)."""
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
max_num_tokens: int | None = None,
num_dispatchers: int | None = None,
):
super().__init__(moe_config, quant_config, max_num_tokens, num_dispatchers)
assert quant_config.quant_dtype is None, (
"MoonEPExperts supports unquantized BF16 only"
)
if (
quant_config.gemm1_alpha is not None
or quant_config.gemm1_beta is not None
or quant_config.gemm1_clamp_limit is not None
):
raise NotImplementedError(
"MoonEPExperts implements plain silu(gate) * up only; SwiGLU "
"variants with alpha/beta/clamp parameters are not supported"
)
self._weight_layout = None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
# The [E+B] gate/up/down layout built by
# convert_to_unquantized_kernel_format; MoonEPPrepareAndFinalize
# reads it from here (post_init_setup) for weight prefetch.
layout = getattr(layer, "_moonep_weight_layout", None)
assert layout is not None, (
"MoonEPExperts requires the layer to carry _moonep_weight_layout "
"(set by convert_to_unquantized_kernel_format)"
)
self._weight_layout = layout
@property
def weight_layout(self):
return self._weight_layout
@staticmethod
def activation_format() -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
@staticmethod
def _supports_current_device() -> bool:
return current_platform.is_cuda()
@staticmethod
def _supports_no_act_and_mul() -> bool:
return False
@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
return activation == MoEActivation.SILU
@staticmethod
def _supports_parallel_config(moe_parallel_config: FusedMoEParallelConfig) -> bool:
# EPLB rearranges the named expert parameters as local_num_experts
# rows, which does not understand the replicated [E+B] layout.
return (
moe_parallel_config.use_moonep_kernels
and not moe_parallel_config.enable_eplb
)
@staticmethod
def _supports_quant_scheme(
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
return weight_key is None and activation_key is None
def supports_chunking(self) -> bool:
# NvS is static and segments must stay whole.
return False
def supports_expert_map(self) -> bool:
# MoonEP addresses global expert rows directly.
return False
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
def moe_problem_size(
self,
a1: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_ids: torch.Tensor,
) -> tuple[int, int, int, int, int]:
# a1 is [NvS, H] in segment order, not token-major, so the base
# implementation's topk_ids/a1 row-count check does not apply.
assert a1.dim() == 2 and w1.dim() == 3 and w2.dim() == 3
num_rows, intermediate, hidden = w1.shape # [E+B, I, H]
assert a1.size(1) == hidden
return num_rows, a1.size(0), intermediate, hidden, topk_ids.size(1)
def workspace_shapes(
self,
M: int,
N: int,
K: int,
topk: int,
global_num_experts: int,
local_num_experts: int,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
activation: MoEActivation,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
# M is NvS. torch._grouped_mm allocates its own outputs, so no
# workspaces are needed.
return ((0,), (0,), (M, K))
def apply(
self,
output: torch.Tensor,
hidden_states: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
activation: MoEActivation,
global_num_experts: int,
expert_map: torch.Tensor | None,
a1q_scale: torch.Tensor | None,
a2_scale: torch.Tensor | None,
workspace13: torch.Tensor,
workspace2: torch.Tensor,
expert_tokens_meta: mk.ExpertTokensMetadata | None,
apply_router_weight_on_input: bool,
) -> None:
# expert_map is ignored: MoonEP dispatches on global expert ids and
# the weights are addressed by global [E+B] row, on every rank.
assert activation == MoEActivation.SILU
assert self._weight_layout is not None, (
"process_weights_after_loading() not called"
)
assert expert_tokens_meta is not None
# MoonEPPrepareAndFinalize returns route weights in NvS order as the
# dispatched topk_weights, and per-row segment lengths as
# expert_tokens_meta.
route_weights_nvs = topk_weights
assert route_weights_nvs.dim() == 1
cu_seqlens = torch.cumsum(
expert_tokens_meta.expert_num_tokens, dim=0, dtype=torch.int32
)
assert cu_seqlens.numel() == w1.size(0)
gate = moonep_grouped_gemm(hidden_states, w1, cu_seqlens)
up = moonep_grouped_gemm(
hidden_states, self._weight_layout.full_up_weight, cu_seqlens
)
act = torch.nn.functional.silu(gate)
act.mul_(up)
if not apply_router_weight_on_input:
# Input-weighted routing (top-1, e.g. Llama 4) was already
# applied to the activations by prepare(), before dispatch.
act.mul_(route_weights_nvs.to(act.dtype).unsqueeze(-1))
# Padding rows past the last segment come out zero-filled.
output.copy_(moonep_grouped_gemm(act, w2, cu_seqlens))
@@ -130,10 +130,18 @@ class TritonExperts(LoRAExpertsMixin, mk.FusedMoEExpertsModular):
# INT8 requires at least 7.5 (Turing) on CUDA. ROCm CDNA GPUs
# (e.g. MI2xx/MI3xx/gfx950) provide native INT8 matrix-core support and
# the Triton int8_w8a8 fused MoE kernel handles them.
# XPU reaches the same Triton kernel through the same launcher, and both
# int8 activation-quant paths work there: per-token uses the Triton
# `per_token_quant_int8`, per-tensor resolves to the XPU branch of
# `scaled_int8_quant`, which is plain elementwise arithmetic.
device_supports_int8 = (
current_platform.is_cuda()
and current_platform.has_device_capability((7, 5))
) or current_platform.is_rocm()
(
current_platform.is_cuda()
and current_platform.has_device_capability((7, 5))
)
or current_platform.is_rocm()
or current_platform.is_xpu()
)
supported: list[tuple[QuantKey | None, QuantKey | None]] = [(None, None)]
if device_supports_int8:
@@ -596,9 +604,9 @@ class TritonWNA16Experts(TritonExperts):
) -> bool:
SUPPORTED_W = [
kInt4Static,
kInt4StaticAsym,
kInt8Static,
kInt4Static32,
kInt4StaticAsym,
kInt4Static32Asym,
# other group sizes?
]
@@ -31,6 +31,15 @@ from vllm.platforms import current_platform
from vllm.utils.flashinfer import has_flashinfer_trtllm_fused_moe
def view_as_block_major_k(weight: torch.Tensor) -> torch.Tensor:
"""View packed storage, including legacy 4D IPC cache entries."""
if weight.ndim == 4:
return weight
experts, rows, cols = weight.shape
block_k = 128 // weight.element_size()
return weight.view(experts, cols // block_k, rows, block_k)
class TrtLlmBf16ExpertsBase:
"""BF16 unquantized TRTLLM-Gen MoE kernels. Shared base for modular and
monolithic interfaces.
@@ -200,8 +209,8 @@ class TrtLlmBf16ExpertsModular(TrtLlmBf16ExpertsBase, mk.FusedMoEExpertsModular)
result = flashinfer.fused_moe.trtllm_bf16_routed_moe(
topk_ids=(topk_ids, topk_weights),
hidden_states=hidden_states,
gemm1_weights=w1,
gemm2_weights=w2,
gemm1_weights=view_as_block_major_k(w1),
gemm2_weights=view_as_block_major_k(w2),
num_experts=global_num_experts,
top_k=topk_ids.size(1),
n_group=None,
@@ -281,8 +290,8 @@ class TrtLlmBf16ExpertsMonolithic(TrtLlmBf16ExpertsBase, mk.FusedMoEExpertsMonol
routing_logits=router_logits,
routing_bias=e_score_correction_bias,
hidden_states=hidden_states,
gemm1_weights=w1,
gemm2_weights=w2,
gemm1_weights=view_as_block_major_k(w1),
gemm2_weights=view_as_block_major_k(w2),
num_experts=global_num_experts,
top_k=self.topk,
n_group=num_expert_group,
@@ -34,6 +34,9 @@ from vllm.model_executor.layers.fused_moe.experts.lora_context import MoELoRACon
from vllm.model_executor.layers.fused_moe.experts.lora_experts_mixin import (
LoRAExpertsMixin,
)
from vllm.model_executor.layers.fused_moe.experts.trtllm_bf16_moe import (
view_as_block_major_k,
)
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
@@ -527,8 +530,8 @@ class TrtLlmBf16LoRAExperts(_TrtLlmLoRAExpertsBase):
ret = flashinfer.fused_moe.trtllm_bf16_routed_moe(
topk_ids=topk_ids_and_weights,
hidden_states=hidden_states,
gemm1_weights=w1,
gemm2_weights=w2,
gemm1_weights=view_as_block_major_k(w1),
gemm2_weights=view_as_block_major_k(w2),
gemm1_lora_delta=gemm1_lora_delta,
num_experts=global_num_experts,
top_k=self.topk,
@@ -137,6 +137,7 @@ def FusedMoEFactory(
runner_args: dict[str, Any] | None = None,
routed_experts_cls: type[RoutedExperts] | None = None,
routed_experts_args: dict[str, Any] | None = None,
skip_padding: bool = False,
) -> MoERunner:
"""Factory function for creating MoE execution pipeline.
@@ -213,6 +214,7 @@ def FusedMoEFactory(
runner_args: Additional arguments for runner constructor
routed_experts_cls: Custom RoutedExperts class (None = use default)
routed_experts_args: Additional arguments for routed_experts constructor
skip_padding: Whether grouped routing should invalidate padding rows.
Returns:
MoERunner: Configured MoE execution pipeline ready for forward passes
@@ -308,6 +310,7 @@ def FusedMoEFactory(
else 1.0,
e_score_correction_bias=e_score_correction_bias,
num_fused_shared_experts=num_fused_shared_experts,
skip_padding=(skip_padding and moe_parallel_config.use_deepep_v2_kernels),
# Fused shared-expert slot weight. With apply_routed_scale_to_output
# the runner scales the combined output by routed_scaling_factor, so
# the shared slot weight must be 1/routed_scaling_factor for its net
@@ -31,11 +31,14 @@ from vllm.model_executor.layers.quantization.utils.marlin_utils_fp8 import (
prepare_fp8_moe_layer_for_marlin,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
GroupShape,
QuantKey,
create_fp8_quant_key,
kFp8Dynamic128Sym,
kFp8Static128BlockSym,
)
from vllm.platforms import current_platform
from vllm.utils.math_utils import round_up
logger = init_logger(__name__)
@@ -54,7 +57,9 @@ class Fp8MoeBackend(Enum):
VLLM_CUTLASS = "VLLM_CUTLASS"
BATCHED_VLLM_CUTLASS = "BATCHED_VLLM_CUTLASS"
XPU = "XPU"
# CPU FP8 W8A16 (BF16 activations); CPU_W8A8 needs native AMX-FP8.
CPU = "CPU"
CPU_W8A8 = "CPU_W8A8"
HPC = "HPC"
# Dequantize-to-BF16 emulation for MXFP8 on devices without a native
# MXFP8 MoE kernel (e.g. ROCm). Weights pass through unchanged here.
@@ -89,6 +94,7 @@ def _get_priority_backends(
Fp8MoeBackend.BATCHED_VLLM_CUTLASS,
Fp8MoeBackend.BATCHED_TRITON,
Fp8MoeBackend.XPU,
Fp8MoeBackend.CPU_W8A8,
Fp8MoeBackend.CPU,
Fp8MoeBackend.HPC,
]
@@ -126,8 +132,10 @@ def _get_priority_backends(
_move_to_front(_AVAILABLE_BACKENDS, Fp8MoeBackend.XPU)
if current_platform.is_cpu():
# CPU platform uses FP8 W8A16 fused MoE kernel.
# W8A8 first: it falls through to the W8A16 backend whenever the
# hardware (AMX-FP8) or the config isn't supported.
_move_to_front(_AVAILABLE_BACKENDS, Fp8MoeBackend.CPU)
_move_to_front(_AVAILABLE_BACKENDS, Fp8MoeBackend.CPU_W8A8)
return _AVAILABLE_BACKENDS
@@ -235,6 +243,13 @@ def backend_to_kernel_cls(
return [CPUExpertsFp8]
elif backend == Fp8MoeBackend.CPU_W8A8:
from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
CPUExpertsFp8W8A8,
)
return [CPUExpertsFp8W8A8]
elif backend == Fp8MoeBackend.HPC:
from vllm.model_executor.layers.fused_moe.hpc_moe import (
HPCExperts,
@@ -299,6 +314,80 @@ def refine_fp8_moe_block_shape(
return [refine, refine]
def pad_tp_shard_to_weight_blocks(
config: FusedMoEConfig,
weight_block_size: list[int],
) -> bool:
"""Pad the TP shard to whole checkpoint blocks, keeping scales rank-local."""
block_n, block_k = weight_block_size
if (
block_n != block_k
or config.tp_size == 1
or config.intermediate_size_per_partition % block_n == 0
):
return False
if (
config.intermediate_size % block_n != 0
or config.hidden_dim % block_n != 0
or config.ep_size != 1
or config.is_lora_enabled
or config.has_bias
):
raise ValueError(
f"Block-aligned FP8 TP sharding requires {block_n}-aligned "
"global expert dimensions, pure TP, and no LoRA or "
"expert bias."
)
config.tp_shard_with_padding = True
config.intermediate_size_per_partition = round_up(
config.intermediate_size_per_partition, block_n
)
return True
def resolve_fp8_moe_weight_block_shape(
config: FusedMoEConfig,
weight_block_size: list[int],
activation_key: QuantKey,
is_checkpoint_fp8_serialized: bool,
) -> tuple[list[int], tuple[int, int] | None]:
"""Return the TP-adapted block shape and refine factor:
refine if kernels allow, else pad to the TP shard."""
refined_shape = refine_fp8_moe_block_shape(config, weight_block_size)
if is_checkpoint_fp8_serialized and config.moe_backend != "auto":
kernel_classes = backend_to_kernel_cls(map_fp8_backend(config.moe_backend))
can_refine = refined_shape is not None and any(
k_cls._supports_quant_scheme(
create_fp8_quant_key(
static=True, group_shape=GroupShape(*refined_shape)
),
activation_key,
)
for k_cls in kernel_classes
)
if not can_refine and pad_tp_shard_to_weight_blocks(config, weight_block_size):
logger.info_once(
"FP8 %s TP loading uses complete checkpoint blocks: "
"local allocation %d, without weight requantization.",
config.moe_backend,
config.intermediate_size_per_partition,
)
return weight_block_size, None
if refined_shape is None:
return weight_block_size, None
logger.info_once(
"FP8 MoE block scales refined from %s to %s to fit "
"the TP-sharded intermediate size %d.",
str(weight_block_size),
str(refined_shape),
config.intermediate_size_per_partition,
)
return refined_shape, (
weight_block_size[0] // refined_shape[0],
weight_block_size[1] // refined_shape[1],
)
def select_fp8_moe_backend(
config: FusedMoEConfig,
weight_key: QuantKey | None,
@@ -575,6 +664,14 @@ def convert_to_fp8_moe_kernel_format(
)
w13, w2 = prepare_fp8_moe_layer_for_cpu(w13, w2)
elif fp8_backend == Fp8MoeBackend.CPU_W8A8:
from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
prepare_fp8_w8a8_moe_layer_for_cpu,
)
w13, w13_scale, w2, w2_scale = prepare_fp8_w8a8_moe_layer_for_cpu(
w13, w2, w13_scale, w2_scale
)
else:
if fp8_backend not in [
Fp8MoeBackend.TRITON,
@@ -620,7 +717,15 @@ def make_fp8_moe_quant_config(
In a future PR, we will have this function should be
a method of the modular kernel itself.
"""
# MARLIN and CPU are mixed precision W8A16 config.
if fp8_backend == Fp8MoeBackend.CPU_W8A8:
return fp8_w8a8_moe_quant_config(
w1_scale=w1_scale,
w2_scale=w2_scale,
a1_scale=a1_scale,
block_shape=block_shape,
)
# MARLIN and CPU (W8A16) are mixed precision W8A16 configs.
if fp8_backend == Fp8MoeBackend.MARLIN or fp8_backend == Fp8MoeBackend.CPU:
return fp8_w8a16_moe_quant_config(
w1_scale=w1_scale,
@@ -71,10 +71,16 @@ def backend_to_kernel_cls(
from vllm.model_executor.layers.fused_moe.experts.cpu_moe import (
ArmCPUExpertsInt8,
CPUExpertsInt8,
PowerCPUExpertsInt8,
ZenCPUExpertsInt8,
)
return [ZenCPUExpertsInt8, ArmCPUExpertsInt8, CPUExpertsInt8]
return [
ZenCPUExpertsInt8,
PowerCPUExpertsInt8,
ArmCPUExpertsInt8,
CPUExpertsInt8,
]
else:
raise ValueError(f"Unknown Int8 MoE backend: {backend.value}")
@@ -31,7 +31,12 @@ from vllm.model_executor.layers.fused_moe.config import (
from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
swap_w13_to_w31,
)
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import _swizzle_mxfp4
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import (
_swizzle_mxfp4,
)
from vllm.model_executor.layers.quantization.utils.mxfp4_utils import (
mx_scale_kwargs as _mx_scale_kwargs,
)
from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import (
OCP_MX_BLOCK_SIZE,
)
@@ -70,15 +75,6 @@ if triton_kernels_version is not None:
)
def _mx_scale_kwargs(scale):
"""PrecisionConfig weight-scale kwargs: 3.8 uses b_mx_scale/b_microblock_size,
3.5.1/3.6 use weight_scale.
"""
if triton_kernels_version == "3.8":
return {"b_mx_scale": scale, "b_microblock_size": 32}
return {"weight_scale": scale}
def _pack_deepgemm_mxfp4_scales(
w13_weight: torch.Tensor,
w2_weight: torch.Tensor,
@@ -769,18 +765,31 @@ def mxfp4_round_up_hidden_size_and_intermediate_size(
intermediate_size = round_up(intermediate_size, 128)
hidden_size = round_up(hidden_size, 128)
elif current_platform.is_rocm():
if backend == Mxfp4MoeBackend.AITER_MXFP4_BF16 and (
activation == MoEActivation.SITU or activation == MoEActivation.SILU
):
# K3's AITER A16W4 SiTU kernel handles K3's native intermediate size
# (moe_intermediate 3072; e.g. 384/partition at TP8). Align to 128 (a
# no-op for K3's shapes) rather than the generic ROCm 256 round-up,
# which would inflate weights and OOM.
intermediate_size = round_up(intermediate_size, 128)
hidden_size = round_up(hidden_size, 128)
else:
intermediate_size = round_up(intermediate_size, 256)
hidden_size = round_up(hidden_size, 256)
from vllm.platforms.rocm import get_cdna_version
is_situ_or_silu = activation in (
MoEActivation.SITU,
MoEActivation.SILU,
)
# K3's AITER A16W4 SiTU kernel handles K3's native intermediate size
# (moe_intermediate 3072; e.g. 384/partition at TP8). Align to 128
# rather than the generic ROCm 256 round-up, which would inflate
# weights and OOM.
aiter_uses_128 = backend == Mxfp4MoeBackend.AITER_MXFP4_BF16
# matmul_ogs uses block_k=128 for MXFP4 on pre-CDNA4 GPUs.
# CDNA4's F16xMXFP4 configuration uses block_k=256.
triton_uses_128 = (
backend == Mxfp4MoeBackend.TRITON_UNFUSED and get_cdna_version() != 4
)
alignment = (
128 if is_situ_or_silu and (aiter_uses_128 or triton_uses_128) else 256
)
intermediate_size = round_up(intermediate_size, alignment)
hidden_size = round_up(hidden_size, alignment)
elif backend == Mxfp4MoeBackend.CPU:
# CPU AMX kernel uses BLOCK_N=32, align to 32
intermediate_size = round_up(intermediate_size, 32)
@@ -26,6 +26,7 @@ from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
swap_w13_to_w31,
)
from vllm.platforms import current_platform
from vllm.utils.math_utils import round_up
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
@@ -39,6 +40,7 @@ class UnquantizedMoeBackend(Enum):
AITER = "ROCm AITER"
TRITON = "TRITON"
BATCHED_TRITON = "BATCHED_TRITON"
MOONEP = "MOONEP"
CPU = "CPU"
XPU = "XPU"
TPU = "TPU"
@@ -137,6 +139,13 @@ def backend_to_kernel_cls(
return [BatchedTritonExperts]
elif backend == UnquantizedMoeBackend.MOONEP:
from vllm.model_executor.layers.fused_moe.experts.moonep_experts import (
MoonEPExperts,
)
return [MoonEPExperts]
elif backend == UnquantizedMoeBackend.XPU:
from vllm.model_executor.layers.fused_moe.experts.xpu_moe import XPUExperts
@@ -280,6 +289,13 @@ def select_unquantized_moe_backend(
return backend, k_cls
raise ValueError(_make_log_unsupported(backend, reason))
# MoonEP owns the expert layout (expert-grouped [NvS, H] + cu_seqlens),
# so it is not interchangeable with the token-major experts backends.
if moe_config.moe_parallel_config.use_moonep_kernels:
return _return_or_raise(
UnquantizedMoeBackend.MOONEP, moe_config, activation_format
)
runner_backend = moe_config.moe_backend
# 'humming' is quantization-only; an unquantized layer (e.g. excluded via
# modules_to_not_convert) falls through to auto instead of erroring.
@@ -305,7 +321,33 @@ def select_unquantized_moe_backend(
AVAILABLE_BACKENDS.remove(UnquantizedMoeBackend.AITER)
else:
backend = UnquantizedMoeBackend.AITER
return _return_or_raise(backend, moe_config, activation_format)
reason = None
for k_cls in backend_to_kernel_cls(backend):
supported, reason = k_cls.is_supported_config(
k_cls, moe_config, None, None, activation_format
)
if supported:
logger.info_once(_make_log_backend(backend))
return backend, k_cls
# AITER was explicitly requested but does not support this
# deployment configuration (e.g. a non-gated MoE activation,
# which AiterExperts._supports_no_act_and_mul() rejects
# unconditionally). Rather than hard-crashing at engine init,
# warn — explicitly stating that this is falling back, and
# which backends will be tried next — and fall back to the
# remaining backends in priority order below.
logger.warning_once(
"VLLM_ROCM_USE_AITER_MOE=1 was requested, but %s "
"Falling back to try the remaining available MoE backends: %s.",
_make_log_unsupported(backend, reason),
", ".join(
b.value
for b in AVAILABLE_BACKENDS
if b != UnquantizedMoeBackend.AITER
),
)
if UnquantizedMoeBackend.AITER in AVAILABLE_BACKENDS:
AVAILABLE_BACKENDS.remove(UnquantizedMoeBackend.AITER)
for backend in AVAILABLE_BACKENDS:
for k_cls in backend_to_kernel_cls(backend):
@@ -323,12 +365,58 @@ def select_unquantized_moe_backend(
)
def unquantized_round_up_hidden_size_and_intermediate_size(
backend: UnquantizedMoeBackend,
hidden_size: int,
intermediate_size: int,
) -> tuple[int, int]:
"""Round up dimensions before allocation to satisfy the selected kernel."""
if backend == UnquantizedMoeBackend.FLASHINFER_TRTLLM:
intermediate_size = round_up(intermediate_size, 128)
return hidden_size, intermediate_size
def convert_to_unquantized_kernel_format(
unquantized_backend: UnquantizedMoeBackend,
moe_config: FusedMoEConfig,
w13_weight: torch.Tensor,
w2_weight: torch.Tensor,
layer: torch.nn.Module | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
if unquantized_backend == UnquantizedMoeBackend.MOONEP:
if layer is None:
raise ValueError(
"MoonEP weight conversion requires the layer module to stash "
"the [E+B] weight layout on"
)
# MoonEP addresses expert weights by global [E+B] row and needs one
# contiguous tensor per projection (gate / up / down). The layer's
# w13_weight becomes the gate tensor and w2_weight the down tensor;
# the up tensor and the full layout are stashed on the layer for
# the kernel wiring in _setup_kernel.
from vllm.model_executor.layers.fused_moe.prepare_finalize.moonep import (
MOONEP_DEFAULT_NUM_PREFETCH_SLOTS,
gather_moonep_weight_layout,
)
if getattr(layer, "_moonep_weight_layout", None) is not None:
# On a reload the layer parameters were already replaced by the
# converted [E+B] gate/down tensors, so the source-format weights
# this conversion needs are gone (and the unregistered up
# projection cannot be recovered from them at all). Tracked in
# RFC #52095.
raise NotImplementedError(
"MoonEP does not support in-place weight reloads yet"
)
layout = gather_moonep_weight_layout(
w13_weight,
w2_weight,
num_global_experts=moe_config.num_experts,
num_prefetch_slots=MOONEP_DEFAULT_NUM_PREFETCH_SLOTS,
)
layer._moonep_weight_layout = layout
return layout.full_gate_weight, layout.full_down_weight
if unquantized_backend == UnquantizedMoeBackend.AITER:
w13_weight, w2_weight = rocm_aiter_ops.shuffle_weights(w13_weight, w2_weight)
w13_weight.is_shuffled = True
@@ -351,13 +439,26 @@ def convert_to_unquantized_kernel_format(
)
moe_config.intermediate_size_per_partition = padded_intermediate
# Reloads only overwrite checkpoint slices. An earlier in-place
# permutation can leave nonzero values in the raw padding slots.
unpadded = moe_config.intermediate_size_per_partition_unpadded
assert unpadded is not None
if padded_intermediate > unpadded:
w13_weight[:, unpadded:padded_intermediate].zero_()
if is_act_and_mul:
w13_weight[:, padded_intermediate + unpadded :].zero_()
w2_weight[:, :, unpadded:].zero_()
_cache_permute_indices: dict[torch.Size, torch.Tensor] = {}
w13_weight, w2_weight = convert_moe_weights_to_flashinfer_trtllm_block_layout(
convert_moe_weights_to_flashinfer_trtllm_block_layout(
_cache_permute_indices,
w13_weight,
w2_weight,
is_gated_act_gemm=is_act_and_mul,
)
# Keep checkpoint-shaped parameters for reload/IPC. The experts create
# BlockMajorK views at dispatch without changing the underlying storage.
return w13_weight, w2_weight
if (
unquantized_backend == UnquantizedMoeBackend.TRITON
@@ -471,9 +572,10 @@ class UnquantizedMoEKernelOracle(MoEKernelOracle[UnquantizedMoeBackend]):
moe_config: FusedMoEConfig,
w13_weight: torch.Tensor,
w2_weight: torch.Tensor,
layer: torch.nn.Module | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
return convert_to_unquantized_kernel_format(
backend, moe_config, w13_weight, w2_weight
backend, moe_config, w13_weight, w2_weight, layer=layer
)
def make_kernel(
@@ -0,0 +1,429 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""MoonEP (https://github.com/MoonshotAI/MoonEP) prepare/finalize.
BF16 correctness-first proof of concept on top of vLLM's modular kernel
interface.
MoonEP differs from DeepEP-style backends in two ways that shape this
integration:
- ``dispatch`` returns tokens already grouped by expert *row* (a fixed
``[NvS, H]`` layout with ``NvS = S x K`` real slots plus padding) together
with a ``cu_seqlens[E+B]`` segment table and an opaque ``plan``. There is
no per-token topk id tensor after dispatch; the expert compute must be a
grouped GEMM over ``cu_seqlens`` segments.
- Rows ``[E, E+B)`` of the weight/segment space are dynamic redundant-expert
prefetch slots. ``plan.experts_to_copy`` names the source expert of each
slot and ``Buffer.prefetch_weight`` must run between dispatch and expert
compute.
PoC limitations:
- BF16 / unquantized only, eager only.
- Expert weights are replicated in global-expert order on every rank
(memory-heavy). Production Kimi-K3 serving requires sharded
symmetric-memory expert ownership, where rows ``[0, E)`` physically alias
each home rank's parameter memory.
- Route weights are applied inside the expert compute and MoonEP's
``combine`` performs the K-sum, so ``finalize`` requires
``TopKWeightAndReduceNoOP``.
"""
from typing import Any, NamedTuple
import torch
import torch.nn.functional as F
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm.forward_context import get_forward_context
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
MOONEP_DEFAULT_NUM_PREFETCH_SLOTS = 4
MOONEP_DEFAULT_TOKEN_PADDING = 128
MOONEP_DEFAULT_NUM_SMS = 32
# MoonEP's weight-prefetch kernel tiles hidden and intermediate dims by 128.
MOONEP_WEIGHT_TILE = 128
class MoonEPExpertWeightLayout(NamedTuple):
"""Contiguous BF16 expert weights in MoonEP ``[E+B, ...]`` layout.
Rows ``[0, E)`` hold expert weights in global expert order; rows
``[E, E+B)`` are mutable prefetch slots filled by
``Buffer.prefetch_weight``.
The prefetch slots never need re-zeroing between calls: the planner
marks unused slots with ``-1`` in ``plan.experts_to_copy`` (skipped by
``prefetch_weight``) and gives them an empty ``cu_seqlens`` segment, so
stale slot contents are never read; used slots are fully overwritten.
"""
full_gate_weight: torch.Tensor
full_up_weight: torch.Tensor
full_down_weight: torch.Tensor
num_prefetch_slots: int
def make_moonep_weight_layout(
w13_weight: torch.Tensor,
w2_weight: torch.Tensor,
num_prefetch_slots: int,
) -> MoonEPExpertWeightLayout:
"""Build the replicated ``[E+B, ...]`` PoC weight layout.
``w13_weight`` must be ``[E, 2I, H]`` (gate rows first) and ``w2_weight``
``[E, H, I]``, both BF16 in global expert order.
"""
if num_prefetch_slots <= 0:
raise ValueError(
f"num_prefetch_slots must be positive, got {num_prefetch_slots}"
)
if w13_weight.dtype != torch.bfloat16 or w2_weight.dtype != torch.bfloat16:
raise NotImplementedError("MoonEP PoC supports BF16 weights only.")
num_experts, two_i, hidden_size = w13_weight.shape
intermediate_size = two_i // 2
if tuple(w2_weight.shape) != (num_experts, hidden_size, intermediate_size):
raise ValueError(
f"w2_weight shape {tuple(w2_weight.shape)} does not match "
f"w13_weight shape {tuple(w13_weight.shape)}"
)
if hidden_size % MOONEP_WEIGHT_TILE or intermediate_size % MOONEP_WEIGHT_TILE:
raise ValueError(
"MoonEP weight prefetch requires hidden_size and intermediate_size "
f"to be multiples of {MOONEP_WEIGHT_TILE}; got H={hidden_size}, "
f"I={intermediate_size}"
)
full_gate_weight = torch.empty(
num_experts + num_prefetch_slots,
intermediate_size,
hidden_size,
dtype=torch.bfloat16,
device=w13_weight.device,
)
full_up_weight = torch.empty_like(full_gate_weight)
full_down_weight = torch.empty(
num_experts + num_prefetch_slots,
hidden_size,
intermediate_size,
dtype=torch.bfloat16,
device=w2_weight.device,
)
full_gate_weight[:num_experts].copy_(w13_weight[:, :intermediate_size, :])
full_up_weight[:num_experts].copy_(w13_weight[:, intermediate_size:, :])
full_down_weight[:num_experts].copy_(w2_weight)
full_gate_weight[num_experts:].zero_()
full_up_weight[num_experts:].zero_()
full_down_weight[num_experts:].zero_()
return MoonEPExpertWeightLayout(
full_gate_weight=full_gate_weight.contiguous(),
full_up_weight=full_up_weight.contiguous(),
full_down_weight=full_down_weight.contiguous(),
num_prefetch_slots=num_prefetch_slots,
)
def gather_moonep_weight_layout(
w13_local: torch.Tensor,
w2_local: torch.Tensor,
num_global_experts: int,
num_prefetch_slots: int,
) -> MoonEPExpertWeightLayout:
"""Build the replicated ``[E+B, ...]`` layout from this rank's local experts.
PoC bridge: each EP rank loads only its own experts (linear placement),
so all-gather them once at load time into global expert order on every
rank. Production MoonEP instead maps rows ``[0, E)`` onto each home
rank's parameter memory via symmetric memory (RFC #52095 item 5).
"""
from vllm.distributed import get_ep_group
ep_group = get_ep_group()
ep_size = ep_group.world_size
if ep_size == 1:
return make_moonep_weight_layout(w13_local, w2_local, num_prefetch_slots)
if w13_local.size(0) * ep_size != num_global_experts:
raise NotImplementedError(
"MoonEP PoC requires num_experts to be evenly divisible across EP "
f"ranks: {num_global_experts} experts, {ep_size} ranks"
)
w13_global = ep_group.all_gather(w13_local.contiguous(), dim=0)
w2_global = ep_group.all_gather(w2_local.contiguous(), dim=0)
return make_moonep_weight_layout(w13_global, w2_global, num_prefetch_slots)
MOONEP_MIN_DISPATCH_TOKENS = 128
class MoonEPBufferPool:
"""Lazily creates ``moonep.Buffer`` instances at power-of-two capacities.
``Buffer`` fixes its token capacity ``S`` at construction, so a single
full-capacity buffer would pad every dispatch to
``max_num_batched_tokens``. The pool instead serves the smallest
power-of-two capacity that fits the step's token count, so decode-sized
batches dispatch a few hundred slots rather than the full capacity.
Selection must be identical on every EP rank (dispatch is collective and
``Buffer`` construction is itself a collective): callers derive the token
count from ``dp_metadata`` (the max across DP ranks) so all ranks create
and pick the same buffer at the same step.
"""
def __init__(self, buffer_kwargs: dict[str, Any], max_tokens_per_rank: int):
self._kwargs = {k: v for k, v in buffer_kwargs.items() if k != "S"}
self.max_tokens_per_rank = max_tokens_per_rank
self._buffers: dict[int, Any] = {}
def capacity_for(self, num_tokens: int) -> int:
if num_tokens >= self.max_tokens_per_rank:
return self.max_tokens_per_rank
cap = 1 << max(num_tokens - 1, 0).bit_length()
return min(max(cap, MOONEP_MIN_DISPATCH_TOKENS), self.max_tokens_per_rank)
def get(self, num_tokens: int) -> tuple[int, Any]:
"""Return ``(capacity, buffer)`` for the given step token count."""
from moonep import Buffer # type: ignore[import-not-found]
capacity = self.capacity_for(num_tokens)
buffer = self._buffers.get(capacity)
if buffer is None:
buffer = Buffer(S=capacity, **self._kwargs)
self._buffers[capacity] = buffer
return capacity, buffer
def destroy(self) -> None:
for buffer in self._buffers.values():
buffer.destroy()
self._buffers.clear()
class MoonEPPrepareAndFinalize(mk.FusedMoEPrepareAndFinalizeModular):
"""Prepare/Finalize using MoonEP balanced dispatch/combine.
``prepare`` pads the batch to the selected buffer's static token
capacity, dispatches, runs ``prefetch_weight`` for the planned redundant
experts, and stashes the ``plan`` for ``finalize`` (the same pattern
DeepEP-HT uses for its handle). Downstream expert compute must consume
the expert-grouped ``[NvS, H]`` layout via ``cu_seqlens``.
"""
def __init__(
self,
buffer_pool: "MoonEPBufferPool",
max_tokens_per_rank: int,
num_dispatchers: int,
num_global_experts: int,
weight_layout: MoonEPExpertWeightLayout | None = None,
):
super().__init__()
self.buffer_pool = buffer_pool
self.max_tokens_per_rank = max_tokens_per_rank
self.num_dispatchers_ = num_dispatchers
self.num_global_experts = num_global_experts
self.weight_layout = weight_layout
self._fused_experts: Any = None
# dispatch state consumed by finalize (and the expert runner)
self._plan: Any = None
self._cu_seqlens: torch.Tensor | None = None
self._num_tokens: int = 0
self._buffer: Any = None # the pool buffer used by the current step
def post_init_setup(self, fused_experts: mk.FusedMoEExperts) -> None:
# The [E+B] weight layout is attached to the experts by their
# process_weights_after_loading hook (after this runs), so keep the
# reference and resolve the layout lazily in prepare().
self._fused_experts = fused_experts
def _resolve_weight_layout(self) -> MoonEPExpertWeightLayout:
if self.weight_layout is None and self._fused_experts is not None:
layout = getattr(self._fused_experts, "weight_layout", None)
if isinstance(layout, MoonEPExpertWeightLayout):
self.weight_layout = layout
# Redundant experts' weights must be in rows [E, E+B) before the
# expert compute reads them; skipping prefetch silently corrupts
# output.
assert self.weight_layout is not None, (
"MoonEPPrepareAndFinalize: weight layout not available (the "
"experts' process_weights_after_loading has not run)"
)
return self.weight_layout
@property
def num_dispatched_slots(self) -> int:
"""``NvS`` of the buffer selected by the current step's prepare()."""
assert self._buffer is not None, "prepare() has not been called"
return int(self._buffer._ctx["NvS"])
def num_dispatchers(self) -> int:
return self.num_dispatchers_
def output_is_reduced(self) -> bool:
# combine returns the fully weighted+reduced token-major output
return True
@property
def activation_format(self) -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
def max_num_tokens_per_rank(self) -> int | None:
return self.max_tokens_per_rank
def topk_indices_dtype(self) -> torch.dtype | None:
return torch.int32
def supports_async(self) -> bool:
return False
@property
def cu_seqlens(self) -> torch.Tensor:
assert self._cu_seqlens is not None, "prepare() has not been called"
return self._cu_seqlens
@property
def plan(self) -> Any:
assert self._plan is not None, "prepare() has not been called"
return self._plan
def _pad_to_capacity(
self,
a1: torch.Tensor,
topk_ids: torch.Tensor,
topk_weights: torch.Tensor,
capacity: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
num_tokens = a1.shape[0]
if num_tokens > capacity:
raise ValueError(
f"MoonEP static buffer capacity exceeded: {num_tokens} tokens "
f"> S={capacity}."
)
a1 = a1.contiguous()
topk_ids = topk_ids.to(dtype=torch.int32)
topk_weights = topk_weights.to(dtype=torch.float32)
# MoonEP's planner has no sentinel for invalid expert ids, so map
# negative ids (padded/invalid slots from the engine) to expert 0
# with zero route weight — the same convention as the capacity
# padding rows below. Wasted compute, never wrong output.
invalid = topk_ids < 0
topk_ids = torch.where(invalid, torch.zeros_like(topk_ids), topk_ids)
topk_weights = torch.where(
invalid, torch.zeros_like(topk_weights), topk_weights
).contiguous()
topk_ids = topk_ids.contiguous()
if num_tokens == capacity:
return a1, topk_ids, topk_weights, num_tokens
pad = capacity - num_tokens
return (
F.pad(a1, (0, 0, 0, pad)),
F.pad(topk_ids, (0, 0, 0, pad)),
F.pad(topk_weights, (0, 0, 0, pad)),
num_tokens,
)
def prepare(
self,
a1: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
num_experts: int,
expert_map: torch.Tensor | None,
apply_router_weight_on_input: bool,
quant_config: FusedMoEQuantConfig,
defer_input_quant: bool = False,
) -> mk.PrepareResultType:
if a1.dtype != torch.bfloat16:
raise NotImplementedError("MoonEP PoC supports BF16 hidden states only.")
if quant_config.quant_dtype is not None:
raise NotImplementedError("MoonEP PoC does not support quantized dispatch.")
assert num_experts == self.num_global_experts
assert self._plan is None, (
"MoonEPPrepareAndFinalize.prepare() called again before finalize()"
)
if apply_router_weight_on_input:
assert topk_ids.size(1) == 1, (
"apply_router_weight_on_input requires top-1 routing"
)
a1 = a1 * topk_weights.to(a1.dtype)
# Buffer choice must be rank-symmetric: use the max token count
# across DP ranks (every rank sees the same dp_metadata), falling
# back to the local count outside a forward context (tests).
num_tokens = a1.shape[0]
try:
dp_meta = get_forward_context().dp_metadata
except AssertionError:
dp_meta = None
if dp_meta is not None:
num_tokens = int(dp_meta.num_tokens_across_dp_cpu.max())
capacity, self._buffer = self.buffer_pool.get(num_tokens)
a1, topk_ids, topk_weights, self._num_tokens = self._pad_to_capacity(
a1, topk_ids, topk_weights, capacity
)
tokens_per_expert = torch.bincount(
topk_ids.reshape(-1).to(dtype=torch.int64),
minlength=num_experts,
).to(dtype=torch.int32)
hidden_nvsh, route_weights_nvs, cu_seqlens, plan = self._buffer.dispatch(
a1,
topk_weights,
topk_ids,
tokens_per_expert,
)
self._plan = plan
self._cu_seqlens = cu_seqlens
weight_layout = self._resolve_weight_layout()
self._buffer.prefetch_weight(
plan=plan,
full_gate_weight=weight_layout.full_gate_weight,
full_up_weight=weight_layout.full_up_weight,
full_down_weight=weight_layout.full_down_weight,
)
# Segment sizes per [E+B] weight row. NOTE: this is per *row*, not
# per local expert, and NvS rows are expert-grouped rather than
# token-major — only MoonEP-aware expert implementations can consume
# this activation layout.
expert_num_tokens = torch.diff(cu_seqlens, prepend=cu_seqlens.new_zeros(1))
expert_tokens_meta = mk.ExpertTokensMetadata(
expert_num_tokens=expert_num_tokens,
expert_num_tokens_cpu=None,
)
# MoonEP has no post-dispatch per-token topk ids/weights; route
# weights come back in NvS order.
return hidden_nvsh, None, expert_tokens_meta, None, route_weights_nvs
def finalize(
self,
output: torch.Tensor,
fused_expert_output: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
apply_router_weight_on_input: bool,
weight_and_reduce_impl: mk.TopKWeightAndReduce,
) -> None:
# Route weights are applied in the expert compute and MoonEP's
# combine performs the K-sum, so any weight/reduce work in finalize
# means MoonEP was paired with the wrong kind of experts.
assert isinstance(weight_and_reduce_impl, TopKWeightAndReduceNoOP), (
"MoonEP requires TopKWeightAndReduceNoOP, got "
f"{type(weight_and_reduce_impl).__name__}"
)
combined, _, _ = self._buffer.combine(
plan=self.plan,
hidden_nvsh=fused_expert_output,
route_weights_nvs=None,
)
output.copy_(combined[: self._num_tokens])
self._plan = None
self._cu_seqlens = None
@@ -27,6 +27,7 @@ from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
resolve_quant_method,
)
from vllm.utils.math_utils import cdiv
if TYPE_CHECKING:
from vllm.model_executor.layers.fused_moe.runner.shared_experts import SharedExperts
@@ -332,6 +333,7 @@ class RoutedExperts(PluggableLayer):
shard_id: str,
loaded_weight: torch.Tensor,
tp_rank: int,
is_scale: bool = False,
):
"""Load grouped weight scales for group quantization or model weights
@@ -341,14 +343,41 @@ class RoutedExperts(PluggableLayer):
shard_id: either w1, w2, or w3
loaded_weight: checkpoint weight to load into the param
tp_rank: tensor parallel rank
is_scale: whether padding should use unit scales instead of zero weights.
"""
padded_tp = self.moe_config.tp_shard_with_padding
if padded_tp:
destination = expert_data
if shard_id in ("w1", "w3") and self.moe_config.is_act_and_mul:
half = destination.shape[shard_dim] // 2
destination = destination.narrow(
shard_dim, 0 if shard_id == "w1" else half, half
)
shard_size = destination.shape[shard_dim]
expected_size = (
self.moe_config.intermediate_size
* shard_size
// self.moe_config.intermediate_size_per_partition
)
if loaded_weight.shape[shard_dim] != expected_size:
raise ValueError(
"Block-aligned TP loading expects an unsharded checkpoint "
f"projection of size {expected_size}, got "
f"{loaded_weight.shape[shard_dim]}."
)
start = min(tp_rank * shard_size, expected_size)
size = min(shard_size, expected_size - start)
loaded_weight = loaded_weight.narrow(shard_dim, start, size)
destination.fill_(1 if is_scale else 0)
if shard_id == "w2":
self._load_w2(
shard_dim=shard_dim,
loaded_weight=loaded_weight,
expert_data=expert_data,
tp_rank=tp_rank,
load_full=padded_tp,
)
elif shard_id in ("w1", "w3"):
self._load_w13(
@@ -357,6 +386,7 @@ class RoutedExperts(PluggableLayer):
loaded_weight=loaded_weight,
expert_data=expert_data,
tp_rank=tp_rank,
load_full=padded_tp,
)
def _load_per_channel_weight_scale(
@@ -511,11 +541,12 @@ class RoutedExperts(PluggableLayer):
shard_dim: int,
loaded_weight: torch.Tensor,
tp_rank: int,
load_full: bool = False,
):
# Index the loaded weight for tp sharding.
# down_proj: "RowParallel" so tp sharding on input_dim
# Only narrow if the loaded_weight is not a scalar (0-dim tensor).
if loaded_weight.ndim > 0:
# Padded TP weights have already been sliced by the grouped loader.
if not load_full and loaded_weight.ndim > 0:
# Same padding fix as _load_w13: use unpadded per-rank size.
tp_size = self.moe_config.moe_parallel_config.tp_size
loaded_per_rank = loaded_weight.shape[shard_dim] // tp_size
@@ -536,6 +567,23 @@ class RoutedExperts(PluggableLayer):
hidden_dim=hidden_dim,
shard_dim=shard_dim,
)
if (
loaded_weight.device.type == "cpu"
and expert_data.device.type == "cuda"
and not expert_data.is_contiguous()
and expert_data.ndim == 2
):
# A strided CPU-to-CUDA copy can allocate a full-shard CUDA
# temporary. Make the TP slice contiguous on CPU and copy rows
# in chunks to limit the temporary used for the padded view.
loaded_weight = loaded_weight.contiguous()
num_chunks = max(cdiv(loaded_weight.nbytes, 1 << 20), 1)
for dst, src in zip(
expert_data.chunk(num_chunks, dim=0),
loaded_weight.chunk(num_chunks, dim=0),
):
dst.copy_(src)
return
expert_data.copy_(loaded_weight)
def _load_single_value(
@@ -800,6 +848,7 @@ class RoutedExperts(PluggableLayer):
loaded_weight=loaded_weight,
expert_data=expert_data,
tp_rank=self.moe_config.tp_rank,
is_scale=True,
)
elif quant_method == FusedMoeWeightScaleSupported.TENSOR.value:
self._load_per_tensor_weight_scale(
@@ -8,6 +8,7 @@ from vllm import _custom_ops as ops
from vllm import envs as envs
from vllm._aiter_ops import rocm_aiter_ops
from vllm.distributed.eplb.eplb_state import EplbLayerState
from vllm.forward_context import get_forward_context, is_forward_context_available
from vllm.model_executor.custom_op import CustomOp
from vllm.model_executor.layers.fused_moe.config import (
RoutingMethodType,
@@ -258,6 +259,7 @@ class GroupedTopKRouter(BaseRouter):
e_score_correction_bias: torch.Tensor | None = None,
num_fused_shared_experts: int = 0,
eplb_state: EplbLayerState | None = None,
skip_padding: bool = False,
):
super().__init__(
top_k=top_k,
@@ -271,6 +273,7 @@ class GroupedTopKRouter(BaseRouter):
self.routed_scaling_factor = routed_scaling_factor
self.e_score_correction_bias = e_score_correction_bias
self.num_fused_shared_experts = num_fused_shared_experts
self.skip_padding = skip_padding
@property
def routing_method_type(self) -> RoutingMethodType:
@@ -346,4 +349,15 @@ class GroupedTopKRouter(BaseRouter):
e_score_correction_bias=self.e_score_correction_bias,
)
if (
self.skip_padding
and envs.VLLM_MOE_SKIP_PADDING
and is_forward_context_available()
):
is_padding = get_forward_context().is_padding
if is_padding is not None:
is_padding = is_padding[: topk_ids.shape[0]].unsqueeze(1)
topk_weights = topk_weights.masked_fill(is_padding, 0)
topk_ids = topk_ids.masked_fill(is_padding, -1)
return topk_weights, topk_ids
@@ -65,6 +65,7 @@ def create_fused_moe_router(
# Deepseek V4 vision routing bias parameters
bias_vl: torch.Tensor | None = None,
image_sentinel_lo: int = 0,
skip_padding: bool = False,
) -> FusedMoERouter:
"""Factory function to create the appropriate FusedMoERouter subclass based on
the provided parameters.
@@ -91,6 +92,7 @@ def create_fused_moe_router(
topk_group: Top-k within each group (for grouped routing)
scoring_func: Scoring function to use ("softmax" or "sigmoid")
num_fused_shared_experts: Number of fused shared experts (for ROCm AITER)
skip_padding: Whether to invalidate routes for padding rows
Grouped topk and fused topk bias arguments:
routed_scaling_factor: Scaling factor for routed weights
@@ -209,6 +211,7 @@ def create_fused_moe_router(
routed_scaling_factor=routed_scaling_factor,
e_score_correction_bias=e_score_correction_bias,
num_fused_shared_experts=num_fused_shared_experts,
skip_padding=skip_padding,
)
# Otherwise fall through to the non-grouped chain below.
@@ -11,6 +11,7 @@ from vllm.logger import init_logger
from vllm.model_executor.custom_op import CustomOp
from vllm.model_executor.layers.fused_moe.config import (
FusedMoEConfig,
FusedMoEParallelConfig,
FusedMoEQuantConfig,
biased_moe_quant_config,
)
@@ -23,6 +24,7 @@ from vllm.model_executor.layers.fused_moe.oracle.unquantized import (
convert_to_unquantized_kernel_format,
make_unquantized_moe_kernel,
select_unquantized_moe_backend,
unquantized_round_up_hidden_size_and_intermediate_size,
)
from vllm.model_executor.layers.fused_moe.runner.shared_experts import (
SharedExperts,
@@ -47,13 +49,17 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
# --8<-- [end:unquantized_fused_moe]
supports_pre_processed_weights = True
def __init__(self, moe: FusedMoEConfig):
super().__init__(moe)
self.unquantized_backend, self.experts_cls = select_unquantized_moe_backend(
moe_config=self.moe,
)
# MoonEP replaces the named parameters with its [E+B] gate/down
# split and keeps the up projection outside the parameter registry,
# so a pre-processed (e.g. ipc_cache) load cannot reconstruct it.
self.supports_pre_processed_weights = (
self.unquantized_backend != UnquantizedMoeBackend.MOONEP
)
@property
def supports_eplb(self) -> bool:
@@ -68,10 +74,15 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
params_dtype: torch.dtype,
**extra_weight_attrs,
):
unpadded_intermediate = self.moe.intermediate_size_per_partition_unpadded
assert unpadded_intermediate is not None
if self.moe.is_act_and_mul:
w13_up_dim = 2 * intermediate_size_per_partition
else:
w13_up_dim = intermediate_size_per_partition
unpadded_hidden = self.moe.hidden_dim_unpadded
assert unpadded_hidden is not None
unpadded_up = unpadded_intermediate * (2 if self.moe.is_act_and_mul else 1)
# Fused gate_up_proj (column parallel)
w13_weight = torch.nn.Parameter(
torch.empty(
@@ -84,6 +95,7 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
)
layer.register_parameter("w13_weight", w13_weight)
set_weight_attrs(w13_weight, extra_weight_attrs)
w13_weight.weight_loader_numel = num_experts * unpadded_up * unpadded_hidden
if self.moe.has_bias:
w13_bias = torch.nn.Parameter(
torch.zeros(num_experts, w13_up_dim, dtype=params_dtype),
@@ -91,6 +103,7 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
)
layer.register_parameter("w13_bias", w13_bias)
set_weight_attrs(w13_bias, extra_weight_attrs)
w13_bias.weight_loader_numel = num_experts * unpadded_up
# down_proj (row parallel)
w2_weight = torch.nn.Parameter(
torch.empty(
@@ -103,6 +116,9 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
)
layer.register_parameter("w2_weight", w2_weight)
set_weight_attrs(w2_weight, extra_weight_attrs)
w2_weight.weight_loader_numel = (
num_experts * unpadded_hidden * unpadded_intermediate
)
if self.moe.has_bias:
w2_bias = torch.nn.Parameter(
torch.zeros(num_experts, hidden_size, dtype=params_dtype),
@@ -110,6 +126,24 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
)
layer.register_parameter("w2_bias", w2_bias)
set_weight_attrs(w2_bias, extra_weight_attrs)
w2_bias.weight_loader_numel = num_experts * unpadded_hidden
def maybe_roundup_sizes(
self,
hidden_size: int,
intermediate_size_per_partition: int,
act_dtype: torch.dtype,
moe_parallel_config: FusedMoEParallelConfig,
) -> tuple[int, int]:
hidden_size, intermediate_size_per_partition = super().maybe_roundup_sizes(
hidden_size,
intermediate_size_per_partition,
act_dtype,
moe_parallel_config,
)
return unquantized_round_up_hidden_size_and_intermediate_size(
self.unquantized_backend, hidden_size, intermediate_size_per_partition
)
def _maybe_pad_weight(self, weight: torch.Tensor) -> torch.Tensor:
# Pad the weight tensor. This is an optimization on ROCm platform, which
@@ -141,6 +175,7 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
moe_config=layer.moe_config,
w13_weight=w13,
w2_weight=w2,
layer=layer,
)
# `moe_kernel` is initialized to None in FusedMoEMethodBase.__init__;
# On the first call we replace the parameter normally. On subsequent
@@ -161,14 +196,13 @@ class UnquantizedFusedMoEMethod(FusedMoEMethodBase, CustomOp):
# does not need to be re-built.
self._init_moe_kernel(layer)
if self.unquantized_backend == UnquantizedMoeBackend.CPU:
# The CPU experts need the layer itself for the setup that
# convert_to_unquantized_kernel_format cannot express, since
# it only sees the two weight tensors: padding and prepacking
# into the grouped-gemm layout (bias included), and capturing
# the router config that monolithic apply() cannot carry.
assert self.moe_kernel is not None
self.moe_kernel.fused_experts.process_weights_after_loading(layer)
# No-op by default. Experts that need the layer itself for setup
# convert_to_unquantized_kernel_format cannot express override
# it: CPU prepacks into its grouped-gemm layout and captures the
# router config; MoonEP picks up the [E+B] weight layout for
# prefetch and the up projection.
assert self.moe_kernel is not None
self.moe_kernel.fused_experts.process_weights_after_loading(layer)
def _init_moe_kernel(self, layer: "RoutedExperts") -> None:
"""Build the MoE kernel from the layer's current (shuffled) weights."""
@@ -399,6 +399,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
self.key_dim = self.head_k_dim * self.num_k_heads
self.value_dim = self.head_v_dim * self.num_v_heads
self.gqa_interleaved_layout = gqa_interleaved_layout
self.qkvz_layout = "interleaved" if gqa_interleaved_layout else "flat"
if current_platform.is_xpu():
self._forward_method = self.forward_xpu
elif current_platform.is_cpu():
@@ -1206,9 +1207,9 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
"""ROCm AITER fast path: conv1d + recurrent attention from packed
qkvz/ba layout.
For decode-only (no spec, no prefill) interleaved-GQA layouts,
dispatches directly to ``_forward_core_decode_aiter``. Otherwise unpacks
the packed layout and falls through to ``_forward_core``.
For decode-only (no spec, no prefill) batches, dispatches directly to
``_forward_core_decode_aiter``. Otherwise unpacks the packed layout and
falls through to ``_forward_core``.
Args:
qkvz: packed [q, k, v, z] projection (num_tokens, qkvz_dim)
@@ -1231,12 +1232,8 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
assert isinstance(attn_metadata, GDNAttentionMetadata)
# The AITER fused reshape/conv kernel expects Qwen3-Next's interleaved
# GQA layout. Qwen3.5 uses a non-interleaved q/k/v/z layout and must use
# the generic path below to split/rearrange inputs correctly.
if (
self.gqa_interleaved_layout
and attn_metadata.spec_sequence_masks is None
attn_metadata.spec_sequence_masks is None
and attn_metadata.num_prefills == 0
and attn_metadata.num_decodes > 0
):
@@ -1625,6 +1622,7 @@ class QwenGatedDeltaNetAttention(GatedDeltaNetAttention):
: attn_metadata.num_actual_tokens
],
validate_data=True,
qkvz_layout=self.qkvz_layout,
)
)
@@ -222,12 +222,18 @@ class MambaStateShapeCalculator:
@classmethod
def append_replayssm_ring(
cls,
base_shapes: tuple[tuple[int, ...], ...],
base_shapes: tuple[tuple[int, int], tuple[int, int, int]],
n_groups: int,
tp_world_size: int,
logical_window: int,
backend: MambaBackendEnum,
) -> tuple[tuple[int, ...], ...]:
) -> tuple[
tuple[int, int],
tuple[int, int, int],
tuple[int, int, int],
tuple[int, int],
tuple[int, int, int],
]:
"""Append the physical ReplaySSM ring shapes.
``base_shapes[1]`` is ``(nheads // tp, head_dim, state_size)``;
@@ -573,8 +573,8 @@ class Sm100ChunkUWKernel:
for i in cutlass.range_constexpr(4):
M[i] = _bf16x2_sub(_bf16x2_neg(eye[i]), M[i])
# 3 rounds of Newton-Schulz
for _ in cutlass.range_constexpr(3):
# The fourth round keeps correlated-key KKT blocks stable in BF16.
for _ in cutlass.range_constexpr(4):
# First MMA: -AiM = Ai @ (-M)
cute.copy(stsm_atom, Ai_bf16, sA_ldsm[None, (warp_id_, warp_id_)])
cute.arch.sync_warp()
@@ -93,7 +93,7 @@ def _replace_or_register_parameter(
def _convert_awq_to_standard_format(
layer: torch.nn.Module,
w_q_name: str,
w_zp_name: str,
w_zp_name: str | None,
size_bits: int,
) -> None:
"""Convert AWQ weight and zero-point tensors to standard GPTQ-like format.
@@ -101,6 +101,7 @@ def _convert_awq_to_standard_format(
AWQ packs qweight along the output dim with a non-standard bit order.
This converts to standard bit order and repacks qweight along the input
dim, matching the format expected by the MPLinearKernel framework.
If w_zp_name is None (symmetric quantization), only the weight is converted.
"""
pack_factor = 32 // size_bits
mask = (1 << size_bits) - 1
@@ -139,6 +140,9 @@ def _convert_awq_to_standard_format(
)
setattr(layer, w_q_name, new_param)
if w_zp_name is None:
return
# --- Convert qzeros: fix AWQ bit ordering and repack
# AWQ qzeros: (G, N // pack) packed along dim 1, AWQ bit order
# Target: (N // pack, G) packed along dim 0, standard bit order
+11 -32
View File
@@ -8,7 +8,6 @@ import torch
import vllm.envs as envs
from vllm.config import get_current_vllm_config
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.logger import init_logger
from vllm.model_executor.kernels.linear import (
init_fp8_linear_kernel,
)
@@ -24,14 +23,12 @@ from vllm.model_executor.layers.fused_moe import (
SharedExperts,
UnquantizedFusedMoEMethod,
)
from vllm.model_executor.layers.fused_moe.config import (
FusedMoEQuantConfig,
)
from vllm.model_executor.layers.fused_moe.config import FusedMoEQuantConfig
from vllm.model_executor.layers.fused_moe.oracle.fp8 import (
convert_to_fp8_moe_kernel_format,
make_fp8_moe_kernel,
make_fp8_moe_quant_config,
refine_fp8_moe_block_shape,
resolve_fp8_moe_weight_block_shape,
select_fp8_moe_backend,
)
from vllm.model_executor.layers.linear import (
@@ -90,8 +87,6 @@ if TYPE_CHECKING:
ACTIVATION_SCHEMES = ["static", "dynamic"]
logger = init_logger(__name__)
class Fp8Config(QuantizationConfig):
"""Config class for FP8."""
@@ -511,32 +506,16 @@ class Fp8MoEMethod(FusedMoEMethodBase):
# Set weight key and activation key for kernel compatibility
if self.block_quant:
assert self.weight_block_size is not None
# TP shards the intermediate dim of the expert weights, so a
# per-shard size that is not a multiple of the checkpoint's block
# size makes the checkpoint's block scales impossible to shard
# exactly. When a finer block size (>= 32) divides both the
# checkpoint blocks and all involved dims, the weight scales are
# refined to that granularity at load time (a lossless upsampling,
# since the refined block divides the checkpoint block). The
# refined block shape is encoded in the weight key, so the oracle
# only selects kernels that support it (e.g. Triton, which takes
# the block shape as a runtime argument).
refined_shape = refine_fp8_moe_block_shape(self.moe, self.weight_block_size)
if refined_shape is not None:
block_n, block_k = self.weight_block_size
self.weight_scale_refine = (
block_n // refined_shape[0],
block_k // refined_shape[1],
# Adapt the checkpoint block shape to TP sharding before
# building the weight key.
self.moe_block_shape, self.weight_scale_refine = (
resolve_fp8_moe_weight_block_shape(
self.moe,
self.weight_block_size,
kFp8Dynamic128Sym,
self.quant_config.is_checkpoint_fp8_serialized,
)
self.moe_block_shape = refined_shape
logger.info_once(
"FP8 MoE block scales refined from %s to %s to fit "
"the TP-sharded intermediate size %d.",
str(self.weight_block_size),
str(refined_shape),
self.moe.intermediate_size_per_partition,
)
assert self.moe_block_shape is not None
)
weight_key = create_fp8_quant_key(
static=True, group_shape=GroupShape(*self.moe_block_shape)
)
@@ -2482,9 +2482,16 @@ class ModelOptLinearMethod(LinearMethodBase):
@property
def supports_pre_processed_weights(self) -> bool: # type: ignore[override]
# TODO(Isotr0py): support fp8/mxfp8 ModelOpt kernels transpose/repack.
# TODO(Isotr0py): support fp8 ModelOpt kernels transpose/repack.
w = self.spec.weight
return isinstance(w, QuantKey) and w.dtype == FP4_DTYPE
return isinstance(w, QuantKey) and (
w.dtype == FP4_DTYPE
or (
w == kMxfp8Static
and self.kernel is not None
and self.kernel.supports_pre_processed_weights
)
)
def create_weights(
self,
@@ -2524,7 +2531,13 @@ class ModelOptLinearMethod(LinearMethodBase):
expose_input_quant_key(layer, self.kernel)
def process_weights_after_loading(self, layer) -> None:
if self.spec.weight == kMxfp8Static and getattr(layer, "is_bmm", False):
self.kernel = init_mxfp8_linear_kernel(bmm_batch_size=layer.bmm_batch_size)
if is_weights_pre_processed():
if not self.supports_pre_processed_weights:
raise RuntimeError(
f"{type(self.kernel).__name__} cannot use pre-processed weights"
)
return
self.fmt.pre_process(layer)
self.wkey.process(layer, WEIGHT)
@@ -2556,8 +2569,6 @@ class ModelOptLinearMethod(LinearMethodBase):
persistent=False,
)
layer._nvfp4_group_size_for_gather = self.ctx.group_size
if self.spec.weight == kMxfp8Static and getattr(layer, "is_bmm", False):
self.kernel = init_mxfp8_linear_kernel(bmm_batch_size=layer.bmm_batch_size)
self.kernel.process_weights_after_loading(layer)
def apply(self, layer, x, bias=None):
@@ -737,11 +737,13 @@ class Fp8PtpcOnlineMoEMethod(_Fp8OnlineMoEBase):
)
# Reject backends whose make_fp8_moe_quant_config branch silently
# drops per_act_token_quant / per_out_ch_quant or collapses scales:
# MARLIN / CPU route through fp8_w8a16_moe_quant_config; FLASHINFER_*
# fold scales into a per-tensor alpha (oracle/fp8.py).
# MARLIN / CPU route through fp8_w8a16_moe_quant_config, CPU_W8A8
# ignores both flags, and FLASHINFER_* fold scales into a per-tensor
# alpha (oracle/fp8.py).
if self.fp8_backend in (
Fp8MoeBackend.MARLIN,
Fp8MoeBackend.CPU,
Fp8MoeBackend.CPU_W8A8,
Fp8MoeBackend.FLASHINFER_CUTLASS,
Fp8MoeBackend.FLASHINFER_TRTLLM,
):
@@ -32,6 +32,7 @@ from vllm.model_executor.layers.quantization.quark.schemes import (
QuarkOCP_MX,
QuarkScheme,
QuarkW4A8_MXFP4_FP8,
QuarkW4A16Int4,
QuarkW8A8Fp8,
QuarkW8A8Fp8PerBlock,
QuarkW8A8Int8,
@@ -39,6 +40,7 @@ from vllm.model_executor.layers.quantization.quark.schemes import (
from vllm.model_executor.layers.quantization.quark.utils import (
QuarkQTensorHint,
deep_compare,
parse_w4a16_int4_weight_config,
should_ignore_layer,
)
from vllm.model_executor.layers.quantization.utils.ocp_mx_utils import (
@@ -54,6 +56,10 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8Static128BlockSym,
kFp8StaticChannelSym,
kFp8StaticTensorSym,
kInt4Static,
kInt4Static32,
kInt4Static32Asym,
kInt4StaticAsym,
kInt4W4A8StaticChannelSym,
kInt8DynamicTensorAsym,
kInt8DynamicTensorSym,
@@ -172,8 +178,10 @@ class QuarkConfig(QuantizationConfig):
quant_config_with_hf_to_vllm_mapper: dict[str, Any] = {}
for k, v in self.quant_config.items():
if isinstance(v, list):
if isinstance(v, list) and all(isinstance(item, str) for item in v):
quant_config_with_hf_to_vllm_mapper[k] = hf_to_vllm_mapper.apply_list(v)
elif isinstance(v, list):
quant_config_with_hf_to_vllm_mapper[k] = v
elif isinstance(v, dict):
quant_config_with_hf_to_vllm_mapper[k] = hf_to_vllm_mapper.apply_dict(v)
else:
@@ -215,6 +223,9 @@ class QuarkConfig(QuantizationConfig):
weight_quant_key=weight_quant_key,
activation_quant_key=activation_quant_key,
dynamic_mxfp4_quant=dynamic_mxfp4_quant,
weight_config=self._find_matched_config(prefix, type(layer)).get(
"weight"
),
)
layer.scheme = scheme
return QuarkLinearMethod(self)
@@ -227,6 +238,7 @@ class QuarkConfig(QuantizationConfig):
method_cls=method_cls,
weight_quant_key=weight_quant_key,
activation_quant_key=activation_quant_key,
layer_name=prefix,
)
return None
@@ -572,6 +584,26 @@ class QuarkConfig(QuantizationConfig):
)
return QuantKeyMatch(True, activation_quant_key, weight_quant_key)
def _is_w4a16_int4(
self,
weight_quant: dict[str, Any] | None,
input_quant: dict[str, Any] | None,
) -> QuantKeyMatch:
if weight_quant is None or input_quant is not None:
return QuantKeyMatch(False, None, None)
is_int4 = weight_quant.get("dtype") in ("int4", "uint4")
is_packed = self.pack_method in ("order", "reorder")
if not (is_int4 and is_packed):
return QuantKeyMatch(False, None, None)
group_size, is_symmetric = parse_w4a16_int4_weight_config(weight_quant)
if is_symmetric:
weight_key = kInt4Static32 if group_size == 32 else kInt4Static
else:
weight_key = kInt4Static32Asym if group_size == 32 else kInt4StaticAsym
return QuantKeyMatch(True, None, weight_key)
def _is_w4a8_mxfp4_fp8(
self,
weight_quant: dict[str, Any] | None,
@@ -890,6 +922,12 @@ class QuarkConfig(QuantizationConfig):
match.activation_quant_key,
QuarkW8A8Int8,
)
elif match := self._is_w4a16_int4(weight_config, input_config):
return (
match.weight_quant_key,
match.activation_quant_key,
QuarkW4A16Int4,
)
elif match := self._is_w4a8_mxfp4_fp8(weight_config, input_config):
return (
match.weight_quant_key,
@@ -919,6 +957,7 @@ class QuarkConfig(QuantizationConfig):
weight_quant_key: QuantKey | None,
activation_quant_key: QuantKey | None,
dynamic_mxfp4_quant: bool = False,
weight_config: dict[str, Any] | None = None,
) -> "QuarkScheme":
"""Construct a Quark scheme selected by get_scheme_cls."""
if scheme_cls not in (
@@ -928,9 +967,24 @@ class QuarkConfig(QuantizationConfig):
QuarkOCP_MX,
QuarkNVFP4,
QuarkW4A8_MXFP4_FP8,
QuarkW4A16Int4,
):
raise AssertionError(f"Unsupported Quark scheme class: {scheme_cls}")
scheme: QuarkScheme
if scheme_cls is QuarkW4A16Int4:
normalized_weight_config = self._unwrap_single_quant_config(weight_config)
assert normalized_weight_config is not None
assert weight_quant_key is not None
scheme = QuarkW4A16Int4(
weight_quant_key=weight_quant_key,
activation_quant_key=activation_quant_key,
pack_method=self.pack_method,
weight_config=normalized_weight_config,
)
self._check_scheme_supported(scheme.get_min_capability())
return scheme
kwargs: dict[str, Any] = {"activation_quant_key": activation_quant_key}
# These classes handle different possible `weight_quant_key`.
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
import torch
@@ -40,6 +40,12 @@ from vllm.model_executor.layers.fused_moe.oracle.int8 import (
make_int8_moe_quant_config,
select_int8_moe_backend,
)
from vllm.model_executor.layers.fused_moe.oracle.int_wna16 import (
convert_to_wna16_moe_kernel_format,
make_wna16_moe_kernel,
make_wna16_moe_quant_config,
select_wna16_moe_backend,
)
from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import (
TRITON_BACKENDS,
Mxfp4MoeBackend,
@@ -56,7 +62,10 @@ from vllm.model_executor.layers.fused_moe.oracle.nvfp4 import (
make_nvfp4_moe_quant_config,
select_nvfp4_moe_backend,
)
from vllm.model_executor.layers.quantization.quark.utils import QuarkQTensorHint
from vllm.model_executor.layers.quantization.quark.utils import (
QuarkQTensorHint,
parse_w4a16_int4_weight_config,
)
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
validate_fp8_block_shape_moe,
)
@@ -75,6 +84,10 @@ from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8Static128BlockSym,
kFp8StaticChannelSym,
kFp8StaticTensorSym,
kInt4Static,
kInt4Static32,
kInt4Static32Asym,
kInt4StaticAsym,
kInt4W4A8StaticChannelSym,
kInt8DynamicTensorAsym,
kInt8DynamicTensorSym,
@@ -102,6 +115,7 @@ logger = init_logger(__name__)
__all__ = [
"QuarkMoEMethod",
"QuarkW4A16Int4MoEMethod",
"QuarkW8A8Fp8MoEMethod",
"QuarkOCP_MX_MoEMethod",
"QuarkNvfp4MoEMethod",
@@ -179,6 +193,12 @@ class QuarkMoEMethod(FusedMoEMethodBase):
match.activation_quant_key,
QuarkW8A8Fp8MoEMethod,
)
if match := quant_config._is_w4a16_int4(weight_config, input_config):
return (
match.weight_quant_key,
match.activation_quant_key,
QuarkW4A16Int4MoEMethod,
)
if match := quant_config._is_w_ocp_mx_a_x(
weight_config, input_config, allow_static_fp8=True
):
@@ -202,6 +222,7 @@ class QuarkMoEMethod(FusedMoEMethodBase):
method_cls: type["QuarkMoEMethod"],
weight_quant_key: QuantKey | None,
activation_quant_key: QuantKey | None,
layer_name: str | None = None,
) -> "QuarkMoEMethod":
if weight_quant_key is None:
raise RuntimeError("Unsupported FusedMoe scheme")
@@ -226,10 +247,339 @@ class QuarkMoEMethod(FusedMoEMethodBase):
return QuarkW8A8Int8MoEMethod(
module.moe_config, weight_quant_key, activation_quant_key
)
elif method_cls is QuarkW4A16Int4MoEMethod:
assert layer_name is not None
layer_quant_config = quant_config._find_matched_config(
layer_name, type(module)
)
weight_config = quant_config._unwrap_single_quant_config(
layer_quant_config.get("weight")
)
if weight_config is None:
raise RuntimeError(
f"Missing weight quantization config for layer {layer_name}"
)
return QuarkW4A16Int4MoEMethod(
weight_quant_key,
activation_quant_key,
weight_config,
quant_config.pack_method,
module.moe_config,
quant_config=quant_config,
)
else:
raise RuntimeError("Unsupported FusedMoe scheme")
class QuarkW4A16Int4MoEMethod(QuarkMoEMethod):
"""Quark packed INT4 weight-only MoE method."""
supported_activation_quant_keys: list[QuantKey | None] = [None]
supported_weight_quant_keys: list[QuantKey] = [
kInt4Static,
kInt4Static32,
kInt4StaticAsym,
kInt4Static32Asym,
]
def __init__(
self,
weight_quant_key: QuantKey,
activation_quant_key: QuantKey | None,
weight_config: dict[str, Any],
pack_method: str,
moe: FusedMoEConfig,
quant_config: "QuarkConfig | None" = None, # type: ignore # noqa F821
):
super().__init__(moe, weight_quant_key, activation_quant_key)
self.quant_config = quant_config
# group_size is read from the Quark config rather than weight_quant_key:
# the int4 QuantKeys only encode group_size 32 or -1, but Quark int4
# checkpoints commonly use group_size 128, which the QuantKey cannot
# represent. Symmetry is unambiguous, so it comes from the key.
self.group_size = parse_w4a16_int4_weight_config(weight_config)[0]
self.is_symmetric = weight_quant_key.symmetric
self.bit8_pack_factor = 2
self.pack_reorder = pack_method == "reorder"
self.use_wna16_backend = True
self.wna16_backend, self.experts_cls = select_wna16_moe_backend(
config=self.moe,
weight_key=weight_quant_key,
quant_config=self.quant_config,
may_have_zp=not self.is_symmetric,
may_have_bias=False,
)
def create_weights(
self,
layer: RoutedExperts,
num_experts: int,
hidden_size: int,
intermediate_size_per_partition: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
):
group_size = self.group_size
group_size_div_factor = 1
while intermediate_size_per_partition % group_size or hidden_size % group_size:
group_size = group_size // 2
group_size_div_factor *= 2
assert group_size >= 32
layer.group_size = group_size
layer.group_size_div_factor = group_size_div_factor
strategy = FusedMoeWeightScaleSupported.GROUP.value
extra_weight_attrs.update({"quant_method": strategy, "is_transposed": False})
assert "weight_loader" in extra_weight_attrs
weight_loader = extra_weight_attrs["weight_loader"]
extra_weight_attrs["weight_loader"] = self.get_weight_loader(
layer, weight_loader
)
w13_weight = torch.nn.Parameter(
torch.empty(
num_experts,
2 * intermediate_size_per_partition,
hidden_size // self.bit8_pack_factor,
dtype=torch.uint8,
),
requires_grad=False,
)
layer.register_parameter("w13_weight", w13_weight)
set_weight_attrs(w13_weight, extra_weight_attrs)
w2_weight = torch.nn.Parameter(
torch.empty(
num_experts,
hidden_size,
intermediate_size_per_partition // self.bit8_pack_factor,
dtype=torch.uint8,
),
requires_grad=False,
)
layer.register_parameter("w2_weight", w2_weight)
set_weight_attrs(w2_weight, extra_weight_attrs)
w13_weight_scale = torch.nn.Parameter(
torch.zeros(
num_experts,
2 * intermediate_size_per_partition,
hidden_size // group_size,
dtype=params_dtype,
),
requires_grad=False,
)
layer.register_parameter("w13_weight_scale", w13_weight_scale)
set_weight_attrs(w13_weight_scale, extra_weight_attrs)
w2_weight_scale = torch.nn.Parameter(
torch.zeros(
num_experts,
hidden_size,
intermediate_size_per_partition // group_size,
dtype=params_dtype,
),
requires_grad=False,
)
layer.register_parameter("w2_weight_scale", w2_weight_scale)
set_weight_attrs(w2_weight_scale, extra_weight_attrs)
w13_weight_zero_point = torch.nn.Parameter(
torch.zeros(
num_experts,
2 * intermediate_size_per_partition // self.bit8_pack_factor,
hidden_size // group_size,
dtype=torch.uint8,
),
requires_grad=False,
)
layer.register_parameter("w13_weight_zero_point", w13_weight_zero_point)
set_weight_attrs(w13_weight_zero_point, extra_weight_attrs)
w2_weight_zero_point = torch.nn.Parameter(
torch.zeros(
num_experts,
hidden_size // self.bit8_pack_factor,
intermediate_size_per_partition // group_size,
dtype=torch.uint8,
),
requires_grad=False,
)
layer.register_parameter("w2_weight_zero_point", w2_weight_zero_point)
set_weight_attrs(w2_weight_zero_point, extra_weight_attrs)
def process_weights_after_loading(self, layer: RoutedExperts) -> None:
w13_qzeros = layer.w13_weight_zero_point if not self.is_symmetric else None
w2_qzeros = layer.w2_weight_zero_point if not self.is_symmetric else None
converted = convert_to_wna16_moe_kernel_format(
backend=self.wna16_backend,
layer=layer,
quant_config=self.quant_config,
input_dtype=None,
w13=layer.w13_weight,
w2=layer.w2_weight,
w13_scale=layer.w13_weight_scale,
w2_scale=layer.w2_weight_scale,
w13_qzeros=w13_qzeros,
w2_qzeros=w2_qzeros,
)
if converted is None:
# Backend rewrote the layer's params in place (e.g. Humming).
self._setup_kernel(layer)
return
(
w13_qweight,
w2_qweight,
w13_scales,
w2_scales,
_, # w13_qzeros
_, # w2_qzeros
_, # w13_input_global_scale
_, # w2_input_global_scale
_, # w13_bias
_, # w2_bias
) = converted
replace_parameter(layer, "w13_weight", w13_qweight)
replace_parameter(layer, "w2_weight", w2_qweight)
replace_parameter(layer, "w13_weight_scale", w13_scales)
replace_parameter(layer, "w2_weight_scale", w2_scales)
self._setup_kernel(layer)
def _setup_kernel(self, layer: RoutedExperts) -> None:
assert self.experts_cls is not None
self.moe_quant_config = self.get_fused_moe_quant_config(layer)
assert self.moe_quant_config is not None
self.moe_kernel = make_wna16_moe_kernel(
moe_quant_config=self.moe_quant_config,
moe_config=self.moe,
experts_cls=self.experts_cls,
backend=self.wna16_backend,
routing_tables=layer._expert_routing_tables(),
)
def get_fused_moe_quant_config(
self, layer: RoutedExperts
) -> FusedMoEQuantConfig | None:
w1_zp = layer.w13_weight_zero_point if not self.is_symmetric else None
w2_zp = layer.w2_weight_zero_point if not self.is_symmetric else None
return make_wna16_moe_quant_config(
w1_scale=layer.w13_weight_scale,
w2_scale=layer.w2_weight_scale,
w1_zp=w1_zp,
w2_zp=w2_zp,
group_size=layer.group_size,
num_bits=4,
)
def apply(
self,
layer: RoutedExperts,
x: torch.Tensor,
topk_weights: torch.Tensor,
topk_ids: torch.Tensor,
shared_experts: SharedExperts | None,
shared_experts_input: torch.Tensor | None,
) -> torch.Tensor:
assert self.moe_kernel is not None
return self.moe_kernel.apply(
hidden_states=x,
w1=layer.w13_weight,
w2=layer.w2_weight,
topk_weights=topk_weights,
topk_ids=topk_ids,
activation=layer.activation,
global_num_experts=layer.global_num_experts,
apply_router_weight_on_input=layer.apply_router_weight_on_input,
expert_map=layer.expert_map,
shared_experts=shared_experts,
shared_experts_input=shared_experts_input,
)
def get_weight_loader(self, layer: RoutedExperts, weight_loader):
def convert_quark_tensor(tensor: torch.Tensor, tensor_type: str):
size0 = tensor.size(0)
tensor = tensor.view(torch.uint8)
shifter = torch.tensor([0, 4], dtype=torch.uint8, device=tensor.device)
tensor = (tensor[:, :, None] >> shifter) & 0xF
if self.pack_reorder:
reverse_awq_pack_order = [0, 4, 1, 5, 2, 6, 3, 7]
tensor = tensor.view(-1, 8)[:, reverse_awq_pack_order]
else:
tensor = tensor.view(-1, 8)
if self.is_symmetric:
tensor = tensor ^ 0x8
tensor = tensor.view(size0, -1)
tensor = tensor.T.contiguous()
if tensor_type == "weight":
tensor = tensor[:, 1::2] * 16 + tensor[:, ::2]
elif tensor_type == "zero_point":
tensor = tensor[1::2, :] * 16 + tensor[::2, :]
return tensor
def quark_int4_weight_loader(
param: torch.nn.Parameter,
loaded_weight: torch.Tensor,
weight_name: str,
shard_id: str,
expert_id: int,
return_success: bool = False,
):
loaded_weight = loaded_weight.to(param.data.device)
shard_size = layer.intermediate_size_per_partition
if weight_name.endswith("_weight"):
loaded_weight = convert_quark_tensor(loaded_weight, "weight")
elif weight_name.endswith("_weight_zero_point"):
loaded_weight = convert_quark_tensor(loaded_weight, "zero_point")
elif weight_name.endswith("_weight_scale"):
loaded_weight = loaded_weight.T
if layer.group_size_div_factor > 1 and (
"weight_zero_point" in weight_name or "weight_scale" in weight_name
):
loaded_weight = loaded_weight.repeat_interleave(
layer.group_size_div_factor, 1
)
if "w13_weight_zero_point" in weight_name:
tensor = loaded_weight.view(
layer.moe_config.tp_size, -1, loaded_weight.size(1)
)[layer.moe_config.tp_rank]
if shard_id == "w1":
param.data[expert_id, : shard_size // 2] = tensor
else:
param.data[expert_id, shard_size // 2 :] = tensor
return True if return_success else None
elif "w2_weight_zero_point" in weight_name:
param.data[expert_id] = loaded_weight.view(
loaded_weight.size(0), layer.moe_config.tp_size, -1
)[:, layer.moe_config.tp_rank]
return True if return_success else None
return weight_loader(
param,
loaded_weight,
weight_name,
shard_id,
expert_id,
return_success=return_success,
)
return quark_int4_weight_loader
class QuarkW8A8Fp8MoEMethod(QuarkMoEMethod):
supported_activation_quant_keys = [
kFp8StaticTensorSym,
@@ -5,6 +5,7 @@ from .quark_nvfp4 import QuarkNVFP4
from .quark_ocp_mx import QuarkOCP_MX
from .quark_scheme import QuarkScheme
from .quark_w4a8_mxfp4_fp8 import QuarkW4A8_MXFP4_FP8
from .quark_w4a16_int4 import QuarkW4A16Int4
from .quark_w8a8_fp8 import QuarkW8A8Fp8, QuarkW8A8Fp8PerBlock
from .quark_w8a8_int8 import QuarkW8A8Int8
@@ -14,6 +15,7 @@ __all__ = [
"QuarkW8A8Fp8PerBlock",
"QuarkW8A8Int8",
"QuarkOCP_MX",
"QuarkW4A16Int4",
"QuarkW4A8_MXFP4_FP8",
"QuarkNVFP4",
]
@@ -0,0 +1,212 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import math
from collections.abc import Callable
from typing import Any
import torch
from vllm.model_executor.kernels.linear import (
MPLinearKernel,
MPLinearLayerConfig,
choose_mp_linear_kernel,
)
from vllm.model_executor.layers.quantization.auto_awq import (
_convert_awq_to_standard_format,
)
from vllm.model_executor.layers.quantization.quark.schemes.quark_scheme import (
QuarkScheme,
)
from vllm.model_executor.layers.quantization.quark.utils import (
canonicalize_quark_packed_int4,
parse_w4a16_int4_weight_config,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kInt4Static,
kInt4Static32,
kInt4Static32Asym,
kInt4StaticAsym,
)
from vllm.model_executor.parameter import (
GroupQuantScaleParameter,
PackedvLLMParameter,
)
from vllm.scalar_type import scalar_types
class QuarkW4A16Int4(QuarkScheme):
"""Quark packed INT4 weight-only linear scheme via MPLinearKernel."""
supported_activation_quant_keys: list[QuantKey | None] = [None]
supported_weight_quant_keys: list[QuantKey] = [
kInt4Static,
kInt4Static32,
kInt4StaticAsym,
kInt4Static32Asym,
]
def __init__(
self,
weight_quant_key: QuantKey,
activation_quant_key: QuantKey | None,
pack_method: str,
weight_config: dict[str, Any],
):
super().__init__(weight_quant_key, activation_quant_key)
# group_size is read from the Quark config rather than weight_quant_key:
# the int4 QuantKeys only encode group_size 32 or -1, but Quark int4
# checkpoints commonly use group_size 128, which the QuantKey cannot
# represent. Symmetry is unambiguous, so it comes from the key.
self.group_size = parse_w4a16_int4_weight_config(weight_config)[0]
self.pack_factor = 8
self.pack_reorder = pack_method == "reorder"
self.is_symmetric = weight_quant_key.symmetric
self.quant_type = (
scalar_types.uint4b8 if self.is_symmetric else scalar_types.uint4
)
self.kernel: MPLinearKernel | None = None
@classmethod
def get_min_capability(cls) -> int:
return 70
def create_weights(
self,
layer: torch.nn.Module,
output_partition_sizes: list[int],
input_size_per_partition: int,
params_dtype: torch.dtype,
weight_loader: Callable,
**kwargs,
):
input_size = kwargs["input_size"]
output_size = kwargs["output_size"]
group_size = (
self.group_size if self.group_size != -1 else input_size_per_partition
)
if input_size_per_partition % group_size != 0:
raise ValueError(
"The input size is not aligned with the quantized weight shape. "
"This can be caused by too large tensor parallel size. "
f"input_size_per_partition={input_size_per_partition}, "
f"group_size={group_size}."
)
output_size_per_partition = sum(output_partition_sizes)
packed_output_size_per_partition = math.ceil(
output_size_per_partition / self.pack_factor
)
layer.output_size_per_partition = output_size_per_partition
layer.packed_output_size_per_partition = packed_output_size_per_partition
mp_linear_kernel_config = MPLinearLayerConfig(
full_weight_shape=(input_size, output_size),
partition_weight_shape=(
input_size_per_partition,
output_size_per_partition,
),
weight_type=self.quant_type,
act_type=params_dtype,
group_size=group_size,
zero_points=not self.is_symmetric,
)
kernel_type = choose_mp_linear_kernel(mp_linear_kernel_config)
def weight_scale_loader(
param: torch.nn.Parameter,
loaded_weight: torch.Tensor,
*args,
**loader_kwargs,
) -> None:
if loaded_weight.shape[1] < param.data.shape[1]:
padded_weight = loaded_weight.new_zeros(param.data.shape)
padded_weight[:, : loaded_weight.shape[1]] = loaded_weight
loaded_weight = padded_weight
weight_loader(param, loaded_weight, *args, **loader_kwargs)
weight = PackedvLLMParameter(
data=torch.empty(
input_size_per_partition,
packed_output_size_per_partition,
dtype=torch.int32,
),
input_dim=0,
output_dim=1,
packed_dim=1,
packed_factor=self.pack_factor,
weight_loader=weight_loader,
)
num_groups = input_size_per_partition // group_size
weight_zero_point = PackedvLLMParameter(
data=torch.zeros(
num_groups,
packed_output_size_per_partition,
dtype=torch.int32,
),
input_dim=0,
output_dim=1,
packed_dim=1,
packed_factor=self.pack_factor,
weight_loader=weight_loader,
)
weight_scale = GroupQuantScaleParameter(
data=torch.empty(
num_groups,
packed_output_size_per_partition * self.pack_factor,
dtype=params_dtype,
),
input_dim=0,
output_dim=1,
weight_loader=weight_scale_loader,
)
layer.register_parameter("weight", weight)
layer.register_parameter("weight_zero_point", weight_zero_point)
layer.register_parameter("weight_scale", weight_scale)
self.kernel = kernel_type(
mp_linear_kernel_config,
w_q_param_name="weight",
w_s_param_name="weight_scale",
w_zp_param_name="weight_zero_point" if not self.is_symmetric else None,
)
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
layer.weight.data = canonicalize_quark_packed_int4(
layer.weight.data,
pack_reorder=self.pack_reorder,
is_symmetric=self.is_symmetric,
pack_factor=self.pack_factor,
)
if not self.is_symmetric:
layer.weight_zero_point.data = canonicalize_quark_packed_int4(
layer.weight_zero_point.data,
pack_reorder=self.pack_reorder,
is_symmetric=self.is_symmetric,
pack_factor=self.pack_factor,
)
output_size = layer.output_size_per_partition
packed_output_size = layer.packed_output_size_per_partition * self.pack_factor
if output_size < packed_output_size:
layer.weight_scale.data[:, output_size:].zero_()
_convert_awq_to_standard_format(
layer,
"weight",
"weight_zero_point" if not self.is_symmetric else None,
self.quant_type.size_bits,
)
assert self.kernel is not None
self.kernel.process_weights_after_loading(layer)
def apply_weights(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
):
assert self.kernel is not None
return self.kernel.apply_weights(layer, x, bias)
@@ -66,6 +66,63 @@ def should_ignore_layer(
return all(shards_ignored)
def parse_w4a16_int4_weight_config(
weight_config: Mapping[str, Any],
) -> tuple[int, bool]:
"""Parse required W4A16 INT4/UINT4 weight fields from Quark config."""
if "group_size" not in weight_config:
raise ValueError(
"Quark W4A16 INT4/UINT4 configs must specify weight.group_size"
)
if "symmetric" not in weight_config:
raise ValueError("Quark W4A16 INT4/UINT4 configs must specify weight.symmetric")
group_size = weight_config["group_size"]
is_symmetric = weight_config["symmetric"]
if not isinstance(group_size, int) or group_size <= 0:
raise ValueError(
f"Quark W4A16 weight.group_size must be a positive int, got {group_size!r}"
)
if not isinstance(is_symmetric, bool):
raise ValueError(
f"Quark W4A16 weight.symmetric must be a bool, got {is_symmetric!r}"
)
return group_size, is_symmetric
def canonicalize_quark_packed_int4(
packed_weight: torch.Tensor,
*,
pack_reorder: bool,
is_symmetric: bool,
pack_factor: int = 8,
) -> torch.Tensor:
"""Convert Quark export nibble layout to AWQ checkpoint layout."""
from vllm.model_executor.layers.quantization.auto_awq import (
_REVERSE_AWQ_PACK_ORDER,
)
if pack_reorder:
source_order = torch.tensor(
_REVERSE_AWQ_PACK_ORDER, device=packed_weight.device, dtype=torch.int32
)
else:
source_order = torch.arange(
pack_factor, device=packed_weight.device, dtype=torch.int32
)
target_order = torch.tensor(
_REVERSE_AWQ_PACK_ORDER, device=packed_weight.device, dtype=torch.int32
)
source_shifts = source_order * 4
target_shifts = target_order * 4
values = (packed_weight.to(torch.int32)[..., None] >> source_shifts) & 0xF
if is_symmetric:
values = values ^ 0x8
packed = (values.to(torch.int64) << target_shifts.to(torch.int64)).sum(dim=-1)
return packed.to(torch.int32)
# utility for tensor dims > 2 cases
def quark_quantize_weight_to_mxfp4(w: torch.Tensor):
assert w.dtype == torch.bfloat16, (
@@ -112,8 +112,9 @@ def convert_moe_weights_to_flashinfer_trtllm_block_layout(
) -> tuple[torch.Tensor, torch.Tensor]:
"""Convert expert weights to FlashInfer's block layout.
This reorders W13 and W2 into the expected epilogue-tiled block layout and
returns the shuffled weight tensors.
This reorders W13 and W2 in place into the expected epilogue-tiled block
layout and returns views of the shuffled weight tensors. Using one expert
as scratch space avoids allocating another full copy of both weights.
"""
if w13_weight.dtype != torch.bfloat16 or w2_weight.dtype != torch.bfloat16:
raise ValueError(
@@ -147,51 +148,50 @@ def convert_moe_weights_to_flashinfer_trtllm_block_layout(
out=out,
)
w13_rows, w13_cols = w13_weight[0].view(torch.uint8).shape
w2_rows, w2_cols = w2_weight[0].view(torch.uint8).shape
w13_weights_shuffled_tensor = torch.empty(
(num_experts, w13_cols // block_k, w13_rows, block_k),
dtype=torch.uint8,
device=w13_weight.device,
)
w2_weights_shuffled_tensor = torch.empty(
(num_experts, w2_cols // block_k, w2_rows, block_k),
dtype=torch.uint8,
device=w2_weight.device,
)
for i in range(num_experts):
w13_expert_uint8 = w13_weight[i].view(torch.uint8)
permute_indices = _maybe_get_cached_w3_w1_permute_indices(
cache_permute_indices,
w13_expert_uint8,
epilogue_tile_m,
is_gated_act_gemm=is_gated_act_gemm,
)
if is_gated_act_gemm:
rows = w13_expert_uint8.shape[0]
permute_indices = (permute_indices + rows // 2) % rows
_copy_permuted_expert_to_block_layout(
w13_weights_shuffled_tensor[i],
w13_expert_uint8,
permute_indices,
def _convert_weight_in_place(
weight: torch.Tensor,
is_w13: bool,
) -> torch.Tensor:
rows, cols = weight[0].view(torch.uint8).shape
block_layout_shape = (num_experts, cols // block_k, rows, block_k)
expert_scratch = torch.empty(
block_layout_shape[1:],
dtype=torch.uint8,
device=weight.device,
)
permute_indices = get_w2_permute_indices_with_cache(
cache_permute_indices,
w2_weight[i].view(torch.uint8),
epilogue_tile_m,
)
_copy_permuted_expert_to_block_layout(
w2_weights_shuffled_tensor[i],
w2_weight[i].view(torch.uint8),
permute_indices,
)
for i in range(num_experts):
expert_uint8 = weight[i].view(torch.uint8)
if is_w13:
permute_indices = _maybe_get_cached_w3_w1_permute_indices(
cache_permute_indices,
expert_uint8,
epilogue_tile_m,
is_gated_act_gemm=is_gated_act_gemm,
)
if is_gated_act_gemm:
permute_indices = (
permute_indices + expert_uint8.shape[0] // 2
) % expert_uint8.shape[0]
else:
permute_indices = get_w2_permute_indices_with_cache(
cache_permute_indices,
expert_uint8,
epilogue_tile_m,
)
_copy_permuted_expert_to_block_layout(
expert_scratch,
expert_uint8,
permute_indices,
)
expert_uint8.view(-1).copy_(expert_scratch.view(-1))
return weight.view(torch.uint8).view(block_layout_shape).view(torch.bfloat16)
return (
w13_weights_shuffled_tensor.view(torch.bfloat16),
w2_weights_shuffled_tensor.view(torch.bfloat16),
_convert_weight_in_place(w13_weight, is_w13=True),
_convert_weight_in_place(w2_weight, is_w13=False),
)
@@ -36,6 +36,15 @@ def weight_mx_scale(precision_config):
return precision_config.weight_scale
def mx_scale_kwargs(scale):
"""PrecisionConfig weight-scale kwargs: 3.8 uses b_mx_scale/b_microblock_size,
3.5.1/3.6 use weight_scale.
"""
if get_triton_kernels_version() == "3.8":
return {"b_mx_scale": scale, "b_microblock_size": 32}
return {"weight_scale": scale}
def _swizzle_mxfp4(quant_tensor, scale, num_warps=8):
"""Weight swizzle for mxfp4 moe, used for OAI mxfp4 kernel."""
assert has_triton_kernels()
@@ -642,6 +642,19 @@ def sparse_attn_indexer(
assert decode_metadata is not None
kv_cache = kv_cache_as_quant_view(kv_cache, head_dim, use_fp4_cache)
decode_lens = decode_metadata.decode_lens
# requires_padding can be computed False for ragged warmup/mixed
# batches (seen on SM120 TP=2: 8 tokens over 6 seqs -> uniform
# reshape below would crash). The token-count/batch-size divisibility
# check is a necessary-but-not-sufficient proxy for "uniform batch"
# (e.g. decode_lens=[1, 2, 3] divides evenly by 3 but isn't uniform);
# it catches the specific case seen in practice without requiring a
# device sync to inspect decode_lens directly, which would break
# CUDA-graph-capture safety on this path. Shared by both the pack
# branch below and the matching unpack branch further down — they
# must agree on which path was taken.
needs_padded_path = decode_metadata.requires_padding or (
num_decode_tokens % decode_lens.shape[0] != 0
)
if num_decode_tokens == 0:
padded_q_quant_decode_tokens = q_quant[:1].reshape(1, 1, *q_quant.shape[1:])
padded_q_scale = (
@@ -649,7 +662,7 @@ def sparse_attn_indexer(
if q_scale is not None
else None
)
elif decode_metadata.requires_padding:
elif needs_padded_path:
# pad in edge case where we have short chunked prefill length <
# decode_threshold since we unstrictly split
# prefill and decode by decode_threshold
@@ -773,7 +786,7 @@ def sparse_attn_indexer(
cp_kv_cache_interleave_size,
)
if decode_metadata.requires_padding:
if needs_padded_path:
# if padded, we need to unpack
# the topk indices removing padded tokens
topk_indices = unpack_seq_triton(
@@ -9,7 +9,7 @@ from torch.utils._python_dispatch import TorchDispatchMode
from .sanitize import restore_layer_refs, sanitize_layer_refs
from .types import LayerReloadingInfo, LayerTensors
from .utils import get_layer_params_buffers, get_layer_tensors
from .utils import get_layer_params_buffers, get_layer_tensors, get_tensor_load_numel
__all__ = [
"to_meta_tensor",
@@ -206,5 +206,5 @@ def get_numel_loaded(
numel = counter.copied_numel
param = args.arguments.get("param", None)
if isinstance(param, torch.Tensor):
numel = min(numel, param.numel())
numel = min(numel, get_tensor_load_numel(param))
return numel, return_value
@@ -11,6 +11,7 @@ __all__ = [
"get_layer_tensors",
"get_layer_params_buffers",
"get_layer_size",
"get_tensor_load_numel",
"has_device_tensors",
"get_info_size",
]
@@ -30,6 +31,11 @@ def get_layer_params_buffers(layer: torch.nn.Module) -> LayerTensors:
)
def get_tensor_load_numel(tensor: torch.Tensor) -> int:
"""Count checkpoint elements, excluding padding declared by the weight creator."""
return getattr(tensor, "weight_loader_numel", tensor.numel())
def get_layer_size(layer: torch.nn.Module) -> int:
"""Calculate total number of elements across loadable tensors in a layer.
@@ -39,7 +45,7 @@ def get_layer_size(layer: torch.nn.Module) -> int:
from .meta import SKIP_LOAD_TENSORS
return sum(
tensor.numel()
get_tensor_load_numel(tensor)
for name, tensor in get_layer_tensors(layer).items()
if name not in SKIP_LOAD_TENSORS
)
+6 -6
View File
@@ -324,9 +324,9 @@ class AXK1Attention(nn.Module):
assert config.rope_parameters is not None
if config.rope_parameters["rope_type"] != "default":
config.rope_parameters["rope_type"] = (
"deepseek_yarn"
if config.rope_parameters.get("apply_yarn_scaling", True)
else "deepseek_llama_scaling"
"deepseek_llama_scaling"
if config.rope_parameters.get("attention_factor") == 1.0
else "deepseek_yarn"
)
self.rotary_emb = get_rope(
@@ -496,9 +496,9 @@ class AXK1MLAAttention(nn.Module):
assert config.rope_parameters is not None
if config.rope_parameters["rope_type"] != "default":
config.rope_parameters["rope_type"] = (
"deepseek_yarn"
if config.rope_parameters.get("apply_yarn_scaling", True)
else "deepseek_llama_scaling"
"deepseek_llama_scaling"
if config.rope_parameters.get("attention_factor") == 1.0
else "deepseek_yarn"
)
self.rotary_emb = get_rope(
+14 -5
View File
@@ -26,7 +26,10 @@ from vllm.transformers_utils.configs.ovis import AIMv2Config
class AIMv2SwiGLUFFN(nn.Module):
def __init__(
self, config: AIMv2Config, quant_config: QuantizationConfig, prefix: str
self,
config: AIMv2Config,
quant_config: QuantizationConfig | None,
prefix: str,
):
super().__init__()
hidden_features = config.intermediate_size
@@ -91,7 +94,10 @@ class AIMv2ViTPreprocessor(nn.Module):
class AIMv2Attention(nn.Module):
def __init__(
self, config: AIMv2Config, quant_config: QuantizationConfig, prefix: str
self,
config: AIMv2Config,
quant_config: QuantizationConfig | None,
prefix: str,
):
super().__init__()
self.config = config
@@ -144,7 +150,10 @@ class AIMv2Attention(nn.Module):
class AIMv2Block(nn.Module):
def __init__(
self, config: AIMv2Config, quant_config: QuantizationConfig, prefix: str
self,
config: AIMv2Config,
quant_config: QuantizationConfig | None,
prefix: str,
):
super().__init__()
self.attn = AIMv2Attention(
@@ -166,7 +175,7 @@ class AIMv2Transformer(nn.Module):
def __init__(
self,
config: AIMv2Config,
quant_config: QuantizationConfig,
quant_config: QuantizationConfig | None,
*,
require_post_norm: bool | None = None,
prefix: str = "",
@@ -206,7 +215,7 @@ class AIMv2Model(torch.nn.Module):
def __init__(
self,
config: AIMv2Config,
quant_config: QuantizationConfig,
quant_config: QuantizationConfig | None,
*,
require_post_norm: bool | None = None,
prefix: str = "",
+13 -12
View File
@@ -3,6 +3,7 @@
from collections.abc import Iterable, Mapping, Sequence
from typing import Annotated, Literal
import regex as re
import torch
import torch.nn as nn
from transformers import AriaConfig, AriaTextConfig, BatchFeature
@@ -10,7 +11,7 @@ from transformers.models.aria.modeling_aria import AriaCrossAttention
from transformers.models.aria.processing_aria import AriaProcessor
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.layers.fused_moe import FusedMoEFactory
@@ -222,6 +223,7 @@ class AriaTextMoELayer(nn.Module):
intermediate_size=config.intermediate_size,
quant_config=quant_config,
prefix=f"{prefix}.experts",
is_fused_checkpoint_transposed=True,
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
@@ -267,14 +269,17 @@ class AriaTextModel(LlamaModel, SupportsQuant):
"gate_up_proj": ["gate_proj", "up_proj"],
}
# Aria packs all experts into single (transposed) fc1/fc2 tensors, which is
# exactly the pre-fused checkpoint layout FusedMoE self-loads once fc1/fc2
# are renamed to the fused gate_up_proj/down_proj names.
# The fused expert loader expects names without the .weight suffix.
hf_to_vllm_mapper = LlamaModel.hf_to_vllm_mapper | WeightsMapper(
orig_to_new_regex={
re.compile(r"experts\.fc1\.weight$"): "experts.gate_up_proj",
re.compile(r"experts\.fc2\.weight$"): "experts.down_proj",
},
# Quantization configs also use the expert module names.
orig_to_new_substr={
"experts.fc1": "experts.gate_up_proj",
"experts.fc2": "experts.down_proj",
}
},
)
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
@@ -315,22 +320,18 @@ class AriaDummyInputsBuilder(BaseDummyInputsBuilder[AriaProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
vision_config = self.info.get_vision_config()
max_image_size = vision_config.image_size
num_images = mm_counts.get("image", 0)
image_overrides = mm_options.get("image")
assert image_overrides is None or isinstance(image_overrides, ImageDummyOptions)
return {
"image": self._get_dummy_images(
width=max_image_size,
height=max_image_size,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+4 -7
View File
@@ -30,7 +30,7 @@ from transformers.models.audioflamingo3 import (
from transformers.models.qwen2_audio import Qwen2AudioEncoder
from vllm.config import VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import ModalityData, MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.models.module_mapping import MultiModelKeys
@@ -216,21 +216,18 @@ class AudioFlamingo3DummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
hf_processor = self.info.get_hf_processor()
feature_extractor = self.info.get_feature_extractor()
sampling_rate = feature_extractor.sampling_rate
audio_len = int(hf_processor.max_audio_len * sampling_rate)
num_audios = mm_counts.get("audio", 0)
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
return {
"audio": self._get_dummy_audios(
length=audio_len,
num_audios=num_audios,
overrides=audio_overrides,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
)
}
+4 -7
View File
@@ -14,7 +14,7 @@ import torch
import torch.nn as nn
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.logger import init_logger
from vllm.model_executor.layers.activation import get_act_fn
@@ -248,23 +248,20 @@ class BagelDummyInputsBuilder(BaseDummyInputsBuilder[BagelProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
hf_config = self.info.get_hf_config()
vit_config = hf_config.vit_config
# Use the configured image size
image_size = vit_config.image_size
image_overrides = mm_options.get("image")
assert image_overrides is None or isinstance(image_overrides, ImageDummyOptions)
return {
"image": self._get_dummy_images(
width=image_size,
height=image_size,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
}
@@ -13,7 +13,7 @@ import torch.nn as nn
from transformers import AutoProcessor, BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
@@ -103,7 +103,7 @@ class BailingMoeV3VLDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
target_width, target_height = self.info.get_image_size_with_most_features()
return {
+4 -9
View File
@@ -8,7 +8,7 @@ import torch.nn as nn
from transformers.activations import GELUActivation
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -90,21 +90,16 @@ class BeeDummyInputsBuilder(LlavaDummyInputsBuilder[BeeProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
assert image_overrides is None or isinstance(image_overrides, ImageDummyOptions)
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
}
+4 -8
View File
@@ -15,7 +15,7 @@ from transformers import (
)
from vllm.config import CacheConfig, VllmConfig
from vllm.config.multimodal import BaseDummyOptions, ImageDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.layers.quantization import QuantizationConfig
@@ -444,23 +444,19 @@ class Blip2DummyInputsBuilder(BaseDummyInputsBuilder[Blip2ProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
hf_config = self.info.get_hf_config()
vision_config = hf_config.vision_config
max_image_size = vision_config.image_size
num_images = mm_counts.get("image", 0)
image_overrides = mm_options.get("image")
assert image_overrides is None or isinstance(image_overrides, ImageDummyOptions)
return {
"image": self._get_dummy_images(
width=max_image_size,
height=max_image_size,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+4 -8
View File
@@ -15,7 +15,7 @@ from transformers import (
)
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import divide, get_tensor_model_parallel_world_size
from vllm.inputs import MultiModalDataDict, MultiModalInput
from vllm.model_executor.layers.activation import get_act_fn
@@ -205,20 +205,16 @@ class CLIPDummyInputsBuilder(BaseDummyInputsBuilder[CLIPProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+17 -6
View File
@@ -35,7 +35,7 @@ from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from .commandr import LayerNorm
from .interfaces import SupportsPP, SupportsQuant
from .interfaces import EagleModelMixin, SupportsEagle3, SupportsPP, SupportsQuant
from .utils import (
AutoWeightsLoader,
WeightsMapper,
@@ -385,7 +385,7 @@ class Cohere2MoeDecoderLayer(nn.Module):
@support_torch_compile
class Cohere2MoeModel(nn.Module):
class Cohere2MoeModel(nn.Module, EagleModelMixin):
"""Transformer decoder for Cohere2Moe."""
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
@@ -439,7 +439,7 @@ class Cohere2MoeModel(nn.Module):
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
) -> torch.Tensor | IntermediateTensors | tuple[torch.Tensor, list[torch.Tensor]]:
if get_pp_group().is_first_rank:
if inputs_embeds is not None:
hidden_states = inputs_embeds
@@ -450,17 +450,28 @@ class Cohere2MoeModel(nn.Module):
assert intermediate_tensors is not None
hidden_states = intermediate_tensors["hidden_states"]
residual = intermediate_tensors["residual"]
for layer in islice(self.layers, self.start_layer, self.end_layer):
aux_hidden_states = []
if self.start_layer in self.aux_hidden_state_layers:
aux_hidden_states.append(hidden_states)
for layer_idx, layer in enumerate(
islice(self.layers, self.start_layer, self.end_layer),
start=self.start_layer,
):
hidden_states, residual = layer(positions, hidden_states, residual)
if layer_idx + 1 in self.aux_hidden_state_layers:
aux_hidden_states.append(hidden_states)
if not get_pp_group().is_last_rank:
return IntermediateTensors(
{"hidden_states": hidden_states, "residual": residual}
)
hidden_states, _ = self.norm(hidden_states, residual)
if aux_hidden_states:
return hidden_states, aux_hidden_states
return hidden_states
class Cohere2MoeForCausalLM(nn.Module, SupportsPP, SupportsQuant):
class Cohere2MoeForCausalLM(nn.Module, SupportsPP, SupportsQuant, SupportsEagle3):
is_text_generation_model = True
hf_to_vllm_mapper = WeightsMapper(
@@ -520,7 +531,7 @@ class Cohere2MoeForCausalLM(nn.Module, SupportsPP, SupportsQuant):
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
) -> torch.Tensor | IntermediateTensors | tuple[torch.Tensor, list[torch.Tensor]]:
return self.model(input_ids, positions, intermediate_tensors, inputs_embeds)
def compute_logits(
+4 -7
View File
@@ -18,7 +18,7 @@ from transformers.models.cohere2_vision.processing_cohere2_vision import (
)
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import MulAndSilu
from vllm.model_executor.layers.linear import (
@@ -202,19 +202,16 @@ class Cohere2VisionDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
image_size = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=image_size.width,
height=image_size.height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+14 -6
View File
@@ -12,7 +12,7 @@ from transformers import PretrainedConfig
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.inputs import MultiModalDataDict, PromptType, TokensPrompt
@@ -1206,10 +1206,18 @@ class RelPositionMultiHeadAttention(CohereASRMultiHeadAttention):
matrix_bd = torch.matmul(q_with_bias_v, p.transpose(-2, -1))
matrix_bd = self.rel_shift(matrix_bd)
# drops extra elements in the matrix_bd to match the matrix_ac's size
matrix_ac = torch.matmul(q_with_bias_u, k.transpose(-2, -1))
matrix_bd = matrix_bd[:, :, :, : matrix_ac.size(-1)]
scores = (matrix_ac + matrix_bd) / self.s_d_k # (batch, head, time1, time2)
# drops extra elements in matrix_bd to match the key sequence length
matrix_bd = matrix_bd[:, :, :, : k.size(-2)]
batch, heads, query_len, key_len = matrix_bd.shape
scale = 1.0 / self.s_d_k
scores = torch.baddbmm(
matrix_bd.flatten(0, 1),
q_with_bias_u.flatten(0, 1),
k.transpose(-2, -1).flatten(0, 1),
beta=scale,
alpha=scale,
).view(batch, heads, query_len, key_len)
return self.forward_attention(v, scores, mask)
@@ -1936,7 +1944,7 @@ class CohereASRDummyInputsBuilder(BaseDummyInputsBuilder[CohereASRProcessingInfo
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
mm_processor_kwargs=None,
) -> MultiModalDataDict:
feature_extractor = self.info.get_feature_extractor()
+4 -7
View File
@@ -51,7 +51,7 @@ from transformers.models.cohere_compass.image_processing_cohere_compass import (
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import (
get_pp_group,
get_tensor_model_parallel_world_size,
@@ -1238,11 +1238,8 @@ class CohereCompassDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
image_overrides = mm_options.get("image")
target_image_width, target_image_height = (
self.info.get_image_size_with_most_features()
)
@@ -1251,8 +1248,8 @@ class CohereCompassDummyInputsBuilder(
"image": self._get_dummy_images(
width=target_image_width,
height=target_image_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
}
+4 -6
View File
@@ -15,7 +15,7 @@ from torch import nn
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.pooler.tokwise import pooler_for_token_embed
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -135,18 +135,16 @@ class ColModernVBertDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+3 -5
View File
@@ -11,7 +11,7 @@ import torch.nn as nn
from transformers import BatchFeature, CLIPVisionConfig
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.models.interfaces import (
MultiModalEmbeddings,
@@ -268,17 +268,15 @@ class DeepseekOCRDummyInputsBuilder(BaseDummyInputsBuilder[DeepseekOCRProcessing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
max_image_size = self.info.get_image_size_with_most_features()
return {
"image": self._get_dummy_images(
width=max_image_size.width,
height=max_image_size.height,
num_images=num_images,
num_images=mm_counts.get("image", 0),
)
}
+3 -5
View File
@@ -11,7 +11,7 @@ import torch.nn as nn
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.models.interfaces import (
MultiModalEmbeddings,
@@ -140,17 +140,15 @@ class DeepseekOCR2DummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
max_image_size = self.info.get_image_size_with_most_features()
return {
"image": self._get_dummy_images(
width=max_image_size.width,
height=max_image_size.height,
num_images=num_images,
num_images=mm_counts.get("image", 0),
)
}
+6 -6
View File
@@ -540,9 +540,9 @@ class DeepseekV2Attention(nn.Module):
)
if config.rope_parameters["rope_type"] != "default":
config.rope_parameters["rope_type"] = (
"deepseek_yarn"
if config.rope_parameters.get("apply_yarn_scaling", True)
else "deepseek_llama_scaling"
"deepseek_llama_scaling"
if config.rope_parameters.get("attention_factor") == 1.0
else "deepseek_yarn"
)
self.rotary_emb = get_rope(
@@ -1107,9 +1107,9 @@ class DeepseekV2MLAAttention(nn.Module):
if config.rope_parameters["rope_type"] != "default":
config.rope_parameters["rope_type"] = (
"deepseek_yarn"
if config.rope_parameters.get("apply_yarn_scaling", True)
else "deepseek_llama_scaling"
"deepseek_llama_scaling"
if config.rope_parameters.get("attention_factor") == 1.0
else "deepseek_yarn"
)
self.rotary_emb = get_rope(
+4 -8
View File
@@ -15,7 +15,7 @@ from einops import rearrange, repeat
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.quantization import QuantizationConfig
@@ -212,20 +212,16 @@ class DeepseekVL2DummyInputsBuilder(BaseDummyInputsBuilder[DeepseekVL2Processing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
max_image_size = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=max_image_size.width,
height=max_image_size.height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+43 -116
View File
@@ -46,7 +46,11 @@ from vllm.model_executor.models.gemma4_mm import (
)
from vllm.model_executor.models.module_mapping import MultiModelKeys
from vllm.model_executor.models.transformers.utils import recursive_replace_linear
from vllm.model_executor.models.utils import WeightsMapper, maybe_prefix
from vllm.model_executor.models.utils import (
AutoWeightsLoader,
WeightsMapper,
maybe_prefix,
)
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.platforms import current_platform
from vllm.utils.torch_utils import async_tensor_h2d
@@ -160,14 +164,12 @@ class DiffusionGemmaForConditionalGeneration(
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
"model.decoder.self_conditioning.": "self_conditioning.",
"model.decoder.": "model.",
"model.encoder.language_model.": "model.",
"model.encoder.vision_tower.": "vision_tower.",
"model.encoder.embed_vision.": "embed_vision.",
},
orig_to_new_substr={
".experts.": ".moe.experts.",
},
)
packed_modules_mapping = {
@@ -336,113 +338,12 @@ class DiffusionGemmaForConditionalGeneration(
logits = _softcap_logits(logits, self.final_logit_softcapping)
return logits
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
"""Load weights from checkpoint.
Checkpoint layout (HF DiffusionGemma):
model.encoder.vision_tower.* → vision tower
model.encoder.embed_vision.* → vision embedder
model.encoder.language_model.layers.* → backbone
model.decoder.layers.* → backbone (tied)
model.decoder.embed_tokens.* → embeddings
model.decoder.self_conditioning.* → self-conditioning MLP
lm_head.* → LM head (tied)
We load encoder weights into our single ``Gemma4Model`` backbone,
skip duplicate decoder backbone weights, handle vision tower and
self-conditioning separately.
"""
sc_params = dict(
(n, p)
for n, p in self.named_parameters()
if n.startswith("self_conditioning.")
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# Some checkpoints carry a vestigial Gemma3n-style embedding table.
loader = AutoWeightsLoader(
self, ignore_unexpected_prefixes=["embed_vision.embedding."]
)
# Collect vision tower + embedder parameters AND buffers for manual
# loading. The HF vision tower registers std_bias / std_scale as
# buffers (not parameters) when config.standardize is True, so we
# must include named_buffers() to avoid "not found in model" warnings.
vision_params: dict[str, torch.Tensor] = {}
for n, p in self.named_parameters():
if n.startswith(("vision_tower.", "embed_vision.")):
vision_params[n] = p
for n, b in self.named_buffers():
if n.startswith(("vision_tower.", "embed_vision.")):
vision_params[n] = b
def _remap_weights():
# Use full weight names (including suffixes like .weight_scale,
# .weight_packed) for dedup instead of just the base layer name. Critical
# for quantized checkpoints where each weight has multiple tensors;
# tracking only base names skips scales as duplicates.
seen_weights: set[str] = set()
for name, weight in weights:
# Self-conditioning lives under model.decoder.self_conditioning.*
# in the checkpoint but at self_conditioning.* in our model.
if "self_conditioning" in name:
sc_name = name.split("self_conditioning.", 1)[1]
sc_name = "self_conditioning." + sc_name
if sc_name in sc_params:
sc_params[sc_name].data.copy_(weight)
continue
# Vision tower: model.encoder.vision_tower.* → vision_tower.*
# In HF, the vision tower is a sibling of language_model
# under the encoder module.
if name.startswith("model.encoder.vision_tower."):
vt_name = name[len("model.encoder.") :]
if vt_name in vision_params:
vision_params[vt_name].data.copy_(weight)
else:
logger.warning(
"Vision tower weight %s (mapped to %s) not found in model",
name,
vt_name,
)
continue
# Vision embedder: model.encoder.embed_vision.* → embed_vision.*
if name.startswith("model.encoder.embed_vision."):
ev_name = name[len("model.encoder.") :]
if ev_name in vision_params:
vision_params[ev_name].data.copy_(weight)
else:
logger.warning(
"Embed vision weight %s (mapped to %s) not found in model",
name,
ev_name,
)
continue
# Skip vestigial embed_vision.embedding weights.
if "embed_vision.embedding." in name:
continue
# Encoder backbone → model.*
if name.startswith("model.encoder.language_model."):
name = name.replace("model.encoder.language_model.", "model.")
# Decoder backbone → model.* (skip exact duplicates)
elif name.startswith("model.decoder."):
name = name.replace("model.decoder.", "model.")
# Skip only if we've seen the exact same weight name (including scales)
if name in seen_weights:
continue
seen_weights.add(name)
yield name, weight
# Delegate to Gemma4ForCausalLM.load_weights for the backbone,
# which handles stacked params, MoE, k_eq_v, etc.
# Temporarily set self.config to text_config since Gemma4's
# load_weights expects it (e.g. tie_word_embeddings, layer_types).
from vllm.model_executor.models.gemma4 import Gemma4ForCausalLM
saved_config = self.config
self.config = self.model.config
try:
Gemma4ForCausalLM.load_weights(self, _remap_weights())
finally:
self.config = saved_config
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
@classmethod
def get_placeholder_str(cls, modality: str, i: int) -> str | None:
@@ -1066,6 +967,7 @@ class DiffusionSampler:
tp_group_name: str = "",
):
self.sampling_states = sampler.sampling_states
self.logprob_token_ids_state = sampler.logprob_token_ids_state
self.req_states = sampler.req_states
self.logits_mode = sampler.logprobs_mode in ("raw_logits", "processed_logits")
# Self-conditioning soft embed = probs @ embed_weight * normalizer,
@@ -1112,7 +1014,7 @@ class DiffusionSampler:
# on the subsequent commit step when num_sampled=CANVAS_LEN.
self._pending_logprobs: dict[int, LogprobsTensors] = {}
def add_request(self, req_idx: int, prompt_len: int, sampling_params: Any) -> None:
def add_request(self, req_idx: int, sampling_params: Any) -> None:
if use_penalty(sampling_params):
logger.warning_once(
"DiffusionGemma does not support repetition/frequency/presence "
@@ -1122,9 +1024,11 @@ class DiffusionSampler:
# that was aborted between its converging denoise and commit steps.
self._pending_logprobs.pop(req_idx, None)
self.sampling_states.add_request(req_idx, sampling_params)
self.logprob_token_ids_state.add_request(req_idx, sampling_params)
def apply_staged_writes(self) -> None:
self.sampling_states.apply_staged_writes()
self.logprob_token_ids_state.apply_staged_writes()
@property
def penalties_state(self):
@@ -1312,8 +1216,12 @@ class DiffusionSampler:
is_committing = states.is_encoder_phase[decode_slots].clone()
slots_np = input_batch.idx_mapping_np[:num_reqs]
is_decode_np = per_req_nlogits_np > 0
max_num_logprobs = self.sampling_states.max_num_logprobs(slots_np)
# Requests may ask for specific token ids' logprobs instead of, or as
# well as, a top-k.
max_token_ids = self.logprob_token_ids_state.max_num_token_ids(slots_np)
want_logprobs = max_num_logprobs >= 0 or max_token_ids > 0
num_logprobs = max(max_num_logprobs, 0)
# Sample over the [num_decode * CL, vocab] logits. The fp32 pipeline in
# _compiled_sample_step keeps several live [group * CL, vocab] copies, so
@@ -1371,7 +1279,7 @@ class DiffusionSampler:
# Logprobs for denoise steps that just converged (is_encoder_phase
# flipped False→True), stashed per tile so `scaled` is freed each tile.
if max_num_logprobs >= 0:
if want_logprobs:
converged_mask = states.is_encoder_phase[tile_slots]
just_converged = converged_mask & ~is_committing[tile]
if just_converged.any():
@@ -1385,24 +1293,43 @@ class DiffusionSampler:
# positions are never emitted.
k_i = int(valid_canvas_len_np[start_req + li])
pos = li * CL
per_req_ids = max_token_ids > 0
self._pending_logprobs[slot.item()] = compute_topk_scores(
flat_logits[pos : pos + k_i],
max_num_logprobs,
num_logprobs,
argmax_tokens[local_idx][:k_i],
logprob_token_ids_state=(
self.logprob_token_ids_state if per_req_ids else None
),
# every row of this stash belongs to one slot
expanded_idx_mapping=(
torch.full(
(k_i,),
slot.item(),
dtype=torch.int32,
device=flat_logits.device,
)
if per_req_ids
else None
),
max_per_req_token_ids=max_token_ids,
logits_mode=self.logits_mode,
)
# Commit steps: is_committing was True at entry. Reassemble previously
# stashed logprobs and attach to SamplerOutput.
logprobs_tensors = None
if max_num_logprobs >= 0 and is_committing.any() and self._pending_logprobs:
if want_logprobs and is_committing.any() and self._pending_logprobs:
committing_slots = set(
decode_slots_np[is_committing.cpu().numpy()].tolist()
)
parts_ids, parts_lp, parts_ranks = [], [], []
cu_gen: list[int] = []
flat_offset = 0
for i in range(num_reqs):
cu_gen.append(flat_offset)
slot = int(slots_np[i])
if is_decode_np[i] and slot in self._pending_logprobs:
if slot in committing_slots and slot in self._pending_logprobs:
lp = self._pending_logprobs.pop(slot)
parts_ids.append(lp.logprob_token_ids)
parts_lp.append(lp.logprobs)
+4 -8
View File
@@ -9,7 +9,7 @@ from torch.nn import LayerNorm
from transformers.models.qwen2_vl import Qwen2VLProcessor
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import utils as dist_utils
from vllm.distributed.parallel_state import (
get_tensor_model_parallel_rank,
@@ -104,20 +104,16 @@ class DotsOCRDummyInputsBuilder(Qwen2VLDummyInputsBuilder):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
}
+6 -13
View File
@@ -36,7 +36,7 @@ from einops import rearrange
from transformers import BaseImageProcessor, BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions, VideoDummyOptions
from vllm.distributed import parallel_state
from vllm.distributed import utils as dist_utils
from vllm.inputs import MultiModalDataDict
@@ -1276,33 +1276,26 @@ class Ernie4_5_VLDummyInputsBuilder(BaseDummyInputsBuilder[Ernie4_5_VLProcessing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_videos = mm_counts.get("video", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = self.info.get_num_frames_with_most_features(
seq_len, mm_counts
)
image_overrides = mm_options.get("image")
video_overrides = mm_options.get("video")
assert video_overrides is None or isinstance(video_overrides, VideoDummyOptions)
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
"video": self._get_dummy_videos(
width=target_width,
height=target_height,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides,
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video"),
),
}
+5 -7
View File
@@ -12,7 +12,7 @@ from transformers import (
)
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.inputs import MultiModalDataDict, PromptType
from vllm.logger import init_logger
@@ -207,20 +207,18 @@ class FireRedASR2DummyInputsBuilder(BaseDummyInputsBuilder[FireRedASR2Processing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
feature_extractor = self.info.get_feature_extractor()
sampling_rate = feature_extractor.sampling_rate
audio_len = feature_extractor.chunk_length * sampling_rate
num_audios = mm_counts.get("audio", 0)
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
ret = {
"audio": self._get_dummy_audios(
length=audio_len, num_audios=num_audios, overrides=audio_overrides
length=audio_len,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
)
}
return ret
+4 -8
View File
@@ -14,7 +14,7 @@ from transformers import (
)
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.inputs import MultiModalDataDict, PromptType
@@ -734,22 +734,18 @@ class FunASRDummyInputsBuilder(BaseDummyInputsBuilder[FunASRProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
feature_extractor = self.info.get_feature_extractor()
sampling_rate = feature_extractor.sampling_rate
audio_len = feature_extractor.chunk_length * sampling_rate
num_audios = mm_counts.get("audio", 0)
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
return {
"audio": self._get_dummy_audios(
length=audio_len,
num_audios=num_audios,
overrides=audio_overrides,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
),
}
+4 -7
View File
@@ -26,7 +26,7 @@ from transformers.feature_extraction_utils import BatchFeature
from transformers.modeling_outputs import BaseModelOutput
from vllm.config import VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.attention.mm_encoder_attention import MMEncoderAttention
from vllm.model_executor.layers.linear import QKVParallelLinear, RowParallelLinear
@@ -580,7 +580,7 @@ class FunAudioChatDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
feature_extractor = self.info.get_feature_extractor()
sampling_rate = int(feature_extractor.sampling_rate)
@@ -597,15 +597,12 @@ class FunAudioChatDummyInputsBuilder(
1,
(target_num_frames * sampling_rate + token_fps - 1) // token_fps,
)
num_audios = int(mm_counts.get("audio", 0))
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
return {
"audio": self._get_dummy_audios(
length=audio_len,
num_audios=num_audios,
overrides=audio_overrides,
num_audios=int(mm_counts.get("audio", 0)),
overrides=mm_options.get("audio"),
)
}
+4 -8
View File
@@ -11,7 +11,7 @@ from transformers.models.gemma3.image_processing_gemma3 import Gemma3ImageProces
from transformers.models.gemma3.processing_gemma3 import Gemma3ProcessorKwargs
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.logger import init_logger
from vllm.model_executor.layers.layernorm import GemmaRMSNorm
@@ -244,20 +244,16 @@ class Gemma3DummyInputsBuilder(BaseDummyInputsBuilder[Gemma3ProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+6 -12
View File
@@ -18,7 +18,7 @@ from transformers.models.gemma3n import (
from transformers.models.siglip import SiglipImageProcessorFast
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.inputs import MultiModalDataDict, PromptType, TextPrompt
from vllm.logger import init_logger
@@ -232,10 +232,8 @@ class Gemma3nDummyInputsBuilder(BaseDummyInputsBuilder[Gemma3nProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_audios = mm_counts.get("audio", 0)
processor = self.info.get_hf_processor()
audio_feature_extractor: Gemma3nAudioFeatureExtractor = (
processor.feature_extractor
@@ -245,21 +243,17 @@ class Gemma3nDummyInputsBuilder(BaseDummyInputsBuilder[Gemma3nProcessingInfo]):
img_width = image_processor.size.get("width", 224)
img_height = image_processor.size.get("height", 224)
image_overrides = mm_options.get("image")
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
return {
"image": self._get_dummy_images(
width=img_width,
height=img_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
"audio": self._get_dummy_audios(
length=audio_len,
num_audios=num_audios,
overrides=audio_overrides,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
),
}
+114 -363
View File
@@ -22,12 +22,12 @@ from collections.abc import Iterable
from dataclasses import replace
from itertools import islice
import regex as re
import torch
from torch import nn
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
from vllm.config.utils import getattr_iter
from vllm.distributed import (
get_pp_group,
get_tensor_model_parallel_rank,
@@ -40,7 +40,7 @@ from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
fused_moe_make_expert_params_mapping,
MoERunner,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
@@ -57,10 +57,6 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
ParallelLMHead,
VocabParallelEmbedding,
)
from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader,
maybe_remap_kv_scale_name,
)
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from vllm.transformers_utils.configs.gemma4 import gemma4_layer_config
@@ -73,27 +69,63 @@ from .interfaces import (
SupportsEagle3,
SupportsLoRA,
SupportsPP,
SupportsQuant,
)
from .utils import (
AutoWeightsLoader,
PPMissingLayer,
ShardIds,
WeightsMapper,
extract_layer_index,
is_pp_missing_parameter,
make_layers,
maybe_prefix,
)
logger = init_logger(__name__)
_GEMMA4_EXPERT_PARENT_MAPPER = WeightsMapper(
orig_to_new_regex={
re.compile(r"(?<!\.moe)\.experts$"): ".moe.experts",
def _gemma4_layer_weights_mapper(config) -> WeightsMapper:
"""Stack each decoder layer's projections the way its modules are built.
gate/up pack into `mlp.gate_up_proj`. Layers with a qkv_proj pack q/k/v
into it; `attention_k_eq_v` full-attention layers ship k_proj only, so K
is loaded into both the K and V shards and no v_proj is expected. KV-shared
layers only have q_proj; the K/V tensors original checkpoints still ship
for them are dropped.
"""
num_layers = config.num_hidden_layers
first_kv_shared = num_layers - getattr(config, "num_kv_shared_layers", 0)
k_eq_v_layers = (
{
i
for i, layer_type in enumerate(config.layer_types[:first_kv_shared])
if layer_type == "full_attention"
}
if getattr(config, "attention_k_eq_v", False)
else set()
)
qkv_shards: tuple[tuple[str, ShardIds], ...] = (("q", "q"), ("k", "k"), ("v", "v"))
k_eq_v_shards: tuple[tuple[str, ShardIds], ...] = (("q", "q"), ("k", ["k", "v"]))
stacked: dict[str, tuple[str, ShardIds]] = {
".mlp.gate_proj.": (".mlp.gate_up_proj.", 0),
".mlp.up_proj.": (".mlp.gate_up_proj.", 1),
}
)
def _remap_gemma4_expert_weight_name(name: str) -> str:
return re.sub(r"(?<!\.moe)\.experts\.(\d+)\.", r".moe.experts.\1.", name)
stacked |= {
f"layers.{i}.self_attn.{shard}_proj.": (
f"layers.{i}.self_attn.qkv_proj.",
shard_id,
)
for i in range(first_kv_shared)
for shard, shard_id in (k_eq_v_shards if i in k_eq_v_layers else qkv_shards)
}
return WeightsMapper(
orig_to_new_substr={
f"layers.{i}.self_attn.{name}.": None
for i in range(first_kv_shared, num_layers)
for name in ("k_proj", "v_proj", "k_norm")
},
orig_to_new_stacked=stacked,
)
@triton.jit
@@ -279,6 +311,9 @@ class Gemma4Router(nn.Module):
self.norm = RMSNorm(self.hidden_size, eps=config.rms_norm_eps, has_weight=False)
# Per-dimension learned scale, applied after norm + root_size
self.scale = nn.Parameter(torch.ones(self.hidden_size))
# Per-expert output scale folded into routing weights so that
# MoERunner's fused kernel computes: Σ_e (expert_e * w_e * scale_e)
self.per_expert_scale = nn.Parameter(torch.ones(config.num_experts))
# Constant 1/sqrt(hidden_size) scaling factor
self.register_buffer(
"root_size",
@@ -296,6 +331,29 @@ class Gemma4Router(nn.Module):
prefix=f"{prefix}.proj",
)
def routing_function(
self,
hidden_states: torch.Tensor,
gating_output: torch.Tensor,
topk: int,
renormalize: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Softmax over ALL experts → top-k → renormalize.
MoERunner's built-in fused_topk scopes softmax differently, so Gemma4
needs its own routing for numerical correctness.
NOTE: self.per_expert_scale is read at call time (not captured into a
local) so that torch.func.functional_call parameter substitution
reaches the routing function correctly.
"""
if current_platform.is_cuda_alike() or current_platform.is_xpu():
return gemma4_fused_routing_kernel_triton(
gating_output, topk, self.per_expert_scale
)
return gemma4_routing_function_torch(gating_output, topk, self.per_expert_scale)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Returns raw router logits [T, E]."""
x = self.norm(x)
@@ -305,77 +363,6 @@ class Gemma4Router(nn.Module):
return router_logits
class Gemma4MoE(nn.Module):
"""Mixture of Experts for Gemma4 using vLLM's MoERunner.
Wraps MoERunner with custom routing. The router projection is
external (Gemma4Router) — this class only handles expert dispatch.
Gemma4 routing: softmax over ALL experts → top-k → renormalize.
per_expert_scale is folded into routing weights for mathematical
correctness with MoERunner's fused kernel.
"""
def __init__(
self,
config,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
super().__init__()
self.hidden_size = config.hidden_size
self.num_experts = config.num_experts
# Per-expert output scale folded into routing weights so that
# MoERunner's fused kernel computes: Σ_e (expert_e * w_e * scale_e)
self.per_expert_scale = nn.Parameter(torch.ones(config.num_experts))
# Gemma4 routing: softmax over ALL experts → top-k → renormalize.
# MoERunner's built-in fused_topk scopes softmax differently, so
# a custom routing function is needed for numerical correctness.
# NOTE: self.per_expert_scale is read at call time (not captured into
# a local) so that torch.func.functional_call parameter substitution
# reaches the routing function correctly.
def routing_function(
hidden_states: torch.Tensor,
gating_output: torch.Tensor,
topk: int,
renormalize: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
if current_platform.is_cuda_alike() or current_platform.is_xpu():
return gemma4_fused_routing_kernel_triton(
gating_output, topk, self.per_expert_scale
)
return gemma4_routing_function_torch(
gating_output, topk, self.per_expert_scale
)
# MoERunner experts with custom Gemma4 routing
intermediate_size = getattr(
config,
"moe_intermediate_size",
getattr(config, "expert_intermediate_size", None),
)
if intermediate_size is None:
raise ValueError("Gemma4 MoE requires an expert intermediate size")
self.experts = FusedMoEFactory(
num_experts=config.num_experts,
top_k=config.top_k_experts,
hidden_size=config.hidden_size,
intermediate_size=intermediate_size,
renormalize=True,
quant_config=quant_config,
prefix=f"{prefix}.experts",
custom_routing_function=routing_function,
activation="gelu_tanh",
)
def forward(self, x: torch.Tensor, router_logits: torch.Tensor) -> torch.Tensor:
return self.experts(x, router_logits)
class Gemma4Attention(nn.Module):
def __init__(
self,
@@ -433,7 +420,7 @@ class Gemma4Attention(nn.Module):
else:
# QKVParallelLinear handles GQA correctly for all layer types.
# k_eq_v layers load K weights into both K and V slots via
# _weight_iterator remapping — no structural difference needed.
# hf_to_vllm_mapper — no structural difference needed.
self.qkv_proj = QKVParallelLinear(
hidden_size,
self.head_dim,
@@ -645,7 +632,7 @@ class Gemma4DecoderLayer(nn.Module):
config, "use_second_mlp_block", False
)
self.router: Gemma4Router | None
self.moe: Gemma4MoE | None
self.experts: MoERunner | None
self.post_feedforward_layernorm_1: RMSNorm | None
self.post_feedforward_layernorm_2: RMSNorm | None
self.pre_feedforward_layernorm_2: RMSNorm | None
@@ -655,10 +642,20 @@ class Gemma4DecoderLayer(nn.Module):
quant_config=quant_config,
prefix=f"{prefix}.router",
)
self.moe = Gemma4MoE(
config,
names = ("moe_intermediate_size", "expert_intermediate_size")
intermediate_size = getattr_iter(config, names)
if intermediate_size is None:
raise ValueError("Gemma4 MoE requires an expert intermediate size")
self.experts = FusedMoEFactory(
num_experts=config.num_experts,
top_k=config.top_k_experts,
hidden_size=config.hidden_size,
intermediate_size=intermediate_size,
renormalize=True,
quant_config=quant_config,
prefix=f"{prefix}.moe",
prefix=f"{prefix}.experts",
custom_routing_function=self.router.routing_function,
activation="gelu_tanh",
)
self.post_feedforward_layernorm_1 = RMSNorm(
config.hidden_size, eps=config.rms_norm_eps
@@ -671,7 +668,7 @@ class Gemma4DecoderLayer(nn.Module):
)
else:
self.router = None
self.moe = None
self.experts = None
self.post_feedforward_layernorm_1 = None
self.post_feedforward_layernorm_2 = None
self.pre_feedforward_layernorm_2 = None
@@ -747,13 +744,13 @@ class Gemma4DecoderLayer(nn.Module):
assert self.post_feedforward_layernorm_1 is not None
assert self.pre_feedforward_layernorm_2 is not None
assert self.router is not None
assert self.moe is not None
assert self.experts is not None
assert self.post_feedforward_layernorm_2 is not None
hidden_states_1 = self.post_feedforward_layernorm_1(hidden_states)
hidden_states_2 = self.pre_feedforward_layernorm_2(residual)
router_logits = self.router(residual)
hidden_states_2 = self.moe(hidden_states_2, router_logits)
hidden_states_2 = self.experts(hidden_states_2, router_logits)
hidden_states_2 = self.post_feedforward_layernorm_2(hidden_states_2)
# Combine MLP and MoE outputs
@@ -983,7 +980,7 @@ class Gemma4CrossDecoderLayers(nn.Module):
@support_torch_compile(
enable_if=lambda vllm_config: not vllm_config.cache_config.kv_sharing_fast_prefill
)
class Gemma4Model(nn.Module, EagleModelMixin):
class Gemma4Model(nn.Module, EagleModelMixin, SupportsQuant):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = _get_text_config(vllm_config.model_config.hf_config)
@@ -991,6 +988,7 @@ class Gemma4Model(nn.Module, EagleModelMixin):
quant_config = vllm_config.quant_config
self.config = config
self.quant_config = quant_config
self.hf_to_vllm_mapper = _gemma4_layer_weights_mapper(config)
# PLE config values (default to 0 if not present — disables PLE)
self.hidden_size_per_layer_input = getattr(
@@ -1391,152 +1389,21 @@ class Gemma4Model(nn.Module, EagleModelMixin):
return hidden_states
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
stacked_params_mapping = [
# (param_name, shard_name, shard_id)
("qkv_proj", "q_proj", "q"),
("qkv_proj", "k_proj", "k"),
("qkv_proj", "v_proj", "v"),
("gate_up_proj", "gate_proj", 0),
("gate_up_proj", "up_proj", 1),
]
# MoE expert weight mapping: checkpoint can have either:
# 1. 3D packed tensors (exploded in _weight_iterator to per-expert 2D)
# 2. Already per-expert 2D weights (if quantized)
# Map to MoERunner parameters:
# moe.experts.{id}.gate_proj → MoERunner w1 (shard of w13)
# moe.experts.{id}.up_proj → MoERunner w3 (shard of w13)
# moe.experts.{id}.down_proj → MoERunner w2
num_experts = getattr(self.config, "num_experts", None) or 0
# Strategy A: dot-separated suffix
# (standard AWQ/GPTQ e.g. .qweight, .scales, .weight)
dot_suffix_expert_params_mapping = fused_moe_make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
ckpt_up_proj_name="up_proj",
num_experts=num_experts,
)
# Strategy B: underscore-separated suffix
# (CompressedTensors-format AWQ/W4A16 _packed, _scale)
underscore_suffix_expert_params_mapping = [
(
f"{param_name}weight_",
f"{weight_name.rstrip('.')}_",
expert_id,
shard_id,
)
for (
param_name,
weight_name,
expert_id,
shard_id,
) in dot_suffix_expert_params_mapping
]
expert_params_mapping = (
dot_suffix_expert_params_mapping + underscore_suffix_expert_params_mapping
)
params_dict = dict(self.named_parameters())
# Include buffers (e.g. layer_scalar) so they can be loaded too
params_dict.update(dict(self.named_buffers()))
loaded_params: set[str] = set()
for name, loaded_weight in weights:
if name.endswith((".k_scale", ".v_scale", ".q_scale", ".prob_scale")):
remapped_name = maybe_remap_kv_scale_name(name, params_dict)
if remapped_name is not None and remapped_name in params_dict:
param = params_dict[remapped_name]
weight_loader = getattr(
param, "weight_loader", default_weight_loader
)
weight_loader(param, loaded_weight)
loaded_params.add(remapped_name)
continue
for param_name, shard_name, shard_id in stacked_params_mapping:
if shard_name not in name:
continue
stacked_name = name.replace(shard_name, param_name)
# KV-shared layers have a plain q_proj instead of a packed
# qkv_proj: fall through to the direct load, which also
# skips the redundant K/V tensors original checkpoints ship.
if stacked_name not in params_dict:
continue
if is_pp_missing_parameter(stacked_name, self):
continue
param = params_dict[stacked_name]
weight_loader = param.weight_loader
weight_loader(param, loaded_weight, shard_id)
loaded_params.add(stacked_name)
break
else:
for (
param_name,
weight_name,
expert_id,
shard_id,
) in expert_params_mapping:
# Match both:
# - Bare weights: "experts.0.down_proj" (from 3D explosion)
# - With suffix: "experts.0.down_proj.weight_scale" (2D quantized)
# weight_name has trailing dot, so check with and without it
weight_name_base = weight_name.rstrip(".")
if weight_name in name:
# Has suffix (e.g., .weight_scale)
moe_name = name.replace(weight_name, param_name)
elif name.endswith(weight_name_base):
# Bare weight (no suffix)
moe_name = name.replace(
weight_name_base, param_name.rstrip("_") + "_weight"
)
else:
continue
if moe_name not in params_dict:
continue
if is_pp_missing_parameter(moe_name, self):
continue
param = params_dict[moe_name]
# Expert weights are already in the correct
# orientation for MoERunner after _weight_iterator:
# gate/up: [I, H] → w1/w3 expects [I, H]
# down: [H, I] → w2 expects [H, I]
# Scales and other quantization params may be 1D or scalar.
weight_loader = param.weight_loader
weight_loader(
param,
loaded_weight,
moe_name, # Pass mapped name (handles both weights and scales)
shard_id=shard_id,
expert_id=expert_id,
)
loaded_params.add(moe_name)
break
else:
if name.endswith(".bias") and name not in params_dict:
continue
remapped_name = maybe_remap_kv_scale_name(name, params_dict)
if remapped_name is None:
continue
name = remapped_name
if is_pp_missing_parameter(name, self):
continue
# Skip if name doesn't exist in params_dict (e.g., individual
# expert weights that should have been handled above)
if name not in params_dict:
continue
param = params_dict[name]
weight_loader = getattr(
param, "weight_loader", default_weight_loader
)
weight_loader(param, loaded_weight)
loaded_params.add(name)
return loaded_params
loader = AutoWeightsLoader(self)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
class Gemma4ForCausalLM(
nn.Module, SupportsLoRA, SupportsPP, MixtureOfExperts, SupportsEagle3
):
hf_to_vllm_mapper = _GEMMA4_EXPERT_PARENT_MAPPER | WeightsMapper(
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_substr={
# Multimodal weights are handled by the multimodal wrapper.
"audio_tower.": None,
"vision_tower.": None,
"embed_audio.": None,
"embed_vision.": None,
},
orig_to_new_prefix={
# Gemma4ForConditionalGeneration already loads the text stack
# from `model.language_model.*`. We reuse that same checkpoint
@@ -1544,13 +1411,6 @@ class Gemma4ForCausalLM(
# so LoRA keys from the conditional wrapper map onto `model.*`.
"model.language_model.": "model.",
},
orig_to_new_substr={
# Gemma4ForConditionalGeneration names MoE adapter targets under
# `...moe.experts.*`, while the text-only model exposes them
# under `...moe.*`.
".moe.experts.gate_up_proj": ".moe.gate_up_proj",
".moe.experts.down_proj": ".moe.down_proj",
},
)
# KV-shared layers only have q_proj, so qkv_proj packing applies to
# the other layers.
@@ -1596,26 +1456,18 @@ class Gemma4ForCausalLM(
)
# --- MixtureOfExperts protocol ---
self.moe_layers: list[nn.Module] = []
example_moe: Gemma4MoE | None = None
for layer in self.model.layers:
if hasattr(layer, "moe") and isinstance(layer.moe, Gemma4MoE):
example_moe = layer.moe
self.moe_layers.append(layer.moe.experts)
self.moe_layers: list[nn.Module] = [
layer.experts
for layer in self.model.layers
if not isinstance(layer, PPMissingLayer) and layer.experts is not None
]
self.num_moe_layers = len(self.moe_layers)
if example_moe is not None:
self.num_logical_experts = example_moe.num_experts
self.num_physical_experts = example_moe.num_experts
self.num_local_physical_experts = example_moe.num_experts
self.num_routed_experts = example_moe.num_experts
else:
self.num_logical_experts = 0
self.num_physical_experts = 0
self.num_local_physical_experts = 0
self.num_routed_experts = 0
num_experts = config.num_experts if self.num_moe_layers else 0
self.num_logical_experts = num_experts
self.num_physical_experts = num_experts
self.num_local_physical_experts = num_experts
self.num_routed_experts = num_experts
self.num_expert_groups = 1
self.num_shared_experts = 0
@@ -1644,106 +1496,5 @@ class Gemma4ForCausalLM(
return self.logits_processor(self.lm_head, hidden_states)
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# Checkpoint weight names use "language_model." prefix (from the
# Gemma4ForConditionalGeneration wrapper). Strip it to map to our
# model tree which is just "model.*".
def _weight_iterator():
use_k_eq_v = getattr(self.config, "attention_k_eq_v", False)
# Build set of k_eq_v layer indices (full_attention layers
# when attention_k_eq_v is enabled). These layers have k_proj
# but no v_proj in checkpoint — we duplicate k_proj as v_proj.
k_eq_v_layer_indices: set[int] = set()
if use_k_eq_v:
for idx, lt in enumerate(self.config.layer_types):
if lt == "full_attention":
k_eq_v_layer_indices.add(idx)
for name, weight in weights:
# Remap "language_model." → "" to match our model tree.
# Checkpoint: model.language_model.layers.X.*
# Our model: model.layers.X.*
name = name.replace("language_model.", "")
# Remap new HF checkpoint naming to internal vLLM
# naming: HF moved per_expert_scale to router and
# renamed moe → experts in the MoE block.
name = name.replace(
".router.per_expert_scale",
".moe.per_expert_scale",
)
if ".experts.gate_up_proj" in name:
name = name.replace(
".experts.gate_up_proj",
".moe.gate_up_proj",
)
elif ".experts.down_proj" in name:
name = name.replace(
".experts.down_proj",
".moe.down_proj",
)
# Remap individual 2D expert weights:
# .experts.{id}.{proj} → .moe.experts.{id}.{proj}
# (This handles per-expert 2D quantized weights)
name = _remap_gemma4_expert_weight_name(name)
# MoE expert weights: checkpoint stores as 3D packed
# tensors. Explode into per-expert 2D weights for
# MoERunner weight_loader.
#
# Checkpoint format:
# moe.gate_up_proj: [E, 2*I, H] (fused gate + up)
# moe.down_proj: [E, H, I]
#
# MoERunner expects per-expert:
# w1 (gate): [I, H] — first half of gate_up
# w3 (up): [I, H] — second half of gate_up
# w2 (down): [H, I] — as-is from checkpoint
#
# No transpose needed: checkpoint orientation already
# matches MoERunner's expected layout.
if "moe.gate_up_proj" in name and weight.dim() == 3:
num_experts = weight.size(0)
intermediate_size = weight.size(1) // 2
for expert_id in range(num_experts):
gate_weight = weight[expert_id, :intermediate_size, :]
up_weight = weight[expert_id, intermediate_size:, :]
base = name.replace("moe.", f"moe.experts.{expert_id}.")
yield base.replace("gate_up_proj", "gate_proj"), gate_weight
yield base.replace("gate_up_proj", "up_proj"), up_weight
continue
if "moe.down_proj" in name and weight.dim() == 3:
num_experts = weight.size(0)
for expert_id in range(num_experts):
expert_name = name.replace("moe.", f"moe.experts.{expert_id}.")
yield expert_name, weight[expert_id]
continue
# k_eq_v layers: checkpoint has k_proj but no v_proj.
# QKVParallelLinear expects both, so duplicate k_proj
# as v_proj so V gets identical weights to K.
# ONLY for full_attention layers — sliding layers have
# their own real v_proj weights.
if "self_attn.k_proj" in name and k_eq_v_layer_indices:
m = re.search(r"layers\.(\d+)\.", name)
if m and int(m.group(1)) in k_eq_v_layer_indices:
yield name, weight
yield name.replace("k_proj", "v_proj"), weight.clone()
continue
yield name, weight
# Drop multimodal weights, which are handled by the multimodal wrapper.
# `_weight_iterator` already applies this model's renames by hand, so
# `hf_to_vllm_mapper` is deliberately not passed here.
mapper = WeightsMapper(
orig_to_new_substr={
"audio_tower.": None,
"vision_tower.": None,
"embed_audio.": None,
"embed_vision.": None,
}
)
loader = AutoWeightsLoader(self)
return loader.load_weights(_weight_iterator(), mapper=mapper)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
+9 -26
View File
@@ -36,20 +36,13 @@ from transformers.models.gemma4.configuration_gemma4 import (
from vllm.config import VllmConfig
from vllm.config.model import get_served_model_name
from vllm.config.multimodal import (
AudioDummyOptions,
BaseDummyOptions,
VideoDummyOptions,
)
from vllm.config.multimodal import MultiModalDummyOptions, VideoDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.logger import init_logger
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.models.gemma3n_mm import batch_audio_features
from vllm.model_executor.models.gemma4 import (
_GEMMA4_EXPERT_PARENT_MAPPER,
Gemma4ForCausalLM,
)
from vllm.model_executor.models.gemma4 import Gemma4ForCausalLM
from vllm.model_executor.models.module_mapping import MultiModelKeys
from vllm.model_executor.models.transformers.utils import recursive_replace_linear
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -276,10 +269,7 @@ class Gemma4ProcessingInfo(BaseProcessingInfo):
num_frames = _VIDEO_MAX_FRAMES
mm_config = self.ctx.model_config.get_multimodal_config()
video_opts = mm_config.limit_per_prompt.get("video")
if (
isinstance(video_opts, VideoDummyOptions)
and video_opts.num_frames is not None
):
if video_opts is not None and video_opts.num_frames is not None:
num_frames = min(num_frames, video_opts.num_frames)
tokens["video"] = num_frames * (_VIDEO_MAX_SOFT_TOKENS + 2 + 6)
return tokens
@@ -505,9 +495,8 @@ class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions] | None = None,
mm_options: MultiModalDummyOptions | None = None,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_audios = mm_counts.get("audio", 0)
num_videos = mm_counts.get("video", 0)
processor = self.info.get_hf_processor()
@@ -520,18 +509,12 @@ class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
img_width = size.get("width", 224)
img_height = size.get("height", 224)
image_overrides = mm_options.get("image") if mm_options else None
audio_overrides = mm_options.get("audio") if mm_options else None
video_overrides = mm_options.get("video") if mm_options else None
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
assert video_overrides is None or isinstance(video_overrides, VideoDummyOptions)
data: dict[str, Any] = {
"image": self._get_dummy_images(
width=img_width,
height=img_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image") if mm_options else None,
),
}
@@ -540,7 +523,7 @@ class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
data["audio"] = self._get_dummy_audios(
length=audio_len,
num_audios=num_audios,
overrides=audio_overrides,
overrides=mm_options.get("audio") if mm_options else None,
)
if num_videos > 0:
@@ -549,7 +532,7 @@ class Gemma4DummyInputsBuilder(BaseDummyInputsBuilder[Gemma4ProcessingInfo]):
height=img_height,
num_frames=_VIDEO_MAX_FRAMES,
num_videos=num_videos,
overrides=video_overrides,
overrides=mm_options.get("video") if mm_options else None,
)
return data
@@ -1060,7 +1043,7 @@ class Gemma4ForConditionalGeneration(
}
# Maps checkpoint prefixes to vLLM module paths.
hf_to_vllm_mapper = _GEMMA4_EXPERT_PARENT_MAPPER | WeightsMapper(
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_prefix={
# vision tower
"model.vision_tower": "vision_tower",
+1 -5
View File
@@ -28,7 +28,6 @@ from transformers.models.gemma4_unified.processing_gemma4_unified import (
)
from vllm.config import VllmConfig
from vllm.config.multimodal import VideoDummyOptions
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.model_executor.models.gemma3n_mm import batch_audio_features
from vllm.model_executor.models.gemma4 import Gemma4ForCausalLM
@@ -177,10 +176,7 @@ class Gemma4UnifiedProcessingInfo(Gemma4ProcessingInfo):
num_frames = _VIDEO_MAX_FRAMES
mm_config = self.ctx.model_config.get_multimodal_config()
video_opts = mm_config.limit_per_prompt.get("video")
if (
isinstance(video_opts, VideoDummyOptions)
and video_opts.num_frames is not None
):
if video_opts is not None and video_opts.num_frames is not None:
num_frames = min(num_frames, video_opts.num_frames)
tokens["video"] = num_frames * (_VIDEO_MAX_SOFT_TOKENS + 2 + 6)
return tokens
+16 -45
View File
@@ -36,9 +36,7 @@ import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import transformers
from einops import rearrange
from packaging.version import Version
from transformers import BatchFeature, Glm4vProcessor
from transformers.image_processing_base import ImageProcessingMixin
from transformers.models.glm4v.configuration_glm4v import (
@@ -54,7 +52,7 @@ from transformers.video_processing_utils import BaseVideoProcessor
from transformers.video_utils import VideoMetadata
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions, VideoDummyOptions
from vllm.distributed import get_tensor_model_parallel_world_size, parallel_state
from vllm.distributed import utils as dist_utils
from vllm.inputs import MultiModalDataDict
@@ -132,8 +130,6 @@ logger = init_logger(__name__)
# For profile run
_MAX_FRAMES_PER_VIDEO = 600
TRANSFORMERS_WITH_GA = Version(transformers.__version__) >= Version("5.10.0.dev0")
def _to_video_metadata(metadata: Mapping[str, Any]) -> VideoMetadata:
return VideoMetadata(
@@ -1389,17 +1385,6 @@ class Glm4vProcessingInfo(BaseProcessingInfo):
timestamps_list = full_second_idxs[::2]
return list(timestamps_list)
def _get_video_frame_embed_token_id(self, hf_processor: object) -> int:
attr = (
"image_token_id"
if isinstance(hf_processor, Glm4vProcessor) or TRANSFORMERS_WITH_GA
else "video_token_id"
)
token_id = getattr(hf_processor, attr, None)
if not isinstance(token_id, int):
raise ValueError(f"Processor has no valid {attr}")
return token_id
def _construct_video_placeholder(
self,
video_array: np.ndarray,
@@ -1437,7 +1422,7 @@ class Glm4vProcessingInfo(BaseProcessingInfo):
num_tokens_per_frame = int(H * W) // merge_length
placeholder = []
placeholder.append(bov_token_id)
frame_embed_token_id = self._get_video_frame_embed_token_id(hf_processor)
frame_embed_token_id = hf_processor.image_token_id
for frame_idx in frames_idx_token:
placeholder.append(boi_token_id)
placeholder.extend([frame_embed_token_id] * num_tokens_per_frame)
@@ -1470,33 +1455,26 @@ class Glm4vDummyInputsBuilder(BaseDummyInputsBuilder[Glm4vProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_videos = mm_counts.get("video", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = self.info.get_num_frames_with_most_features(
seq_len, mm_counts
)
image_overrides = mm_options.get("image")
video_overrides = mm_options.get("video")
assert video_overrides is None or isinstance(video_overrides, VideoDummyOptions)
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
"video": self._get_dummy_videos(
width=target_width,
height=target_height,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides,
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video"),
),
}
@@ -1601,10 +1579,7 @@ class Glm4vMultiModalProcessor(BaseMultiModalProcessor[Glm4vProcessingInfo]):
processor = self.info.get_hf_processor(**hf_kwargs)
use_direct_path = (
not isinstance(processor, Glm4vProcessor) and TRANSFORMERS_WITH_GA
)
if use_direct_path:
if not isinstance(processor, Glm4vProcessor):
prepared_data, prepared_kwargs = self._get_direct_path_inputs(
hf_data, hf_kwargs
)
@@ -1627,8 +1602,6 @@ class Glm4vMultiModalProcessor(BaseMultiModalProcessor[Glm4vProcessingInfo]):
del hf_data["videos"]
video_grid_thw_lst = []
pixel_values_videos_lst = []
frame_embed_token_id = self.info._get_video_frame_embed_token_id(processor)
swap_video_frame_tokens = frame_embed_token_id == processor.image_token_id
for item in videos:
video_array, metadata = item
@@ -1651,10 +1624,10 @@ class Glm4vMultiModalProcessor(BaseMultiModalProcessor[Glm4vProcessingInfo]):
video_mm_kwargs,
)
input_ids = video_outputs.pop("input_ids")
if swap_video_frame_tokens:
input_ids[input_ids == processor.image_token_id] = (
processor.video_token_id
)
input_ids[input_ids == processor.image_token_id] = (
processor.video_token_id
)
video_placeholder = processor.tokenizer.batch_decode(input_ids)[0]
prompt_text = prompt_text.replace(
"<|begin_of_video|><|video|><|end_of_video|>",
@@ -1670,17 +1643,15 @@ class Glm4vMultiModalProcessor(BaseMultiModalProcessor[Glm4vProcessingInfo]):
)
else:
video_outputs = dict()
swap_video_frame_tokens = False
processed_data = self.info.ctx.call_hf_processor(
self.info.get_hf_processor(**hf_kwargs),
dict(text=prompt_text, **hf_data),
hf_kwargs,
)
if swap_video_frame_tokens:
input_ids = processed_data["input_ids"]
input_ids[input_ids == processor.video_token_id] = processor.image_token_id
processed_data["input_ids"] = input_ids
input_ids = processed_data["input_ids"]
input_ids[input_ids == processor.video_token_id] = processor.image_token_id
processed_data["input_ids"] = input_ids
processed_data.update(video_outputs)
return self._finalize_hf_mm_data(
@@ -1728,7 +1699,7 @@ class Glm4vMultiModalProcessor(BaseMultiModalProcessor[Glm4vProcessingInfo]):
)
return PromptUpdateDetails.select_token_id(
placeholder,
embed_token_id=self.info._get_video_frame_embed_token_id(hf_processor),
embed_token_id=hf_processor.image_token_id,
)
return [
+4 -7
View File
@@ -16,7 +16,7 @@ from torch.nn import LayerNorm
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import SiluAndMul, get_act_fn
@@ -445,22 +445,19 @@ class GLM4VDummyInputsBuilder(BaseDummyInputsBuilder[GLM4VProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
hf_config = self.info.get_hf_config()
vision_config = hf_config.vision_config
target_width = target_height = vision_config["image_size"]
num_images = mm_counts.get("image", 0)
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+4 -7
View File
@@ -11,7 +11,7 @@ from transformers.models.glmasr import GlmAsrConfig, GlmAsrProcessor
from transformers.models.whisper import WhisperFeatureExtractor
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.distributed.parallel_state import get_tensor_model_parallel_world_size
from vllm.inputs import ModalityData, MultiModalDataDict, PromptType, TokensPrompt
@@ -694,13 +694,10 @@ class GlmAsrDummyInputsBuilder(BaseDummyInputsBuilder[GlmAsrProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
feature_extractor = self.info.get_feature_extractor()
sampling_rate = feature_extractor.sampling_rate
num_audios = mm_counts.get("audio", 0)
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
max_audio_len = getattr(
self.info.get_hf_processor(), "max_audio_len", DEFAULT_MAX_AUDIO_LEN_S
@@ -710,8 +707,8 @@ class GlmAsrDummyInputsBuilder(BaseDummyInputsBuilder[GlmAsrProcessingInfo]):
return {
"audio": self._get_dummy_audios(
length=audio_len,
num_audios=num_audios,
overrides=audio_overrides,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
)
}
+4 -8
View File
@@ -34,7 +34,7 @@ from torch import nn
from transformers import BatchFeature, PretrainedConfig
from vllm.config import CacheConfig, ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.inputs import MultiModalDataDict, PromptType, TokensPrompt
from vllm.model_executor.layers.linear import ColumnParallelLinear, RowParallelLinear
@@ -208,17 +208,13 @@ class GraniteSpeechDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_audios = mm_counts.get("audio", 0)
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
return {
"audio": self._get_dummy_audios(
length=self.info.get_max_audio_len(),
num_audios=num_audios,
overrides=audio_overrides,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
)
}
@@ -18,7 +18,7 @@ import torch.nn as nn
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.forward_context import set_forward_context
from vllm.inputs import MultiModalDataDict
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -193,7 +193,7 @@ class HCXVisionV2DummyInputsBuilder(BaseDummyInputsBuilder[HCXVisionV2Processing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions] | None = None,
mm_options: MultiModalDummyOptions | None = None,
mm_processor_kwargs: Mapping[str, object] | None = None,
) -> ProcessorInputs:
"""Build dummy processor inputs for memory profiling."""
@@ -225,31 +225,25 @@ class HCXVisionV2DummyInputsBuilder(BaseDummyInputsBuilder[HCXVisionV2Processing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions] | None = None,
mm_options: MultiModalDummyOptions | None = None,
mm_processor_kwargs: Mapping[str, object] | None = None,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_videos = mm_counts.get("video", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = 16 # Default for video
image_overrides = mm_options.get("image") if mm_options else None
video_overrides = mm_options.get("video") if mm_options else None
result: MultiModalDataDict = {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides, # type: ignore
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image") if mm_options else None,
),
"video": self._get_dummy_videos(
width=target_width,
height=target_height,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides, # type: ignore
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video") if mm_options else None,
),
}
+4 -7
View File
@@ -29,7 +29,7 @@ from transformers import (
)
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.logits_processor import LogitsProcessor
@@ -221,21 +221,18 @@ class Idefics3DummyInputsBuilder(BaseDummyInputsBuilder[Idefics3ProcessingInfo])
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
hf_processor = self.info.get_hf_processor()
image_processor: Idefics3ImageProcessor = hf_processor.image_processor
longest_edge = image_processor.max_image_size["longest_edge"]
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=longest_edge,
height=longest_edge,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+7
View File
@@ -91,6 +91,13 @@ MambaStateShapes: TypeAlias = (
tuple[int, int, int],
tuple[int, int, int],
]
| tuple[
tuple[int, int],
tuple[int, int, int],
tuple[int, int, int],
tuple[int, int],
tuple[int, int, int],
]
)
+6 -12
View File
@@ -22,7 +22,7 @@ from transformers.models.internvl.video_processing_internvl import (
)
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.models.interns1_vit import InternS1VisionModel
@@ -299,35 +299,29 @@ class InternS1DummyInputsBuilder(BaseDummyInputsBuilder[InternS1ProcessingInfo])
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = self.info.get_num_frames_with_most_features(
seq_len, mm_counts
)
num_images = mm_counts.get("image", 0)
num_videos = mm_counts.get("video", 0)
config = self.info.get_hf_config()
image_size_h, image_size_w = config.vision_config.image_size
image_overrides = mm_options.get("image")
video_overrides = mm_options.get("video")
assert video_overrides is None or isinstance(video_overrides, VideoDummyOptions)
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
"video": self._get_dummy_videos(
width=image_size_w,
height=image_size_h,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides,
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video"),
),
}
+5 -11
View File
@@ -17,7 +17,7 @@ import torch.nn as nn
from transformers import BatchFeature, PretrainedConfig
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.quantization.auto_awq import AutoAWQConfig
@@ -203,19 +203,16 @@ class BaseInternVLDummyInputsBuilder(BaseDummyInputsBuilder[_I]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
target_width, target_height = self.info.get_image_size_with_most_features()
num_images = mm_counts.get("image", 0)
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
@@ -425,7 +422,7 @@ class InternVLDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
dummy_image = super().get_dummy_mm_data(seq_len, mm_counts, mm_options)
if self.info.ctx_video_token:
@@ -436,9 +433,6 @@ class InternVLDummyInputsBuilder(
)
num_videos = mm_counts.get("video", 0)
video_overrides = mm_options.get("video")
assert video_overrides is None or isinstance(
video_overrides, VideoDummyOptions
)
dummy_video = {
"video": self._get_dummy_videos(
width=image_size,
+4 -7
View File
@@ -13,7 +13,7 @@ from einops import rearrange
from transformers.image_processing_utils import BatchFeature
from vllm.config import ModelConfig, VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import parallel_state
from vllm.distributed import utils as dist_utils
from vllm.inputs import MultiModalDataDict
@@ -386,19 +386,16 @@ class IsaacDummyInputsBuilder(BaseDummyInputsBuilder[IsaacProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
}
+2 -2
View File
@@ -18,7 +18,7 @@ from transformers.modeling_outputs import BaseModelOutput
from transformers.models.qwen2_vl.configuration_qwen2_vl import Qwen2VLVisionConfig
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.logger import init_logger
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -442,7 +442,7 @@ class KananaVDummyInputsBuilder(BaseDummyInputsBuilder[KananaVProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
return {
+6 -12
View File
@@ -17,7 +17,7 @@ from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPo
from transformers.utils import torch_int
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.inputs import ModalityData, MultiModalDataDict
from vllm.logger import init_logger
@@ -1124,30 +1124,24 @@ class KeyeBaseDummyInputsBuilder(BaseDummyInputsBuilder[_I]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_videos = mm_counts.get("video", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = self.info.get_num_frames_with_most_features(seq_len)
image_overrides = mm_options.get("image")
video_overrides = mm_options.get("video")
mm_data = {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
"video": self._get_dummy_videos(
width=target_width,
height=target_height,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides,
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video"),
),
}
+2 -2
View File
@@ -13,7 +13,7 @@ from transformers import BatchFeature
from transformers import WhisperConfig as HFWhisperConfig
from vllm.config import ModelConfig, SpeechToTextConfig, VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.config.speech_to_text import SpeechToTextParams
from vllm.inputs import PromptType, TokensPrompt
from vllm.model_executor.model_loader import DefaultModelLoader
@@ -180,7 +180,7 @@ class KimiAudioDummyInputsBuilder(BaseDummyInputsBuilder[KimiAudioProcessingInfo
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> ProcessorInputs:
dummy_mm_data = self.get_dummy_mm_data(seq_len, mm_counts, mm_options)
dummy_mm_items = self.info.parse_mm_data(dummy_mm_data)
+2 -2
View File
@@ -14,7 +14,7 @@ from torch import nn
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization import QuantizationConfig
@@ -216,7 +216,7 @@ class KimiK25DummyInputsBuilder(BaseDummyInputsBuilder[KimiK25ProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
# TODO: Support mm_options for vision_chunk to allow user configuration
dummy_items = self.get_dummy_mm_items()
+4 -8
View File
@@ -53,7 +53,7 @@ from transformers import BatchFeature
from transformers.activations import GELUActivation
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.models.interfaces import (
@@ -219,18 +219,14 @@ class KimiVLDummyInputsBuilder(BaseDummyInputsBuilder[KimiVLProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=MaxImageTokenMeta.width,
height=MaxImageTokenMeta.height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
+4 -8
View File
@@ -21,7 +21,7 @@ from transformers.models.lfm2_vl.image_processing_lfm2_vl_fast import (
from typing_extensions import Buffer
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.forward_context import set_forward_context
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.linear import ReplicatedLinear
@@ -387,20 +387,16 @@ class Lfm2VLDummyInputsBuilder(BaseDummyInputsBuilder[Lfm2VLProcessingInfo]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
}
+4 -13
View File
@@ -19,13 +19,12 @@ from transformers.models.llava import LlavaProcessor
from transformers.models.pixtral import PixtralProcessor
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.layers.linear import ColumnParallelLinear, RowParallelLinear
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.cache import BaseMultiModalProcessorCache
from vllm.multimodal.inputs import (
MultiModalFieldConfig,
MultiModalKwargsItem,
@@ -228,20 +227,16 @@ class LlavaDummyInputsBuilder(BaseDummyInputsBuilder[_I]):
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
image_overrides = mm_options.get("image")
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
)
}
@@ -411,21 +406,17 @@ def _build_llava_or_pixtral_hf_info(
def _build_llava_or_pixtral_hf_processor(
info: _I,
dummy_inputs: BaseDummyInputsBuilder[_I],
*,
cache: BaseMultiModalProcessorCache | None = None,
) -> BaseMultiModalProcessor:
if isinstance(info, PixtralHFProcessingInfo):
return PixtralHFMultiModalProcessor(
info,
dummy_inputs, # type: ignore
cache=cache,
)
if isinstance(info, LlavaProcessingInfo):
return LlavaMultiModalProcessor(
info,
dummy_inputs, # type: ignore
cache=cache,
)
raise NotImplementedError(type(info))
@@ -10,7 +10,7 @@ import torch.nn as nn
from transformers import BatchFeature, LlavaNextVideoConfig, LlavaNextVideoProcessor
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
from vllm.model_executor.models.clip import CLIPVisionModel
@@ -171,25 +171,20 @@ class LlavaNextVideoDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_videos = mm_counts.get("video", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = self.info.get_num_frames_with_most_features(
seq_len, mm_counts
)
video_overrides = mm_options.get("video")
assert video_overrides is None or isinstance(video_overrides, VideoDummyOptions)
return {
"video": self._get_dummy_videos(
width=target_width,
height=target_height,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides,
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video"),
)
}
+6 -13
View File
@@ -14,7 +14,7 @@ from transformers.models.llava_onevision.modeling_llava_onevision import (
)
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions, VideoDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
from vllm.multimodal import MULTIMODAL_REGISTRY
@@ -278,33 +278,26 @@ class LlavaOnevisionDummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_images = mm_counts.get("image", 0)
num_videos = mm_counts.get("video", 0)
target_width, target_height = self.info.get_image_size_with_most_features()
target_num_frames = self.info.get_num_frames_with_most_features(
seq_len, mm_counts
)
image_overrides = mm_options.get("image")
video_overrides = mm_options.get("video")
assert video_overrides is None or isinstance(video_overrides, VideoDummyOptions)
return {
"image": self._get_dummy_images(
width=target_width,
height=target_height,
num_images=num_images,
overrides=image_overrides,
num_images=mm_counts.get("image", 0),
overrides=mm_options.get("image"),
),
"video": self._get_dummy_videos(
width=target_width,
height=target_height,
num_frames=target_num_frames,
num_videos=num_videos,
overrides=video_overrides,
num_videos=mm_counts.get("video", 0),
overrides=mm_options.get("video"),
),
}
@@ -54,7 +54,7 @@ from vllm.compilation.decorators import (
support_torch_compile,
)
from vllm.config import VllmConfig
from vllm.config.multimodal import BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import parallel_state
from vllm.distributed import utils as dist_utils
from vllm.inputs import ModalityData, MultiModalDataDict
@@ -1471,7 +1471,7 @@ class LlavaOnevision2DummyInputsBuilder(
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions] | None = None,
mm_options: MultiModalDummyOptions | None = None,
) -> MultiModalDataDict:
n_img = mm_counts.get("image", 0)
n_vid = mm_counts.get("video", 0)
+4 -9
View File
@@ -36,7 +36,7 @@ from torch.nn.functional import scaled_dot_product_attention
from transformers import BatchFeature
from vllm.config import VllmConfig
from vllm.config.multimodal import AudioDummyOptions, BaseDummyOptions
from vllm.config.multimodal import MultiModalDummyOptions
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.inputs import MultiModalDataDict
from vllm.model_executor.layers.activation import get_act_fn
@@ -564,18 +564,13 @@ class MiDashengLMDummyInputsBuilder(BaseDummyInputsBuilder[MiDashengLMProcessing
self,
seq_len: int,
mm_counts: Mapping[str, int],
mm_options: Mapping[str, BaseDummyOptions],
mm_options: MultiModalDummyOptions,
) -> MultiModalDataDict:
num_audios = mm_counts.get("audio", 0)
audio_overrides = mm_options.get("audio")
assert audio_overrides is None or isinstance(audio_overrides, AudioDummyOptions)
return {
"audio": self._get_dummy_audios(
length=self.info.get_max_audio_len(),
num_audios=num_audios,
overrides=audio_overrides,
num_audios=mm_counts.get("audio", 0),
overrides=mm_options.get("audio"),
)
}
+140 -54
View File
@@ -50,6 +50,7 @@ from vllm.model_executor.model_loader.weight_utils import (
)
from vllm.model_executor.models.utils import sequence_parallel_chunk
from vllm.sequence import IntermediateTensors
from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backend import AttentionType
from vllm.v1.attention.backends.registry import AttentionBackendEnum
@@ -460,6 +461,28 @@ class MiMoV2FlashDecoderLayer(nn.Module):
return self.config.hybrid_layer_pattern[self.layer_id] == 1
def _requantize_fp8(
grouped: torch.Tensor, rows_rank: int, block: int, dtype: torch.dtype
) -> tuple[torch.Tensor, torch.Tensor]:
"""Block-quantize a rank's ``[Q | K | V]`` rows back to fp8.
A rank's rows need not end on a block boundary (a single 1856-row slice is
14.5 blocks) while ``scaled_quantize`` requires both dims to be multiples of
the block size, so pad the tail with zeros: zero rows cannot raise a block's
amax, so every scale -- and the number of scale rows -- is unchanged. The
padding is dropped again here.
"""
padded = cdiv(rows_rank, block) * block
if padded != rows_rank:
grouped = torch.cat(
[grouped, grouped.new_zeros(padded - rows_rank, grouped.shape[1])], dim=0
)
w_rank, s_rank = scaled_quantize(
grouped, GroupShape(block, block), dtype, compute_dtype=torch.float32
)
return w_rank[:rows_rank], s_rank
def _shard_fp8_qkv_proj(
w_full: torch.Tensor,
s_full: torch.Tensor,
@@ -469,75 +492,136 @@ def _shard_fp8_qkv_proj(
v_head_dim: int,
tp_rank: int,
tp_size: int,
ckpt_tp: int,
block: int = 128,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Shard the fp8 qkv_proj weights for ``tp_rank``.
The checkpoint stores the fused QKV as ``num_kv_heads`` contiguous groups
(one per KV head; ``n`` below), each ordered ``[Q | K | V]``:
The checkpoint stores the fused QKV pre-sharded for ``ckpt_tp`` ranks (the
model config's ``num_key_value_heads``), each chunk holding that slice's
Q, K and V rows:
[Q_1 | K_1 | V_1 | Q_2 | K_2 | V_2 | ... | Q_n | K_n | V_n]
[Q_0 | K_0 | V_0 | Q_1 | K_1 | V_1 | ... | Q_n | K_n | V_n] (n = ckpt_tp)
Per group, Q has ``(num_heads / num_kv_heads) * head_dim`` rows, K has
``head_dim`` rows, and V has ``v_head_dim`` rows.
Per chunk, Q has ``(num_heads / ckpt_tp) * head_dim`` rows, K has
``(num_kv_heads / ckpt_tp) * head_dim`` rows, and V has
``(num_kv_heads / ckpt_tp) * v_head_dim`` rows, and the fp8 block scales
are tiled per chunk too (``ceil(rows_per_chunk / block)`` rows each).
Each TP rank owns ``g = num_kv_heads / tp_size`` of these groups, and the
forward expects them de-interleaved into a single Q, K, and V block:
``ckpt_tp`` is not the layer's KV-head count: a MiMo-V2.5 SWA layer has 8
KV heads over 4 chunks, so each chunk carries two KV heads (3712 rows = 29
blocks) while a GA layer has 4 KV heads over 4 chunks (3392 rows each).
The forward expects each rank's slice de-interleaved:
[Q_1 | Q_2 | ... | Q_g | K_1 | K_2 | ... | K_g | V_1 | V_2 | ... | V_g]
When ``g == 1`` the rank's slice is already ``[Q | K | V]``, so a plain
chunk suffices. When ``g > 1`` we cannot reach the de-interleaved layout by
re-permuting the fp8 block scales: each scale covers a 128-row block, and
since K is 192 rows (1.5 blocks) a block straddles the K/V boundary, so no
whole-block permutation produces it. Instead we dequantize this rank's
groups to float (dropping the block constraint), reorder the rows into the
layout above (Q, K, and V then each span a whole number of blocks), and
re-quantize to fp8.
When ``tp_size == ckpt_tp`` the checkpoint chunk *is* that layout, so a
plain chunk of both weight and scale suffices. Otherwise each rank's Q, K
and V rows are gathered from the chunks that hold them, dequantized with
the chunk's own scales, reordered, and re-quantized to fp8.
"""
assert tp_size <= num_kv_heads and num_kv_heads % tp_size == 0, (
"TP size must evenly split the number of KV heads."
assert num_heads % tp_size == 0, (
f"num_heads={num_heads} must be divisible by tp_size={tp_size}."
)
kv_heads_per_rank = num_kv_heads // tp_size
if kv_heads_per_rank == 1:
# One KV head per rank. The weights and scale can be trivially sharded
# without re-quantization.
w = w_full.chunk(tp_size, dim=0)[tp_rank]
s = s_full.chunk(tp_size, dim=0)[tp_rank]
return w, s
q_rows_per_group = (num_heads // num_kv_heads) * head_dim
k_rows_per_group = head_dim
v_rows_per_group = v_head_dim
rows_per_group = q_rows_per_group + k_rows_per_group + v_rows_per_group
scale_rows_per_group = s_full.shape[0] // num_kv_heads
qs, ks, vs = [], [], []
for g_idx in range(tp_rank * kv_heads_per_rank, (tp_rank + 1) * kv_heads_per_rank):
row_start = g_idx * rows_per_group
scale_row_start = g_idx * scale_rows_per_group
# Dequantize this group's weights.
w_g = w_full[row_start : row_start + rows_per_group].to(torch.float32)
s_g = s_full[scale_row_start : scale_row_start + scale_rows_per_group].to(
torch.float32
if ckpt_tp <= 0 or num_heads % ckpt_tp or num_kv_heads % ckpt_tp:
raise ValueError(
f"fused qkv_proj is pre-sharded at {ckpt_tp} chunks, which do not "
f"divide num_heads={num_heads} / num_kv_heads={num_kv_heads}."
)
s_g_expanded = s_g.repeat_interleave(block, dim=0).repeat_interleave(
block, dim=1
)[:rows_per_group]
w_g_dequant = w_g * s_g_expanded
# Track the dequantized q, k, and v weights separately.
qs.append(w_g_dequant[:q_rows_per_group])
ks.append(w_g_dequant[q_rows_per_group : q_rows_per_group + k_rows_per_group])
vs.append(w_g_dequant[q_rows_per_group + k_rows_per_group :])
# Combine the q, k, and v weights into the following layout:
# [Q_1, Q_2, .., Q_g, K_1, K_2, ..., K_g, V_1, V_2, ..., V_g]
grouped = torch.cat([torch.cat(qs), torch.cat(ks), torch.cat(vs)], dim=0)
# Quantize back to fp8.
return scaled_quantize(
grouped, GroupShape(block, block), w_full.dtype, compute_dtype=torch.float32
# When there are fewer KV heads than ranks, vLLM replicates them
# (`num_kv_head_replicas`) and rank r owns KV head r // replicas, which
# keeps every Q head grouped with the KV head it attends to.
if tp_size <= num_kv_heads:
assert num_kv_heads % tp_size == 0, (
f"num_kv_heads={num_kv_heads} must be divisible by tp_size={tp_size}."
)
kv_head_ids = list(
range(
tp_rank * (num_kv_heads // tp_size),
(tp_rank + 1) * (num_kv_heads // tp_size),
)
)
else:
assert tp_size % num_kv_heads == 0, (
f"tp_size={tp_size} must be divisible by num_kv_heads={num_kv_heads}."
)
kv_head_ids = [tp_rank // (tp_size // num_kv_heads)]
q_head_ids = list(
range(tp_rank * (num_heads // tp_size), (tp_rank + 1) * (num_heads // tp_size))
)
rows_per_chunk = w_full.shape[0] // ckpt_tp
q_per_chunk = (num_heads // ckpt_tp) * head_dim
k_per_chunk = (num_kv_heads // ckpt_tp) * head_dim
v_per_chunk = (num_kv_heads // ckpt_tp) * v_head_dim
if q_per_chunk + k_per_chunk + v_per_chunk != rows_per_chunk:
raise ValueError(
f"fused qkv_proj has {w_full.shape[0]} rows, not {ckpt_tp} chunks of "
f"{q_per_chunk} Q + {k_per_chunk} K + {v_per_chunk} V rows."
)
# The scales are tiled per chunk; they collapse to one continuous grid when
# a chunk is a whole number of blocks (the SWA chunks are: 3712 = 29 * 128).
chunk_scale_rows = cdiv(rows_per_chunk, block)
rows = torch.arange(w_full.shape[0])
per_chunk_scales = s_full.shape[0] == ckpt_tp * chunk_scale_rows
if per_chunk_scales:
scale_index = (rows // rows_per_chunk) * chunk_scale_rows + (
rows % rows_per_chunk
) // block
elif s_full.shape[0] == cdiv(w_full.shape[0], block):
scale_index = rows // block
else:
raise ValueError(
f"fused qkv_proj scale has {s_full.shape[0]} rows, expected either "
f"{ckpt_tp * chunk_scale_rows} ({ckpt_tp} chunks of "
f"{chunk_scale_rows} rows) or {cdiv(w_full.shape[0], block)} "
f"(one continuous grid)"
)
if tp_size == ckpt_tp and per_chunk_scales:
# One checkpoint chunk per rank: already [Q | K | V] for that rank, and
# its scale rows line up with ceil(rows_per_chunk / block).
return (
w_full.chunk(ckpt_tp, dim=0)[tp_rank],
s_full.chunk(ckpt_tp, dim=0)[tp_rank],
)
# Gather this rank's Q, K and V rows from the chunks that hold them.
q_heads_per_chunk = num_heads // ckpt_tp
kv_heads_per_chunk = num_kv_heads // ckpt_tp
head_rows = torch.arange(head_dim)
v_head_rows = torch.arange(v_head_dim)
row_index: list[torch.Tensor] = []
for head in q_head_ids:
chunk = head // q_heads_per_chunk
row_index.append(
chunk * rows_per_chunk + (head % q_heads_per_chunk) * head_dim + head_rows
)
for head in kv_head_ids:
chunk = head // kv_heads_per_chunk
row_index.append(
chunk * rows_per_chunk
+ q_per_chunk
+ (head % kv_heads_per_chunk) * head_dim
+ head_rows
)
for head in kv_head_ids:
chunk = head // kv_heads_per_chunk
row_index.append(
chunk * rows_per_chunk
+ q_per_chunk
+ k_per_chunk
+ (head % kv_heads_per_chunk) * v_head_dim
+ v_head_rows
)
index = torch.cat(row_index)
grouped = w_full[index].to(torch.float32) * s_full[
scale_index[index]
].repeat_interleave(block, dim=1)
return _requantize_fp8(grouped, index.numel(), block, w_full.dtype)
@support_torch_compile
class MiMoV2Model(nn.Module, EagleModelMixin):
@@ -819,6 +903,8 @@ class MiMoV2Model(nn.Module, EagleModelMixin):
v_head_dim=attn.v_head_dim,
tp_rank=tp_rank,
tp_size=tp_size,
# The fused qkv_proj is pre-sharded for this many ranks.
ckpt_tp=self.config.num_key_value_heads,
)
sharded = {"weight": w_rank, "weight_scale_inv": s_rank}
for kind, tensor in sharded.items():

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