Skip to content
Open
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
3 changes: 3 additions & 0 deletions amd_kernels/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ each category's `__init__.py` re-exports its families' `__all__` and holds no lo
experts, top 6, H 5120 I 2304.
- [`moe/mxfp4_h5120_i2304_e16_top3`](moe/mxfp4_h5120_i2304_e16_top3/README.md): routed MXFP8 x MXFP4 experts, 16 local
experts, top 3, H 5120 I 2304.
- [`moe/mxfp4_relu2_norm_h8192_i4096_e32_top8`](moe/mxfp4_relu2_norm_h8192_i4096_e32_top8/README.md): routed
MXFP8 x MXFP4 gate-only ReLU² experts, 32 local experts, top 8, H 8192 I 4096, with each expert's output
RMSNorm and the route weights in the combine.
- [`moe/fused_ep_mxfp4_h5120_i2304_e48_top6_ranks8`](moe/fused_ep_mxfp4_h5120_i2304_e48_top6_ranks8/README.md):
one-launch expert-parallel MoE on eight ranks: dispatch, experts, combine.
- [`moe/router_sqrtsoftplus_top6_h5120_e384`](moe/router_sqrtsoftplus_top6_h5120_e384/README.md): router: gate GEMM
Expand Down
47 changes: 47 additions & 0 deletions amd_kernels/moe/mxfp4_relu2_norm_h8192_i4096_e32_top8/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# MXFP8 x MXFP4 ReLU² routed experts with per-expert output RMSNorm, H8192 I4096 E32 top8 (gfx950)

## What it does

One expert-parallel rank's routed experts of a 256-expert top-8 MoE whose experts are gate-only ReLU² and whose every
expert output gets an RMSNorm with that expert's scale before the weighted top-k sum (Amazon Ergo): 32 local experts
(the count is the weights' first dimension, up to 63), hidden 8192, intermediate 4096, FlyDSL only. Weights MXFP4
(e2m1 + e8m0 per 32 K) in the layouts of AITER's `shuffle_weight_a16w4` / `shuffle_scale_a16w4` with `gate_up=False`
(the MXFP4 MoE weights a serving stack already shuffled for AITER serve as they are); activations MXFP8 (e4m3 + e8m0 per 32) or bf16 (quantized in the
routing launch). Per route: GEMM1 on the scaled FP4 x FP8 MFMA (fp32), `relu(g)^2` in fp32, requantized to MXFP8 in
the GEMM1 epilogue, GEMM2, one bf16 rounding. The combine normalizes each slot over its row with its expert's scale
(`bf16(y * rsqrt(mean(y^2) + eps) * scale)`), weights it and sums a token's 8 slots in slot order (fp32, one
rounding). No output atomics: runs are bitwise repeatable, graph replay equals eager. Contract: `reference.py`
(cosine >= 0.99999).

In: the router's `topk_ids` as local ids (an id outside [0, E), such as -1 or another rank's expert, contributes
zero), FP32 `topk_weights`, FP32 `norm_scale [E, 8192]`. Out: bf16 `[n, 8192]`, or with `return_slots` the
unnormalized slots.

## Entry points

- `ExpertWeights.from_row_major` / `ExpertWeights.from_shuffled`: the checkpoint tensors in the kernel layouts once,
or views of tensors already in them.
- `mxfp4_experts`: the experts of `n <= 1024` tokens; a `warm_up` entry per mode (bf16 or MXFP8, slots or combined).
- `kernel.compile_experts` / `host.DISPATCH`: GEMM1, GEMM2 and the normalizing combine in one launch after the sort
launch; the token count -> tile table. One call at a time per device (`host.ready_counters`).

## Performance

One MI350X, one TP8 + EP8 rank (256 experts, 32 local, so about one route in eight is local), bf16 tokens, graph
replay, median us per call; skewed: odds ~ 1 / (rank + 1) over the 256 experts.

| T tokens | 1 | 8 | 16 | 64 | 128 | 256 | 448 | 576 | 1024 |
|---|---|---|---|---|---|---|---|---|---|
| uniform | 31.7 | 58.4 | 78.2 | 182.2 | 198.9 | 211.4 | 231.2 | 246.7 | 292.0 |
| skewed | 14.0 | 44.8 | 50.0 | 133.4 | 172.5 | 245.8 | 224.4 | 248.8 | 288.7 |

Limit: the HBM weight stream (35.6 MB per expert); from T 64 most of the 32 local experts are read once per call
(T 64 uniform: about 28 experts in 182 us, 5.5 TB/s; T 1024: all 32 in 292 us, 3.9 TB/s as the MFMA work grows).

## Tests

