[ROCm][Perf] MXFP8 dense-linear + grouped-MoE GEMM optimizations for MiniMax-M3 (#46117)

Signed-off-by: amd-ethany <amd-ethany@users.noreply.github.com>
Co-authored-by: amd-ethany <amd-ethany@users.noreply.github.com>
This commit is contained in:
Ethan Yang
2026-07-08 04:03:34 +00:00
committed by GitHub
co-authored by amd-ethany
parent 9021589498
commit d9e57ea82e
3 changed files with 226 additions and 42 deletions
+87
View File
@@ -284,6 +284,93 @@ def test_mxfp8_native_moe(T, H, inter, E, top_k):
assert _relerr(got, ref) < 5e-2
# --------------------------------------------------------------------------- #
# Native MXFP8 grouped GEMM (dot_scaled) vs pure-PyTorch grouped matmul
# --------------------------------------------------------------------------- #
def _ref_grouped_gemm(a_deq, w_deq, topk_ids, a_div, num_valid, mul_weight=None):
"""Pure-PyTorch reference for ``_grouped_gemm_mxfp8``.
For each routed (expanded) token ``tid in [0, num_valid)`` the kernel writes
``out[tid] = a[tid // a_div] @ w[expert(tid)].T`` (fp32 accumulate), optionally
scaled by ``mul_weight[tid]``. The expert for ``tid`` is ``topk_ids.flatten()
[tid]`` (row-major expansion: ``tid = token*top_k + slot``). This is computed
here with plain ``torch.matmul`` on the dequantized operands — independent of
the Triton ``dot_scaled`` path and of the (separate) aiter backend.
"""
eids = topk_ids.reshape(-1)
n = w_deq.shape[1]
out = torch.empty(num_valid, n, dtype=torch.float32, device=a_deq.device)
for tid in range(num_valid):
e = int(eids[tid].item())
out[tid] = a_deq[tid // a_div].float() @ w_deq[e].float().T
if mul_weight is not None:
out[tid] *= float(mul_weight[tid].item())
return out
@requires_gfx950
@pytest.mark.parametrize("T,N,K,E,top_k", [(8, 256, 128, 8, 2), (5, 512, 256, 16, 4)])
@pytest.mark.parametrize("weighted", [False, True])
@torch.inference_mode()
def test_mxfp8_grouped_gemm_native(T, N, K, E, top_k, weighted):
"""Directly exercise ``_grouped_gemm_mxfp8`` against a non-Triton reference.
Covers both call modes used by ``fused_moe_mxfp8_native``:
* ``weighted=False`` -> g1: ``a_div=top_k`` (a-row shared across the top_k
expansions of a token), no per-token weight.
* ``weighted=True`` -> g2: ``a_div=1`` (one a-row per expansion), output
scaled by ``topk_weights``.
"""
from vllm.model_executor.layers.fused_moe.experts.mxfp8_native_moe import (
_grouped_gemm_mxfp8,
)
from vllm.model_executor.layers.fused_moe.moe_align_block_size import (
moe_align_block_size,
)
torch.manual_seed(0)
block_m = 64
a_div = 1 if weighted else top_k
m_routed = T * top_k
# a-rows: g1 reads one row per token (a_div=top_k); g2 one per expansion.
a_rows = m_routed if weighted else T
a_bf16 = torch.randn(a_rows, K, device=DEVICE, dtype=torch.bfloat16) * 0.5
w_bf16 = torch.randn(E, N, K, device=DEVICE, dtype=torch.bfloat16) * 0.1
a_fp8, a_scale = _mxfp8_e4m3_quantize_torch(a_bf16, is_sf_swizzled_layout=False)
w_fp8, w_scale = _mxfp8_e4m3_quantize_torch(w_bf16, is_sf_swizzled_layout=False)
logits = torch.randn(T, E, device=DEVICE, dtype=torch.float32)
topk_weights, topk_ids = logits.softmax(dim=-1).topk(top_k, dim=-1)
topk_weights = topk_weights.to(torch.float32)
topk_ids = topk_ids.to(torch.int32)
mul = topk_weights.reshape(-1) if weighted else None
sorted_ids, expert_ids, num_post = moe_align_block_size(
topk_ids, block_m, E, None, ignore_invalid_experts=False
)
got = _grouped_gemm_mxfp8(
a_fp8,
a_scale,
w_fp8,
w_scale,
sorted_ids,
expert_ids,
num_post,
m_routed,
top_k,
block_m,
torch.bfloat16,
a_div=a_div,
mul_weight_by=mul,
)
# Reference: dequant the SAME bits the kernel reads, plain torch matmul.
a_deq = dequant_mxfp8_to_bf16(a_fp8, a_scale)
w_deq = dequant_mxfp8_to_bf16(w_fp8, w_scale)
ref = _ref_grouped_gemm(a_deq, w_deq, topk_ids, a_div, m_routed, mul)
assert got.shape == (m_routed, N)
assert _relerr(got, ref) < 5e-2
# --------------------------------------------------------------------------- #
# MXFP8 linear emulation: BF16-at-load (default) vs per-step dequant + switch
# --------------------------------------------------------------------------- #
@@ -89,13 +89,7 @@ def _mxfp8_dot_scaled_linear(
N = w.shape[0]
x_q, x_scale = mxfp8_e4m3_quantize(x)
out = torch.empty((M, N), dtype=x.dtype, device=x.device)
# Regime-gated launch tiles for gfx950, tuned at MiniMax-M3 shapes:
# for example, 8k/1k, 1k/1k
if M >= 1024:
BLOCK_M, BLOCK_N, num_warps, num_stages = 128, 256, 8, 2
else:
BLOCK_M, BLOCK_N, num_warps, num_stages = 64, 64, 4, 2
BLOCK_K = 128
BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages = _select_cfg(M, N, K)
grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(N, BLOCK_N))
_mxfp8_linear_kernel[grid](
x_q,
@@ -125,6 +119,81 @@ def _mxfp8_dot_scaled_linear(
return out
def _select_cfg(M, N, K):
"""(BLOCK_M, BLOCK_N, BLOCK_K, num_warps, num_stages) — graph-tuned on gfx950.
The M-bucketed, shape-adaptive tile selection here is the speedup over the
upstream 2-bucket launcher. Tiles are pipelined (num_stages>=2, larger BLOCK_K)
and occupancy- and shape-aware: keyed on the LOCAL (M, N, K), so it adapts to the
TP-sharded shapes (e.g. MiniMax-M3 TP=4 vs TP=8, where local N and K differ) —
large-K prefill uses BLOCK_K=256; short-K (K=768) widens N. BLOCK_K must divide K
(the K-loop is unmasked), so every BLOCK_K below is guarded to be K-divisible
(served K: 384/768/1024/2048/6144).
"""
if M <= 64:
# decode (M in {1,32,64}): tiny-M GEMV is weight-BW + GPU-OCCUPANCY bound. The
# lever is NARROW BLOCK_N=16 (maximize N-tiles so more CUs stream the weight in
# parallel) + LARGE BLOCK_K (fewer K-iters, bigger coalesced weight loads).
# Tuned by CUDA-graph replay latency. Optimal at both TP=4 and TP=8.
if K % 1024 == 0: # K=2048, 6144 -> graph-best 16x16x1024 (all M)
return 16, 16, 1024, 2, 2
if K % 512 == 0:
return 16, 16, 512, 2, 3
if K % 256 == 0: # K=768 (shared_down) -> graph-best 16x32x256
return 16, 32, 256, 4, 3
return 16, 32, 128, 4, 3
# mid-M (65..256) on SMALL local-N: still occupancy-bound (a 64x64 tile makes too
# few N-tiles), so the narrow-BLOCK_N decode-style tile fills the CUs better.
# N<=1536 covers the real fused-qkv local N at TP=8: q heads shard but the GQA KV
# (4) + sparse-indexer (4) heads are < TP=8, so vLLM replicates them to 1/rank ->
# N = 1024 + 4*128 = 1536 (not 2560/2=1280). For the wider 1280<N<=1536 band the
# narrow tile only wins up to M=128 (at M=256 the 64x64 tile is better), so cap it
# there; N<=1280 keeps the narrow tile through M=256. TP=4 qkv N=2560 is unchanged.
if (M <= 256 and N <= 1280) or (M <= 128 and N <= 1536):
if K % 1024 == 0:
return 16, 16, 1024, 2, 2
if K % 512 == 0:
return 16, 16, 512, 2, 3
if K % 256 == 0:
return 16, 16, 256, 2, 3
return 16, 16, 128, 2, 3
# right-sized launch grid (host-side), used to gate the tall 256-BLOCK_M tile.
occ = triton.cdiv(M, 256) * triton.cdiv(N, 128)
if K <= 1024: # short-K (shared_down K=384/768; TP=8 o_proj K=1024)
if M <= 256:
return (64, 64, 256, 8, 2) if K % 256 == 0 else (64, 64, 128, 8, 2)
# large prefill. (The former 256x128x256 tall tile was faster only on triton
# 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, 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
# the entry requires K%128==0) for any other K to stay correct.
if M <= 256: # conc~128 decode + small prefill chunk: occupancy tile
if K % 512 == 0:
return 64, 64, 512, 8, 2
return (64, 64, 256, 8, 2) if K % 256 == 0 else (64, 64, 128, 8, 2)
if M <= 1024: # medium prefill chunk: BN=64 keeps small-N occupied
return (128, 64, 256, 8, 3) if K % 256 == 0 else (128, 64, 128, 8, 3)
# large prefill (M > 1024). The previously graph-tuned tall 256x128x256 and deep
# 128x128x512 tiles won only on triton 3.6; on triton 3.7 their larger BLOCK_M /
# BLOCK_K register+LDS footprint spills (or hits "out of resources" on stricter
# ROCm/triton builds). The 128x128x256 tile is equal-or-faster on triton 3.7 (the
# M=4096,N=2048,K=6144 shape: ~104us vs the 256x128x256 tile's ~184us), within ~5%
# on 3.6, and inside the footprint of the tiles used elsewhere in this selector.
# 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
# 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:
return 128, 64, 256, 8, 3
return (128, 128, 256, 8, 2) if K % 256 == 0 else (128, 256, 128, 8, 3)
class RocmDotScaledMxfp8LinearKernel(Mxfp8LinearKernel):
"""Native CDNA4 (gfx950) MXFP8 linear via Triton ``tl.dot_scaled``."""
@@ -19,7 +19,6 @@ and the top-k weighted reduction run in PyTorch between/after the two GEMMs.
import torch
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm.logger import init_logger
from vllm.model_executor.layers.fused_moe.experts.mxfp8_emulation_moe import (
Mxfp8TritonExpertsBase,
)
@@ -32,7 +31,26 @@ from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
logger = init_logger(__name__)
def _select_cfg(M, N, K, block_m):
"""Pick the launch config from host constants only (M=num_valid_tokens, N, K,
block_m) — graph-capture safe (no GPU-scalar branch)."""
# Per-regime winners (measured, isolated cuda-event A/B on gfx950, GPU 3):
# BLOCK_K=256 (fewer K-iters + bigger MX scale-load coalesced with the dot),
# num_stages=2 (software-pipeline overlaps the E8M0 scale-load with the scaled
# MFMA), GROUP_SIZE_M=4 (XCD-friendly swizzle that keeps each touched expert's
# A rows + B column-tiles L2/MALL-resident across its N-tiles -> kills the
# redundant A re-read). num_warps stays 8 (wave64 here did NOT spill: VGPR fits
# and 4 warps was neutral/worse in measurement). BLOCK_K must be a power of two
# and divide K (K=6144 and K=768 are both multiples of 256).
BLOCK_K = 256 if K % 256 == 0 else 128
return {
"BLOCK_N": 128,
"BLOCK_K": BLOCK_K,
"GROUP_SIZE_M": 4,
"num_warps": 8,
"num_stages": 2,
}
@triton.jit
@@ -46,6 +64,7 @@ def _mxfp8_grouped_gemm_kernel(
sorted_token_ids_ptr,
expert_ids_ptr,
num_tokens_post_padded_ptr,
EM,
N,
K,
num_valid_tokens,
@@ -67,9 +86,33 @@ def _mxfp8_grouped_gemm_kernel(
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
BLOCK_K: tl.constexpr,
GROUP_SIZE_M: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
# ---- Grid-swizzle (super-grouping over M) so consecutive program-ids cover a
# GROUP_SIZE_M x grid_n super-block. This keeps a touched expert's A rows + its
# B-weight column-tiles L2/MALL-resident across the N-tiles they share, killing
# most of the redundant A re-read (the single largest redundant-traffic source:
# dot_scaled keeps operands in registers, so A is otherwise re-fetched per N-tile).
# ``num_pid_m`` uses EM (= sorted_token_ids.shape[0]), the SAME bound the grid
# is sized from, NOT the runtime ``num_tokens_post_padded`` (<= EM). This keeps
# the swizzle consistent with the grid: ``group_size_m`` is always >= 1 for every
# launched program, so the ``% group_size_m`` / ``// group_size_m`` below can never
# hit modulo/division-by-zero. ``num_tokens_post_padded`` is loaded afterwards and
# only gates the early-return. Mirrors the reference ``fused_moe_kernel``.
pid = tl.program_id(0)
num_pid_m = tl.cdiv(EM, BLOCK_M)
num_pid_n = tl.cdiv(N, BLOCK_N)
if GROUP_SIZE_M == 1:
pid_m = pid % num_pid_m
pid_n = pid // num_pid_m
else:
num_pid_in_group = GROUP_SIZE_M * num_pid_n
group_id = pid // num_pid_in_group
first_pid_m = group_id * GROUP_SIZE_M
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
pid_n = (pid % num_pid_in_group) // group_size_m
num_post = tl.load(num_tokens_post_padded_ptr)
if pid_m * BLOCK_M >= num_post:
return
@@ -140,9 +183,6 @@ def _grouped_gemm_mxfp8(
a_div: int,
mul_weight_by: torch.Tensor | None = None,
expert_map: torch.Tensor | None = None,
block_n: int = 128,
num_warps: int = 8,
num_stages: int = 2,
) -> torch.Tensor:
M_routed = num_valid_tokens
E, N, K = w.shape
@@ -152,8 +192,16 @@ def _grouped_gemm_mxfp8(
# written — zero them so the downstream reduction ignores their garbage.
alloc = torch.zeros if expert_map is not None else torch.empty
out = alloc((M_routed, N), dtype=out_dtype, device=a_q.device)
BLOCK_K = 128
grid = (triton.cdiv(sorted_token_ids.shape[0], block_m), triton.cdiv(N, block_n))
cfg = _select_cfg(M_routed, N, K, block_m)
BLOCK_N = cfg["BLOCK_N"]
BLOCK_K = cfg["BLOCK_K"]
GROUP_SIZE_M = cfg["GROUP_SIZE_M"]
n_pid_m = triton.cdiv(sorted_token_ids.shape[0], block_m)
n_pid_n = triton.cdiv(N, BLOCK_N)
grid = (n_pid_m * n_pid_n,)
_mxfp8_grouped_gemm_kernel[grid](
a_q,
a_scale,
@@ -164,6 +212,7 @@ def _grouped_gemm_mxfp8(
sorted_token_ids,
expert_ids,
num_tokens_post_padded,
sorted_token_ids.shape[0], # EM: sizes both the grid and the swizzle
N,
K,
num_valid_tokens,
@@ -183,29 +232,15 @@ def _grouped_gemm_mxfp8(
A_DIV=a_div,
MUL_WEIGHT=mul_weight_by is not None,
BLOCK_M=block_m,
BLOCK_N=block_n,
BLOCK_N=BLOCK_N,
BLOCK_K=BLOCK_K,
num_warps=num_warps,
num_stages=num_stages,
GROUP_SIZE_M=GROUP_SIZE_M,
num_warps=cfg["num_warps"],
num_stages=cfg["num_stages"],
)
return out
# Tuned native-MXFP8 launch tiles for gfx950 (CDNA4) at MiniMax-M3 MoE shapes.
# For example, 8k/1k, 1k/1k cases.
_MXFP8_PREFILL_TILES = dict(block_m=128, block_n=256, num_warps=8, num_stages=2)
_MXFP8_DECODE_TILES = dict(block_m=64, block_n=64, num_warps=4, num_stages=2)
_MXFP8_PREFILL_MIN_TOKENS = 1024
def _mxfp8_moe_tiles(num_tokens: int) -> dict:
"""Pick grouped-GEMM launch tiles by regime (token count)."""
if num_tokens >= _MXFP8_PREFILL_MIN_TOKENS:
return _MXFP8_PREFILL_TILES
return _MXFP8_DECODE_TILES
def fused_moe_mxfp8_native(
hidden_states: torch.Tensor, # [T, H] bf16
w13: torch.Tensor, # [E, 2I, H] fp8
@@ -225,8 +260,7 @@ def fused_moe_mxfp8_native(
top_k = topk_ids.shape[1]
M = T * top_k
tiles = _mxfp8_moe_tiles(T)
block_m = tiles["block_m"]
block_m = 64
# Bin by the actual number of expert weight rows. With fused shared experts
# the weight tensor has more rows than ``global_num_experts`` (the routed
# count), and their ids fall outside [0, global_num_experts); binning by the
@@ -257,9 +291,6 @@ def fused_moe_mxfp8_native(
hidden_states.dtype,
a_div=top_k,
expert_map=expert_map,
block_n=tiles["block_n"],
num_warps=tiles["num_warps"],
num_stages=tiles["num_stages"],
) # [M, 2I]
# SwiGLU-OAI (split layout: gate=g1[:, :I], up=g1[:, I:]) FUSED with the
@@ -288,9 +319,6 @@ def fused_moe_mxfp8_native(
a_div=1,
mul_weight_by=topk_weights.reshape(-1).to(torch.float32),
expert_map=expert_map,
block_n=tiles["block_n"],
num_warps=tiles["num_warps"],
num_stages=tiles["num_stages"],
) # [M, H] == [T*top_k, H]
return g2.view(T, top_k, H).sum(dim=1).to(hidden_states.dtype)