Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 53 additions & 13 deletions vllm/model_executor/layers/fused_moe/router/gate_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@

import vllm._custom_ops as ops
from vllm.model_executor.custom_op import PluggableLayer
from vllm.model_executor.layers.linear import ReplicatedLinear
from vllm.model_executor.layers.linear import (
ReplicatedLinear,
UnquantizedLinearMethod,
)
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.platforms import current_platform
from vllm.utils.torch_utils import direct_register_custom_op

Expand All @@ -25,12 +29,18 @@ class GateLinear(ReplicatedLinear):
The ``out_dtype`` attribute is mutable and can be set after init
(e.g. when the required dtype depends on the expert quantization
method which is only known later).

A ``quant_config`` that actually quantizes the gate disables every
specialized tier, leaving plain ``ReplicatedLinear`` behavior.
"""

# (hidden_size, num_experts) pairs with an instantiated fp32 kernel:
# (3072, 256) -> MiniMax-M2/M2.5, (6144, 128) -> MiniMax-M3
FP32_SUPPORTED_SHAPES = {(3072, 256), (6144, 128)}
FP32_MAX_TOKENS = 32
# Largest batch for which tier 1 beats the cuBLAS epilogue. Subclasses
# whose router shape stays ahead further up the range may raise it.
LL_BF16_MAX_TOKENS = 16

def __init__(
self,
Expand All @@ -40,7 +50,10 @@ def __init__(
out_dtype: torch.dtype | None = None,
params_dtype: torch.dtype | None = None,
force_fp32_compute: bool = False,
skip_bias_add: bool = False,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
return_bias: bool = True,
):
is_hopper = current_platform.is_device_capability((9, 0))
is_blackwell = current_platform.is_device_capability_family(100)
Expand Down Expand Up @@ -72,17 +85,25 @@ def __init__(
input_size,
output_size,
bias=bias,
skip_bias_add=skip_bias_add,
params_dtype=params_dtype,
quant_config=None,
quant_config=quant_config,
prefix=prefix,
return_bias=return_bias,
)
self.out_dtype = out_dtype

# A quantized gate exposes no plain ``weight``, so every specialized
# tier below is disabled and forward falls back to ReplicatedLinear.
self.is_unquantized = isinstance(self.quant_method, UnquantizedLinearMethod)
can_use_specialized_kernels &= self.is_unquantized

self.allow_specialized_router_gemm = can_use_specialized_kernels

# fp32 specialized kernel eligibility (exact dims, fp32 weight)
self.allow_fp32_router_gemm = (
not bias
self.is_unquantized
and not bias
and self.weight.dtype == torch.float32
and (
(
Expand All @@ -94,7 +115,8 @@ def __init__(
)
)
self.allow_bf16x3_router_gemm = (
not bias
self.is_unquantized
and not bias
and self.weight.dtype == torch.float32
and current_platform.is_cuda()
and is_blackwell
Expand All @@ -108,7 +130,7 @@ def __init__(
# applies on any CUDA-alike device (no bias, since torch.mm has no bias
# term). The specialized-kernel gate above excludes family-120 Blackwell
# (GB10 / DGX Spark), which this tier still covers. See #49921.
self._router_gemm_no_bias = not bias
self._router_gemm_no_bias = self.is_unquantized and not bias
self._router_gemm_cublas_capable = (
current_platform.is_cuda() or current_platform.is_rocm()
) and self._router_gemm_no_bias
Expand Down Expand Up @@ -162,17 +184,26 @@ def set_out_dtype(self, out_dtype: torch.dtype) -> None:
and is_available()
)

def _return(
self, output: torch.Tensor
) -> torch.Tensor | tuple[torch.Tensor, Parameter | None]:
return output if not self.return_bias else (output, None)

def forward(
self, x: torch.Tensor
) -> torch.Tensor | tuple[torch.Tensor, Parameter | None]:
# Tier 1: cuteDSL ll_bf16_gemm (SM90+, any dims)
if self.allow_ll_bf16_gemm and x.shape[0] <= 16 and x.dtype == torch.bfloat16:
if (
self.allow_ll_bf16_gemm
and x.shape[0] <= self.LL_BF16_MAX_TOKENS
and x.dtype == torch.bfloat16
):
from vllm.model_executor.kernels.linear.cute_dsl.ll_bf16 import (
ll_bf16_gemm,
)

output = ll_bf16_gemm(x, self.weight)
return output, None
return self._return(output)

# Tier 2: fp32 specialized kernel (model-specific shapes, M<=32)
# Dispatch is wrapped in a custom op so that torch.compile/CUDA-graph
Expand All @@ -184,7 +215,7 @@ def forward(
output = torch.ops.vllm.fp32_router_gemm_dispatch(
x, self.weight, self.allow_bf16x3_router_gemm
)
return output, None
return self._return(output)

# Tier 3: bf16x3 CuteDSL kernel for fp32 router weights
if self.allow_bf16x3_router_gemm and x.dtype == torch.bfloat16:
Expand All @@ -193,20 +224,29 @@ def forward(
)

output = bf16x3_router_gemm(x, self.weight)
return output, None
return self._return(output)

# Tier 4: cuBLAS bf16→fp32
if self.allow_cublas_router_gemm and x.dtype == torch.bfloat16:
output = torch.mm(x, self.weight.T, out_dtype=torch.float32)
return output, None
return self._return(output)

# Tier 5: F.linear (ReplicatedLinear)
if self.out_dtype is not None and x.dtype != self.weight.dtype:
if (
self.out_dtype is not None
and self.is_unquantized
and x.dtype != self.weight.dtype
):
x = x.to(self.weight.dtype)
output, output_bias = super().forward(x)
base_output = super().forward(x)
output_bias: Parameter | None = None
if isinstance(base_output, tuple):
output, output_bias = base_output
else:
output = base_output
if self.out_dtype is not None and output.dtype != self.out_dtype:
output = output.to(self.out_dtype)
return output, output_bias
return output if not self.return_bias else (output, output_bias)


_FP32_ROUTER_GEMM_MAX_TOKENS = GateLinear.FP32_MAX_TOKENS
Expand Down
5 changes: 2 additions & 3 deletions vllm/model_executor/models/AXK1.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,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,
)
from vllm.model_executor.layers.fused_moe.utils import (
Expand Down Expand Up @@ -128,11 +129,9 @@ def __init__(
"Only silu is supported for now."
)

self.gate = ReplicatedLinear(
self.gate = GateLinear(
config.hidden_size,
config.n_routed_experts,
bias=False,
quant_config=None,
prefix=f"{prefix}.gate",
)
if config.topk_method == "noaux_tc":
Expand Down
10 changes: 6 additions & 4 deletions vllm/model_executor/models/afmoe.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
MoERunner,
)
from vllm.model_executor.layers.layernorm import RMSNorm
Expand Down Expand Up @@ -82,11 +83,12 @@ def __init__(
)

# Router gate
self.gate = nn.Linear(
self.gate = GateLinear(
config.hidden_size,
config.num_experts,
bias=False,
dtype=torch.float32,
out_dtype=torch.float32,
params_dtype=torch.float32,
prefix=f"{prefix}.gate",
)
self.expert_bias = nn.Parameter(
torch.empty(config.num_experts, dtype=torch.float32)
Expand Down Expand Up @@ -140,7 +142,7 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
num_tokens, hidden_dim = hidden_states.shape
hidden_states = hidden_states.view(-1, hidden_dim)

router_logits = self.gate(hidden_states.to(dtype=torch.float32))
router_logits, _ = self.gate(hidden_states)

final_hidden_states = self.experts(
hidden_states=hidden_states, router_logits=router_logits
Expand Down
14 changes: 9 additions & 5 deletions vllm/model_executor/models/bailing_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@
)
from vllm.model_executor.layers.activation import SiluAndMul
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.fused_moe import FusedMoEFactory
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (
MergedColumnParallelLinear,
Expand Down Expand Up @@ -243,11 +246,12 @@ def __init__(
else:
self.router_dtype = torch.bfloat16

self.gate = nn.Linear(
self.gate = GateLinear(
self.hidden_size,
self.num_experts,
bias=False,
dtype=self.router_dtype,
out_dtype=self.router_dtype,
params_dtype=self.router_dtype,
prefix=f"{prefix}.gate",
)

if getattr(config, "moe_router_enable_expert_bias", False):
Expand Down Expand Up @@ -312,7 +316,7 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = hidden_states.view(-1, hidden_size)

# router_logits: (num_tokens, n_experts)
router_logits = self.gate(hidden_states.to(self.router_dtype))
router_logits, _ = self.gate(hidden_states)
router_logits = router_logits.to(hidden_states.dtype)

final_hidden_states = self.experts(
Expand Down
47 changes: 12 additions & 35 deletions vllm/model_executor/models/bailing_moe_linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.configuration_utils import PretrainedConfig

from vllm.compilation.decorators import support_torch_compile
Expand All @@ -19,6 +18,7 @@
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe import (
FusedMoEFactory,
GateLinear,
fused_moe_make_expert_params_mapping,
)
from vllm.model_executor.layers.layernorm import RMSNorm
Expand Down Expand Up @@ -229,37 +229,6 @@ def forward(
return self.mla_attn(positions, hidden_states)


class BailingMoEGate(nn.Module):
def __init__(
self,
config: PretrainedConfig,
params_dtype: torch.dtype | None = None,
prefix: str = "",
):
super().__init__()
if params_dtype is None:
params_dtype = torch.get_default_dtype()
self.params_dtype = params_dtype
self.weight = nn.Parameter(
torch.empty(
(config.num_experts, config.hidden_size),
dtype=self.params_dtype,
),
)
if getattr(config, "moe_router_enable_expert_bias", False):
self.expert_bias = nn.Parameter(
torch.empty((config.num_experts,), dtype=torch.float32),
)
else:
self.expert_bias = None

def forward(self, hidden_states):
logits = F.linear(hidden_states.to(self.weight.dtype), self.weight, None).to(
hidden_states.dtype
)
return logits


class BailingMoeV25(nn.Module):
"""Bailing MoE v2.5 - standalone implementation for linear attention model."""

Expand Down Expand Up @@ -296,11 +265,19 @@ def __init__(
self.router_dtype = torch.bfloat16

# Gate for routing
self.gate = BailingMoEGate(
config=config,
self.gate = GateLinear(
self.hidden_size,
self.num_experts,
out_dtype=self.router_dtype,
params_dtype=self.router_dtype,
prefix=f"{prefix}.gate",
)
if getattr(config, "moe_router_enable_expert_bias", False):
self.gate.expert_bias = nn.Parameter(
torch.empty((self.num_experts,), dtype=torch.float32),
)
else:
self.gate.expert_bias = None
correction_bias = (
self.gate.expert_bias if self.gate.expert_bias is not None else None
)
Expand Down Expand Up @@ -357,7 +334,7 @@ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = hidden_states.contiguous().view(-1, hidden_size)

# router_logits: (num_tokens, n_experts)
router_logits = self.gate(hidden_states.to(self.router_dtype))
router_logits, _ = self.gate(hidden_states)
router_logits = router_logits.to(hidden_states.dtype)

final_hidden_states = self.experts(
Expand Down
Loading
Loading