```bash
python3 -m pytest tests/moe/mxfp4_relu2_norm_h8192_i4096_e32_top8 -q
python3 benchmarks/moe/mxfp4_relu2_norm_h8192_i4096_e32_top8/benchmark_experts.py
python3 benchmarks/moe/mxfp4_relu2_norm_h8192_i4096_e32_top8/sweep_dispatch.py
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the amd-kernels project
"""MXFP8 x MXFP4 routed experts, H 8192 I 4096 E 32 top 8: grouped GEMM1 + ReLU² + MXFP8 quant, GEMM2, and a
deterministic slot combine with each expert's output RMSNorm and the route weights."""

from .host import ExpertWeights, mxfp4_experts

__all__ = ["ExpertWeights", "mxfp4_experts"]
213 changes: 213 additions & 0 deletions amd_kernels/moe/mxfp4_relu2_norm_h8192_i4096_e32_top8/host.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the amd-kernels project
"""Routed-expert host: weight layouts, the token-count dispatch and the launch chain: sort with the optional bf16
quant, then GEMM1 + GEMM2 + the normalizing combine in one launch."""
import struct
from dataclasses import dataclass

import torch

from amd_kernels.common.tensor_shim import _run_compiled
from amd_kernels.warm_up import entry

from .kernel import (E, H, I, NE_MAX, READY_STRIDE, TOPK, compile_combine, compile_experts, compile_gemm1,
compile_gemm2, compile_sort, max_blocks)

MAX_TOKENS = 1024
# upper token bound -> (bm, GEMM1 K-waves, GEMM1 prefetch, GEMM1 16-column pairs per wave, GEMM1 ring stages,
# GEMM2 columns, GEMM2 prefetch, GEMM2 ring stages, cached weight loads for experts with several blocks (1 GEMM2,
# 2 GEMM1, 3 both), waves per workgroup, tokens per combine workgroup);
# measured under one TP8 + EP8 rank's uniform routing: benchmarks/moe/mxfp4_relu2_norm_h8192_i4096_e32_top8/sweep_dispatch.py
DISPATCH = (
(256, (16, 4, 3, 2, 0, 128, 4, 0, 1, 4, 1)),
(512, (32, 1, 3, 4, 3, 256, 4, 3, 3, 4, 2)),
(768, (32, 1, 3, 4, 3, 256, 4, 3, 3, 4, 3)),
(MAX_TOKENS, (32, 1, 3, 4, 3, 256, 4, 3, 3, 4, 4)),
)
SORT_TIERS = (16, 32, 64, 128, 192, 256, 384, 448, 512, 768, MAX_TOKENS)
WARM_UP_TOKENS = tuple(sorted(set(SORT_TIERS) | {bound for bound, _ in DISPATCH}))


def config_for(n_tokens: int):
return next(cfg for bound, cfg in DISPATCH if n_tokens <= bound)


def _eps_bits(eps: float) -> int:
return struct.unpack("<i", struct.pack("<f", eps))[0]


@dataclass
class ExpertWeights:
"""One layer's local experts (32 by default, up to ``NE_MAX`` with redundant experts) in the kernel layouts (a pure
permutation of the checkpoint bytes)."""

w1: torch.Tensor
w1_scale: torch.Tensor
w2: torch.Tensor
w2_scale: torch.Tensor

@property
def n_experts(self) -> int:
return self.w1.numel() // (I * (H // 2))

@classmethod
def from_row_major(cls, w1, w1_scale, w2, w2_scale) -> "ExpertWeights":
"""From the checkpoint layouts of ``reference`` (uint8 views of the packed FP4 and e8m0 tensors); once, before
graph capture. Same bytes as AITER's ``shuffle_weight_a16w4`` / ``shuffle_scale_a16w4`` with
``gate_up=False``."""
from aiter.ops.shuffle import shuffle_scale_a16w4, shuffle_weight_a16w4

n = w1.shape[0]
assert 1 <= n <= NE_MAX and w1.shape[1:] == (I, H // 2) and w2.shape[1:] == (H, I // 2)
u8 = torch.uint8
return cls(
shuffle_weight_a16w4(w1.view(u8), 16, False).view(u8).contiguous(),
shuffle_scale_a16w4(w1_scale.view(u8).reshape(-1, H // 32), n, False).view(u8).contiguous(),
shuffle_weight_a16w4(w2.view(u8), 16, False).view(u8).contiguous(),
shuffle_scale_a16w4(w2_scale.view(u8).reshape(-1, I // 32), n, False).view(u8).contiguous(),
)

@classmethod
def from_shuffled(cls, w1, w1_scale, w2, w2_scale) -> "ExpertWeights":
"""Tensors already in those layouts (vLLM's AITER MXFP4 MoE weights): uint8 views, no copy."""
u8 = torch.uint8
w = cls(w1.view(u8), w1_scale.view(u8), w2.view(u8), w2_scale.view(u8))
assert w.w1.numel() == w.n_experts * I * (H // 2) and w.w2.numel() == w.n_experts * H * (I // 2)
return w


def _activation(x, x_scales):
"""(codes, scales, quantize): MXFP8 rows pass through, bf16 rows get quant workgroups in the routing launch."""
if x.dtype == torch.bfloat16:
assert x_scales is None and x.is_contiguous()
dev = x.device
return (torch.empty(x.shape, dtype=torch.uint8, device=dev),
torch.empty((x.shape[0], H // 32), dtype=torch.uint8, device=dev), True)
assert x_scales is not None and x.is_contiguous() and x_scales.is_contiguous()
return x.view(torch.uint8), x_scales.view(torch.uint8), False


def moe_sort(topk_ids, topk_weights, block_m, x=None, xq=None, xs=None, ne=E):
"""Rows sorted by expert in blocks of ``block_m``: (ids, weights, block experts, [padded row count]). With bf16
``x`` the launch also quantizes its rows into ``xq`` / ``xs``."""
n = topk_ids.shape[0]
tier = next(t for t in SORT_TIERS if n <= t)
ms = max_blocks(tier, block_m, ne) * block_m
dev = topk_ids.device
ids = torch.empty(ms, dtype=torch.int32, device=dev)
wts = torch.empty(ms, dtype=torch.float32, device=dev)
eids = torch.empty(ms // block_m, dtype=torch.int32, device=dev)
nv = torch.empty(1, dtype=torch.int32, device=dev)
quant = x is not None
flat = topk_ids.contiguous().int().view(-1)
_run_compiled(compile_sort(block_m=block_m, max_tokens=tier, quant=quant, ne=ne), flat,
topk_weights.contiguous().float().view(-1), ids, wts, eids, nv, x.view(-1) if quant else flat,
xq.view(-1) if quant else flat, xs.view(-1) if quant else flat, n, torch.cuda.current_stream())
return ids, wts, eids, nv


def gemm1_relu2_quant(x_codes, x_scales, w, ids, eids, nv, *, bm, kw, pf, rows, ni=2, nbuf=0, nwv=4, hot=False):
"""Sorted rows' ReLU² MXFP8 intermediate in GEMM2's operand layout (``reference.unpack_rows`` gives
``[rows, 4096]`` e4m3 codes and ``[rows, 128]`` e8m0)."""
n = x_codes.shape[0]
q = torch.empty(rows * I, dtype=torch.uint8, device=x_codes.device)
s = torch.empty(rows * (I // 32), dtype=torch.uint8, device=x_codes.device)
ne = w.n_experts
exe = compile_gemm1(kw=kw, pf=pf, bm=bm, ni=ni, nbuf=nbuf, nwv=nwv, ne=ne, hot=hot)
_run_compiled(exe, x_codes.view(torch.uint8).view(-1),
x_scales.view(torch.uint8).view(-1), w.w1.view(-1), w.w1_scale.view(-1), q, s,
ids, eids, nv, n, rows, max_blocks(n, bm, ne), torch.cuda.current_stream())
return q, s


def gemm2_slots(q, s, w, ids, wts, eids, nv, n_tokens, *, bm, tn, pf, nbuf=0, hot=False, nwv=4):
"""Unnormalized bf16 slots ``[n_tokens, 8, 8192]``."""
out = torch.zeros((n_tokens, TOPK, H), dtype=torch.bfloat16, device=q.device)
ne = w.n_experts
exe = compile_gemm2(tn=tn, bm=bm, pf=pf, nbuf=nbuf, hot=hot, nwv=nwv, ne=ne)
_run_compiled(exe, q, s, w.w2.view(-1), w.w2_scale.view(-1),
out.view(-1), ids, wts, eids, nv, n_tokens, q.numel() // I, max_blocks(n_tokens, bm, ne),
torch.cuda.current_stream())
return out


def combine_slots(slots, topk_ids, topk_weights, norm_scale, eps, ne=E):
"""The normalizing, route-weighted slot sum of ``slots`` ``[n, 8, 8192]`` (``reference.experts_reference``), with
the reduction tree of the fused launch for ``n`` tokens."""
out = torch.empty((slots.shape[0], H), dtype=torch.bfloat16, device=slots.device)
threads = 64 * config_for(slots.shape[0])[9]
_run_compiled(compile_combine(ne=ne, threads=threads), topk_ids.contiguous().int().view(-1),
topk_weights.contiguous().float().view(-1), norm_scale.contiguous().float().view(-1),
slots.view(-1), out.view(-1), slots.shape[0], _eps_bits(eps), torch.cuda.current_stream())
return out


_arenas: dict = {}


def ready_counters(device):
"""The device's counters of the fused launch (``kernel.compile_experts``): zero between calls, one per process;
two calls must not run concurrently on one device."""
arena = _arenas.get(device)
if arena is None:
if torch.cuda.is_current_stream_capturing():
raise RuntimeError("the first call on a device allocates the ready counters: run it before graph capture")
arena = _arenas[device] = torch.zeros((max_blocks(MAX_TOKENS, 16, NE_MAX) + 1) * READY_STRIDE // 4,
dtype=torch.int32, device=device)
return arena


def mxfp4_experts(x, x_scales, w: ExpertWeights, topk_weights, topk_ids, norm_scale, eps, *, return_slots=False,
out=None):
"""The 8 routed experts of each token, normalized per expert and route-weighted. ``x``: MXFP8 e4m3 ``[n, 8192]``
with its e8m0 ``x_scales`` ``[n, 256]``, or bf16 ``[n, 8192]`` with ``x_scales`` None (quantized in the sort
launch); ``topk_ids`` ``[n, 8]`` local expert ids, an id outside [0, ne) (padding row, expert of another rank) is
not routed, ne = ``w.n_experts``; ``topk_weights`` FP32; ``norm_scale`` FP32 ``[ne, 8192]``. Returns bf16
``[n, 8192]`` (into ``out`` when given, contiguous), or with ``return_slots`` the unnormalized slots
``[n, 8, 8192]`` (zero where not routed)."""
n = x.shape[0]
ne = w.n_experts
assert x.shape[1] == H and topk_ids.shape == (n, TOPK) and 1 <= n <= MAX_TOKENS
assert norm_scale.shape == (ne, H) and norm_scale.dtype == torch.float32 and norm_scale.is_contiguous()
cfg = config_for(n)
bm, kw, pf1, ni, nb1, tn, pf2, nb2, hot, nwv, cw = cfg
xq, xs, quant = _activation(x, x_scales)
ids, wts, eids, nv = moe_sort(topk_ids, topk_weights, bm, *((x, xq, xs) if quant else ()), ne=ne)
if return_slots:
q, s = gemm1_relu2_quant(xq, xs, w, ids, eids, nv, bm=bm, kw=kw, pf=pf1, rows=ids.numel(), ni=ni, nbuf=nb1,
nwv=nwv, hot=bool(hot & 2))
return gemm2_slots(q, s, w, ids, wts, eids, nv, n, bm=bm, tn=tn, pf=pf2, nbuf=nb2, hot=bool(hot & 1),
nwv=nwv)
rows = ids.numel()
dev = x.device
q = torch.empty(rows * I, dtype=torch.uint8, device=dev)
s = torch.empty(rows * (I // 32), dtype=torch.uint8, device=dev)
slots = torch.empty(n * TOPK * H, dtype=torch.bfloat16, device=dev)
if out is None:
out = torch.empty((n, H), dtype=torch.bfloat16, device=dev)
assert out.shape == (n, H) and out.dtype == torch.bfloat16 and out.is_contiguous()
exe = compile_experts(bm=bm, kw=kw, pf1=pf1, ni=ni, nb1=nb1, tn2=tn, pf2=pf2, nb2=nb2, hot=bool(hot & 1),
nwv=nwv, cw=cw, ne=ne, hot1=bool(hot & 2))
_run_compiled(exe, xq.view(-1), xs.view(-1), w.w1.view(-1), w.w1_scale.view(-1), q, s, w.w2.view(-1),
w.w2_scale.view(-1), slots, out.view(-1), topk_ids.contiguous().int().view(-1),
topk_weights.contiguous().float().view(-1), norm_scale.view(-1), ids, wts, eids, nv,
ready_counters(dev), n, rows, max_blocks(n, bm, ne), _eps_bits(eps), torch.cuda.current_stream())
return out


def _mode(x, x_scales, *args, **kwargs):
"""What a call fixes about its kernels besides the row count (``amd_kernels.warm_up``): bf16 or MXFP8 rows,
slots or the combined rows, the local expert count."""
return x.dtype == torch.bfloat16, bool(kwargs.get("return_slots", False)), args[0].n_experts


def _inputs(mode, n, x, x_scales, w, topk_weights, topk_ids, norm_scale, eps, **kwargs):
dev = x.device
xn = torch.zeros((n, H), dtype=x.dtype, device=dev)
sn = None if x_scales is None else torch.zeros((n, H // 32), dtype=x_scales.dtype, device=dev)
return (xn, sn, w, torch.ones((n, TOPK), device=dev), torch.zeros((n, TOPK), dtype=torch.int32, device=dev),
norm_scale, eps), {k: v for k, v in kwargs.items() if k != "out"} # ``out`` holds the caller's row count


mxfp4_experts = entry("moe/mxfp4_relu2_norm_h8192_i4096_e32_top8", mode=_mode, sizes=lambda mode: WARM_UP_TOKENS,
inputs=_inputs)(mxfp4_experts)
Loading