[Refactor][ROCm] Migrate the RDNA3 W4A16 MoE to the oracle/experts pa… (#55522)

Signed-off-by: JartX <sagformas@epdcenter.es>
This commit is contained in:
JartX
2026-09-12 21:20:26 +08:00
committed by GitHub
parent 1b29c508bc
commit 986e2f870a
10 changed files with 453 additions and 377 deletions
@@ -0,0 +1,235 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Fused MoE W4A16 experts on the RDNA3 (gfx1100) HIP kernel.
``moe_gptq_gemm_rdna3`` is a single HIP kernel launch per GEMM that handles
expert routing + W4A16 dequant + dot product with atomic output accumulation.
Weight format (per expert, same as the dense RDNA3 W4A16 kernel):
- Packed int32 ``[E, K/8, N]`` with exllama shuffle
- Scales ``[E, groups, N]`` in activation dtype
- Zero points ``[E, groups, N/8]`` packed int32 (synthesized, symmetric only)
"""
import torch
import vllm._custom_ops as ops
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm.model_executor.layers.fused_moe.activation import (
MoEActivation,
apply_moe_activation_supported,
)
from vllm.model_executor.layers.fused_moe.config import (
FusedMoEConfig,
FusedMoEParallelConfig,
FusedMoEQuantConfig,
)
from vllm.model_executor.layers.fused_moe.moe_align_block_size import (
moe_align_block_size,
)
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
kInt4Static,
kInt4Static32,
)
from vllm.platforms import current_platform
def rdna3_moe_kernel_available() -> bool:
"""Whether the fused RDNA3 MoE HIP kernel is built into this binary."""
if not current_platform.is_rocm():
return False
from vllm.platforms.rocm import on_gfx1100
return (
on_gfx1100()
and hasattr(torch.ops, "_rocm_C")
and hasattr(torch.ops._rocm_C, "moe_gptq_gemm_rdna3")
)
class Rdna3WNA16Experts(mk.FusedMoEExpertsModular):
"""W4A16 experts backed by ``moe_gptq_gemm_rdna3`` (gfx1100).
Both GEMMs accumulate atomically, so their destinations are zeroed first.
The second GEMM is given ``output_topk``, which makes it reduce over the
top-k dimension while it accumulates — the ``moe_sum`` launch and the
``[M * top_k, K]`` intermediate are fused away, hence
``TopKWeightAndReduceNoOP``.
"""
def __init__(
self,
moe_config: FusedMoEConfig,
quant_config: FusedMoEQuantConfig,
max_num_tokens: int | None = None,
num_dispatchers: int | None = None,
):
assert quant_config.use_int4_w4a16, "Supports only int4_w4a16"
super().__init__(
moe_config=moe_config,
quant_config=quant_config,
max_num_tokens=max_num_tokens,
num_dispatchers=num_dispatchers,
)
self._empty_topk_weights: torch.Tensor | None = None
@staticmethod
def activation_format() -> mk.FusedMoEActivationFormat:
return mk.FusedMoEActivationFormat.Standard
def finalize_weight_and_reduce_impl(self) -> mk.TopKWeightAndReduce:
return TopKWeightAndReduceNoOP()
@staticmethod
def _supports_current_device() -> bool:
return rdna3_moe_kernel_available()
@staticmethod
def _supports_no_act_and_mul() -> bool:
return True
@staticmethod
def _supports_quant_scheme(
weight_key: QuantKey | None,
activation_key: QuantKey | None,
) -> bool:
# Symmetric int4 weights only: the kernel consumes synthesized zero
# points and has no path for checkpoint zero points.
return activation_key is None and weight_key in (kInt4Static, kInt4Static32)
@staticmethod
def _supports_activation(activation: MoEActivation) -> bool:
return apply_moe_activation_supported(activation)
@staticmethod
def _supports_parallel_config(moe_parallel_config: FusedMoEParallelConfig) -> bool:
return not (
moe_parallel_config.use_fi_nvl_two_sided_kernels
or moe_parallel_config.use_fi_nvl_one_sided_kernels
)
def moe_problem_size(
self,
a1: torch.Tensor,
w1: torch.Tensor,
w2: torch.Tensor,
topk_ids: torch.Tensor,
) -> tuple[int, int, int, int, int]:
# Weights are packed K-first: w1 is [E, K // 8, w13_shards * N] and
# w2 is [E, N // 8, K], so neither N nor K can be read off a trailing
# dimension the way the base implementation does.
assert w1.dim() == 3 and w2.dim() == 3
assert a1.dim() == 2
assert topk_ids.size(0) == a1.size(0), f"{topk_ids.size(0)} != {a1.size(0)}"
return w1.size(0), a1.size(0), w2.size(1) * 8, a1.size(-1), 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, ...]]:
# The modular kernel provisions the output buffer out of workspace13,
# so both GEMM-1 buffers have to live in workspace2 — the second GEMM
# reads the activation output while accumulating into the output.
gate_up = N if not activation.is_gated else 2 * N
return ((M, K), (M * topk * (gate_up + N),), (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:
assert self.w1_scale is not None and self.w2_scale is not None
assert self.w1_zp is not None and self.w2_zp is not None
E, M, N, K, top_k = self.moe_problem_size(hidden_states, w1, w2, topk_ids)
if global_num_experts == -1:
global_num_experts = E
gate_up = w1.size(2)
act_n = self.adjust_N_for_activation(gate_up, activation)
rows = M * top_k
scratch = workspace2.view(-1)
gate_up_out = scratch[: rows * gate_up].view(rows, gate_up)
act_out = scratch[rows * gate_up : rows * (gate_up + act_n)].view(rows, act_n)
# BLOCK_SIZE_M=1 for decode (no padding waste), 4 for prefill.
block_size_m = 1 if M <= 4 else 4
sorted_token_ids, expert_ids, num_tokens_post_padded = moe_align_block_size(
topk_ids,
block_size_m,
global_num_experts,
expert_map,
)
if (
self._empty_topk_weights is None
or self._empty_topk_weights.device != hidden_states.device
):
self._empty_topk_weights = torch.empty(
0, dtype=torch.float32, device=hidden_states.device
)
topk_weights_f32 = topk_weights.reshape(-1).float()
no_topk_weights = self._empty_topk_weights
gate_up_out.zero_()
ops.moe_gptq_gemm_rdna3(
hidden_states,
gate_up_out,
w1,
self.w1_scale,
self.w1_zp,
topk_weights_f32 if apply_router_weight_on_input else no_topk_weights,
sorted_token_ids,
expert_ids,
num_tokens_post_padded,
top_k,
block_size_m,
apply_router_weight_on_input,
)
self.activation(activation, act_out, gate_up_out)
# output_topk=top_k makes the kernel accumulate into out[token_id],
# fusing the top-k reduction into the atomic write-back.
output.zero_()
ops.moe_gptq_gemm_rdna3(
act_out,
output,
w2,
self.w2_scale,
self.w2_zp,
no_topk_weights if apply_router_weight_on_input else topk_weights_f32,
sorted_token_ids,
expert_ids,
num_tokens_post_padded,
1,
block_size_m,
not apply_router_weight_on_input,
output_topk=top_k,
)
@@ -7,6 +7,7 @@ from typing import Any
import torch
from compressed_tensors.quantization import (
QuantizationArgs,
QuantizationStrategy,
)
import vllm._custom_ops as ops
@@ -41,8 +42,10 @@ from vllm.model_executor.layers.quantization.utils.marlin_utils import (
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
pack_quantized_values_into_int32,
)
from vllm.platforms import current_platform
from vllm.scalar_type import scalar_types
logger = init_logger(__name__)
@@ -56,6 +59,7 @@ class WNA16MoEBackend(Enum):
TRITON = "TRITON"
XPU = "XPU"
EMULATION = "EMULATION"
RDNA3 = "RDNA3"
def backend_to_kernel_cls(
@@ -100,6 +104,12 @@ def backend_to_kernel_cls(
)
return [Int4EmulationTritonExperts]
elif backend == WNA16MoEBackend.RDNA3:
from vllm.model_executor.layers.fused_moe.experts.rdna3_moe import (
Rdna3WNA16Experts,
)
return [Rdna3WNA16Experts]
else:
raise ValueError(f"Unknown WNA16 MoE backend: {backend.value}")
@@ -114,6 +124,8 @@ def _get_priority_backends() -> list[WNA16MoEBackend]:
return [WNA16MoEBackend.XPU]
return [
# Native HIP kernel, gated on gfx1100 by _supports_current_device().
WNA16MoEBackend.RDNA3,
WNA16MoEBackend.FLASHINFER_TRTLLM,
WNA16MoEBackend.MARLIN,
WNA16MoEBackend.BATCHED_MARLIN,
@@ -134,6 +146,18 @@ def _backend_incompatibility_reason(
if backend == WNA16MoEBackend.FLASHINFER_TRTLLM and (may_have_zp or may_have_bias):
return "zero points and bias are not supported"
if backend == WNA16MoEBackend.RDNA3:
if not isinstance(quant_config, QuantizationArgs):
return "only compressed-tensors checkpoints are supported"
if may_have_zp:
return "asymmetric checkpoints are not supported"
if may_have_bias:
return "expert bias is not supported"
if quant_config.actorder == "group":
return "group activation ordering is not supported"
if quant_config.strategy != QuantizationStrategy.GROUP:
return "only group-wise scales are supported"
from vllm.model_executor.layers.quantization.auto_awq import AutoAWQConfig
from vllm.model_executor.layers.quantization.auto_gptq import AutoGPTQConfig
from vllm.model_executor.layers.quantization.moe_wna16 import MoeWNA16Config
@@ -190,6 +214,7 @@ def map_wna16_backend(runner_backend: MoEBackend) -> WNA16MoEBackend:
"humming": WNA16MoEBackend.HUMMING,
"flashinfer_trtllm": WNA16MoEBackend.FLASHINFER_TRTLLM,
"emulation": WNA16MoEBackend.EMULATION,
"rdna3": WNA16MoEBackend.RDNA3,
}
if backend := mapping.get(runner_backend):
return backend
@@ -372,6 +397,9 @@ def make_wna16_moe_kernel(
from vllm.model_executor.layers.fused_moe.experts.int4_emulation_moe import (
Int4EmulationTritonExperts,
)
from vllm.model_executor.layers.fused_moe.experts.rdna3_moe import (
Rdna3WNA16Experts,
)
from vllm.model_executor.layers.fused_moe.experts.xpu_moe import (
XPUExpertsWNA16,
)
@@ -387,6 +415,7 @@ def make_wna16_moe_kernel(
XPUExpertsWNA16,
CPUExpertsInt4,
Int4EmulationTritonExperts,
Rdna3WNA16Experts,
)
if backend == WNA16MoEBackend.HUMMING:
allowed_experts += tuple(backend_to_kernel_cls(WNA16MoEBackend.HUMMING))
@@ -811,6 +840,78 @@ def _process_awq_weights_marlin(
)
def _synthesize_rdna3_qzeros(
groups: int, out_features: int, device: torch.device
) -> torch.Tensor:
"""Create the packed zero-point tensor for symmetric quantization.
GPTQv1 +1 quirk: the kernel adds 1 to the stored zeros, so encode
(bias - 1) = 7 for uint4b8 (bias=8).
"""
zeros = torch.full(
(groups, out_features),
scalar_types.uint4b8.bias - 1,
dtype=torch.int32,
device=device,
)
return pack_quantized_values_into_int32(zeros, scalar_types.uint4b8, packed_dim=1)
def _process_weights_rdna3(
w13: torch.Tensor,
w2: torch.Tensor,
w13_scale: torch.Tensor,
w2_scale: torch.Tensor,
group_size: int,
) -> tuple[
torch.Tensor, # w13_qweight
torch.Tensor, # w2_qweight
torch.Tensor, # w13_scales
torch.Tensor, # w2_scales
torch.Tensor | None, # w13_qzeros
torch.Tensor | None, # w2_qzeros
torch.Tensor | None, # w13_input_global_scale
torch.Tensor | None, # w2_input_global_scale
torch.Tensor | None, # w13_bias
torch.Tensor | None, # w2_bias
]:
"""RDNA3 (gfx1100) W4A16 weight post-processing.
Interleaves the packed nibbles per expert (the exllama shuffle the dense
RDNA3 kernel also uses) and synthesizes the symmetric zero points that
``moe_gptq_gemm_rdna3`` dequantizes with. The packed layout
``[E, K // 8, N]`` and the ``[E, groups, N]`` scales are already what the
kernel wants, so neither is repacked.
"""
device = w13.device
num_experts = w13.size(0)
for e in range(num_experts):
w13_e = w13[e].contiguous()
ops.gptq_shuffle(w13_e, 4)
w13[e] = w13_e
w2_e = w2[e].contiguous()
ops.gptq_shuffle(w2_e, 4)
w2[e] = w2_e
def _qzeros(w: torch.Tensor) -> torch.Tensor:
qz = _synthesize_rdna3_qzeros((w.size(1) * 8) // group_size, w.size(2), device)
return qz.unsqueeze(0).expand(num_experts, -1, -1).contiguous()
return (
w13,
w2,
w13_scale.contiguous(),
w2_scale.contiguous(),
_qzeros(w13),
_qzeros(w2),
None, # w13_input_global_scale
None, # w2_input_global_scale
None, # w13_bias
None, # w2_bias
)
def _process_weights_cpu(
quant_config: QuantizationConfig | QuantizationArgs | None,
w13: torch.Tensor,
@@ -1432,6 +1533,15 @@ def convert_to_wna16_moe_kernel_format(
w13_bias,
w2_bias,
)
elif backend == WNA16MoEBackend.RDNA3:
assert isinstance(quant_config, QuantizationArgs)
return _process_weights_rdna3(
w13,
w2,
w13_scale,
w2_scale,
quant_config.group_size,
)
elif backend == WNA16MoEBackend.CPU:
return _process_weights_cpu(
quant_config,
@@ -617,7 +617,6 @@ class RoutedExperts(PluggableLayer):
# against known CompressionFormat enum values that have this quality
if quant_method_name in (
"CompressedTensorsWNA16MoEMethod",
"CompressedTensorsWNA16RDNA3MoEMethod",
"CompressedTensorsW4A16FlydslMoEMethod",
):
if is_transposed: