Skip to content

[ROCm][Perf][DSv4.1] Run aiter_mega_moe layers on AITER FusedEPMoE for small batches - #68998

Draft
Fangzhou-Ai wants to merge 2 commits into
vllm-project:mainfrom
Fangzhou-Ai:fai/dsv41f-fused-ep8-moe-callsite
Draft

Fangzhou-Ai wants to merge 2 commits into
vllm-project:mainfrom
Fangzhou-Ai:fai/dsv41f-fused-ep8-moe-callsite

Conversation

@Fangzhou-Ai

@Fangzhou-Ai Fangzhou-Ai commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Overview

Adds an opt-in call site for AITER's FusedEPMoE (ROCm/aiter#8368, dependency, not merged yet) to DeepseekV4AiterMegaMoEExperts (--moe-backend aiter_mega_moe). For DeepSeek-V4.1-Flash, a whole routed-expert layer (MXFP8 quant, dispatch, GEMM1 + clamp-SwiGLU + requant, GEMM2, combine) then runs as one persistent launch per rank for decode-sized batches; everything else stays on MegaMoEV2.

Claims

  • VLLM_ROCM_USE_AITER_FUSED_EP_MOE=1 (default off) runs a layer on FusedEPMoE when the DP-group max tokens per rank is at most 768, and on MegaMoEV2 otherwise. Every EP rank decides from the same DP max, also under CUDA graph capture.
  • Measured through this call site on 8x MI355X (DeepSeek-V4.1-Flash EP8 layer, uniform routing, CUDA-graph replay): 1.27x-1.84x faster than the MegaMoEV2 path main takes at 1-768 tokens per rank; same path and time at 1024.
  • While FusedEPMoE runs, nothing else is scheduled beside it by this model: the unfused shared expert runs after it, and in FULL CUDA graphs the V4.1 decoder keeps the FFN seam's mHC gate projection on the main stream (the attention seam still overlaps).
  • Without the AITER op, with the flag off, or for any other shape (V4-Pro, fused shared expert / top 7, the DSpark draft's 128-expert top-3 layers, more than 63 experts per rank, not gfx950 with 256 CUs), behaviour is unchanged.
  • End-to-end DSv4.1-Flash DEP8 (AgentX) results are pending; this stays a draft until they are in.

Validation

All runs on 8x MI355X (gfx950, 256 CUs), FlyDSL 0.5.0, AITER = ROCm/aiter main 9569fb31a + ROCm/aiter#8368 @ 54a95a7d2, MoRI from the ROCm vLLM image. The vLLM tree is this branch at 6748ef8; its Python sources were run on top of the compiled extensions of an installed ROCm vLLM build (0.34.0rc1.dev897), since only Python files change here. vLLM upstream main has not touched these files since the branch point, and ROCm/aiter main has no MegaMoEV2 change since 9569fb31a, so the baseline is current.

Tests

  • tests/models/test_deepseek_v4_aiter_mega_moe.py (existing file, (MI355) DeepSeek V4 MoE Integration step):
    • ROCm, 2 GPUs (multi_gpu_test(num_gpus=2), skipped when the op is missing): real vLLM DP=2 / EP parallel state with the MoRI all2all (parallel_launch_with_config), two real DeepseekV4AiterMegaMoEExperts layers on the same checkpoint-layout weights, one with the flag. Each step runs inside set_forward_context with the per-rank token counts [1, 1], [37, 300], [0, 37] (a rank with no tokens), [768, 1] and [769, 1]: up to 768 the flag layer matches the MegaMoEV2 layer (cosine > 0.999), at 769 both take the same MegaMoEV2 runtime and match bitwise. CUDA-graph replay with new inputs is bitwise equal to eager at 1 / 37 / 300 tokens.
    • ROCm, 1 GPU: the existing routing test also checks that the unfused shared expert leaves the aux stream when FusedEPMoE is selected.
  • tests/kernels/mhc/test_mhc_kernels.py::test_deepseek_v41_rocm_decoder_overlap_matches_serial ((MI355) mHC Kernels step): new fused_ep_moe case, where the FFN seam must not split onto the aux stream inside a FULL graph capture and the replayed layer still matches the serial one. It fails without the model change (assert [True] == [], 8 failed) and passes with it.
# ROCm/aiter#8368 + FlyDSL 0.5.0 on PYTHONPATH
pytest -v tests/models/test_deepseek_v4_aiter_mega_moe.py
======================= 21 passed, 17 warnings in 56.84s =======================
46.69s call     tests/models/test_deepseek_v4_aiter_mega_moe.py::test_fused_ep_moe_matches_mega_moe

# installed AITER 0.1.29 (no fused_ep_moe)
pytest -v tests/models/test_deepseek_v4_aiter_mega_moe.py
SKIPPED [1] tests/utils.py:2015: AITER FusedEPMoE is unavailable on this AITER or GPU
================= 20 passed, 1 skipped, 17 warnings in 20.10s ==================

pytest tests/kernels/mhc/test_mhc_kernels.py -k "rocm_decoder_overlap_matches_serial or rocm_mhc_overlap or rocm_mega_mhc_loads"
45 passed, 391 deselected, 19 warnings in 29.70s
# same, model change reverted, -k "rocm_decoder_overlap_matches_serial and at_limit and True"
E       assert [True] == []
8 failed, 428 deselected, 19 warnings in 9.27s

Why the 0.999 bound: both paths quantize the input and the activation to MXFP8, but they do not round identically. Against the fp32 dequant reference of ROCm/aiter#8368's test (2 ranks, random inputs of the test's shapes), FusedEPMoE reached cosine 0.999996-0.9999995 and MegaMoEV2 0.99963-0.99965 at 1 / 37 / 300 tokens per rank, so the two paths agree to ~0.99964 with each other. A wrong weight layout or expert numbering gives a cosine near 0.

Call-site timing (DeepseekV4AiterMegaMoEExperts.forward with the flag off / on; real vLLM DP + EP parallel state, one process per GPU; MegaMoEV2 built as vLLM builds it with max_num_batched_tokens=8192: a 128-token fixed-slot runtime plus an 8192 compact one, i.e. the staged route; uniform routing, top 6, 48 experts per rank, bf16 tokens; 20 distinct calls captured in one CUDA graph inside a forward context carrying the per-rank counts; us per call = max over ranks, best of 5 replays x 2 in A B B A order. Script and commands below.)

EP8 (384 experts, DeepSeek-V4.1-Flash):

tokens/rank flag off: path, us flag on: path, us off / on
1 MegaMoEV2 84.7 FusedEPMoE 46.1 1.84x
16 MegaMoEV2 194.2 FusedEPMoE 144.6 1.34x
64 MegaMoEV2 224.5 FusedEPMoE 166.7 1.35x
128 MegaMoEV2 226.8 FusedEPMoE 178.7 1.27x
256 MegaMoEV2 355.8 FusedEPMoE 198.7 1.79x
512 MegaMoEV2 436.3 FusedEPMoE 301.9 1.45x
768 MegaMoEV2 508.3 FusedEPMoE 364.3 1.40x
1024 MegaMoEV2 583.5 MegaMoEV2 583.3 1.00x (same path)

EP8 with uneven per-rank counts (the eager DP case; each rank captures its own size). FusedEPMoE gets rows_hint = DP max, so its tiles are sized as in a graph padded to the busiest rank; the last column calls the op without it (tiles sized from the local count):

tokens per rank flag off flag on (rows_hint = DP max) flag on, no rows_hint
37, 0, 5, 300, 1, 0, 64, 128 MegaMoEV2 348.9 189.6 (1.84x) 202.9 (1.72x)
512, 1, 1, 1, 1, 1, 1, 1 MegaMoEV2 372.7 269.9 (1.38x) 256.1 (1.46x)
0, 0, 0, 0, 0, 0, 0, 1 MegaMoEV2 71.7 30.6 (2.34x) 31.2 (2.30x)

The hint is a wash (+7 % / -5 % / +2 %); it is kept because it makes eager and graph steps of the same DP max pick the same tiles. Outputs are correct either way (covered by the [37, 300] / [0, 37] / [768, 1] test cases).

EP2 / EP4 (48 experts per rank; FusedEPMoE accepts 2/4/8 ranks with at most 63 experts per rank, so DeepSeek-V4.1-Flash's 384 experts only qualify on EP8; uniform routing only):

tokens/rank EP2 off / on, us EP2 off / on EP4 off / on, us EP4 off / on
1 110.8 / 38.7 2.86x 126.8 / 43.8 2.89x
64 255.6 / 163.0 1.57x 269.8 / 161.8 1.67x
256 392.6 / 276.1 1.42x 351.9 / 218.8 1.61x
512 539.7 / 488.2 1.11x 462.7 / 366.7 1.26x
768 730.0 / 673.9 1.08x 574.5 / 469.4 1.22x
1024 898.9 / 898.0 (same path) 1.00x 671.8 / 672.2 (same path) 1.00x
Call-site benchmark script and commands

Run from the vLLM source root with ROCm/aiter#8368 and FlyDSL 0.5.0 importable:

python bench_callsite.py --world-size 8 --tokens 1 16 64 128 256 512 768 1024 \
    --uneven 37,0,5,300,1,0,64,128 512,1,1,1,1,1,1,1 0,0,0,0,0,0,0,1
python bench_callsite.py --world-size 2 --tokens 1 64 256 512 768 1024
python bench_callsite.py --world-size 4 --tokens 1 64 256 512 768 1024
# SPDX-License-Identifier: Apache-2.0
"""Call-site timing of DeepseekV4AiterMegaMoEExperts.forward with
VLLM_ROCM_USE_AITER_FUSED_EP_MOE off / on (DeepSeek-V4.1-Flash layer shape:
hidden 5120, intermediate 2304, top 6, 48 experts per rank)."""

import argparse
import os

import torch

from tests.kernels.moe.modular_kernel_tools.parallel_utils import (
    parallel_launch_with_config,
)
from vllm.config import ParallelConfig, SchedulerConfig, VllmConfig
from vllm.forward_context import set_forward_context
from vllm.models.deepseek_v4.amd.mega_moe import DeepseekV4AiterMegaMoEExperts

NCALL, REPS = 20, 5
HIDDEN, INTER, TOPK, EPR = 5120, 2304, 6, 48


def worker(pgi, vllm_config, cpu_group, cases):
    rank, ws = pgi.rank, pgi.world_size
    num_experts = EPR * ws
    g = torch.Generator(device=pgi.device).manual_seed(rank)
    layers = {}
    for fused in (False, True):
        os.environ["VLLM_ROCM_USE_AITER_FUSED_EP_MOE"] = str(int(fused))
        ex = DeepseekV4AiterMegaMoEExperts(
            vllm_config,
            num_experts=num_experts,
            top_k=TOPK,
            hidden_size=HIDDEN,
            intermediate_size=INTER,
            swiglu_limit=10.0,
        )
        for p in (ex.w13_weight, ex.w2_weight):
            p.data.random_(0, 256, generator=g)
        for p in (ex.w13_weight_scale, ex.w2_weight_scale):
            p.data.random_(118, 124, generator=g)
        ex.finalize_weights()
        layers[fused] = ex
    fused_layer = layers[True]

    def no_hint(x, w, ids):
        return fused_layer._fused_ep_moe(
            x, None, fused_layer._fused_ep_moe_weights, w, ids
        )

    variants = {"off": layers[False], "on": layers[True], "on, no rows_hint": no_hint}
    for counts in cases:
        m = counts[rank]
        dp_max = max(counts)
        xs = [torch.randn((m, HIDDEN), generator=g).bfloat16() for _ in range(NCALL)]
        ids = [
            torch.rand((m, num_experts), generator=g).topk(TOPK).indices.int()
            for _ in range(NCALL)
        ]
        tws = [
            torch.softmax(torch.randn((m, TOPK), generator=g), -1) for _ in range(NCALL)
        ]
        names = ["off", "on", "on", "off"]
        if len(set(counts)) > 1 and fused_layer.uses_fused_ep_moe(dp_max):
            names += ["on, no rows_hint", "on, no rows_hint"]
        res = {}
        ctx = dict(
            num_tokens=m,
            num_tokens_across_dp=torch.tensor(counts, dtype=torch.int32, device="cpu"),
        )
        for name in names:
            fn = variants[name]
            with set_forward_context(None, vllm_config, **ctx):
                path = (
                    "FusedEPMoE"
                    if name == "on, no rows_hint" or fn.uses_fused_ep_moe(dp_max)
                    else "MegaMoEV2"
                )
                for i in range(NCALL):
                    fn(xs[i], tws[i], ids[i])
                torch.accelerator.synchronize()
                torch.distributed.barrier(cpu_group)
                graph = torch.cuda.CUDAGraph()
                with torch.cuda.graph(graph):
                    for i in range(NCALL):
                        fn(xs[i], tws[i], ids[i])
            torch.accelerator.synchronize()
            torch.distributed.barrier(cpu_group)
            best = 1e30
            for _ in range(REPS):
                torch.distributed.barrier(cpu_group)
                s = torch.cuda.Event(enable_timing=True)
                e = torch.cuda.Event(enable_timing=True)
                s.record()
                graph.replay()
                e.record()
                torch.accelerator.synchronize()
                t = torch.tensor([s.elapsed_time(e) * 1000 / NCALL], device="cpu")
                torch.distributed.all_reduce(
                    t, op=torch.distributed.ReduceOp.MAX, group=cpu_group
                )
                best = min(best, t.item())
            prev = res.get(name, (path, 1e30))
            res[name] = (path, min(best, prev[1]))
            del graph
        if rank == 0:
            row = " | ".join(f"{k}: {p} {t:.1f}" for k, (p, t) in res.items())
            print(f"RESULT ws={ws} tokens={counts} | {row}", flush=True)
    torch.distributed.barrier(cpu_group)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--world-size", type=int, default=8)
    ap.add_argument("--tokens", type=int, nargs="*", default=[])
    ap.add_argument("--uneven", nargs="*", default=[])
    args = ap.parse_args()
    ws = args.world_size
    cases = [[t] * ws for t in args.tokens]
    cases += [[int(v) for v in u.split(",")] for u in args.uneven]
    assert all(len(c) == ws for c in cases)
    vllm_config = VllmConfig(
        parallel_config=ParallelConfig(
            data_parallel_size=ws, enable_expert_parallel=True, all2all_backend="mori"
        ),
        # As served: MegaMoEV2 gets a 128-token fixed-slot runtime and an 8192 one.
        scheduler_config=SchedulerConfig.default_factory(max_num_batched_tokens=8192),
    )
    env = {"VLLM_ROCM_USE_AITER": "1", "MORI_SHMEM_HEAP_SIZE": "8G"}
    parallel_launch_with_config(ws, worker, vllm_config, env, cases)


if __name__ == "__main__":
    main()

Raw output (EP8 run):

RESULT ws=8 tokens=[1, 1, 1, 1, 1, 1, 1, 1] | off: MegaMoEV2 84.7 | on: FusedEPMoE 46.1
RESULT ws=8 tokens=[16, 16, 16, 16, 16, 16, 16, 16] | off: MegaMoEV2 194.2 | on: FusedEPMoE 144.6
RESULT ws=8 tokens=[64, 64, 64, 64, 64, 64, 64, 64] | off: MegaMoEV2 224.5 | on: FusedEPMoE 166.7
RESULT ws=8 tokens=[128, 128, 128, 128, 128, 128, 128, 128] | off: MegaMoEV2 226.8 | on: FusedEPMoE 178.7
RESULT ws=8 tokens=[256, 256, 256, 256, 256, 256, 256, 256] | off: MegaMoEV2 355.8 | on: FusedEPMoE 198.7
RESULT ws=8 tokens=[512, 512, 512, 512, 512, 512, 512, 512] | off: MegaMoEV2 436.3 | on: FusedEPMoE 301.9
RESULT ws=8 tokens=[768, 768, 768, 768, 768, 768, 768, 768] | off: MegaMoEV2 508.3 | on: FusedEPMoE 364.3
RESULT ws=8 tokens=[1024, 1024, 1024, 1024, 1024, 1024, 1024, 1024] | off: MegaMoEV2 583.5 | on: MegaMoEV2 583.3
RESULT ws=8 tokens=[37, 0, 5, 300, 1, 0, 64, 128] | off: MegaMoEV2 348.9 | on: FusedEPMoE 189.6 | on, no rows_hint: FusedEPMoE 202.9
RESULT ws=8 tokens=[512, 1, 1, 1, 1, 1, 1, 1] | off: MegaMoEV2 372.7 | on: FusedEPMoE 269.9 | on, no rows_hint: FusedEPMoE 256.1
RESULT ws=8 tokens=[0, 0, 0, 0, 0, 0, 0, 1] | off: MegaMoEV2 71.7 | on: FusedEPMoE 30.6 | on, no rows_hint: FusedEPMoE 31.2

These match the kernel-level numbers in ROCm/aiter#8368 (same machine, op_tests/multigpu_tests/bench_fused_ep_moe.py, us per call, max over ranks; "main" = MegaMoEV2 staged route as built above):

tokens/rank uniform main uniform #8368 zipf main zipf #8368 hot main hot #8368
1 87.8 47.1 83.6 41.7 165.7 109.9
64 228.4 167.8 261.1 168.6 474.0 238.1
256 362.6 199.7 534.3 355.1 935.4 736.1
512 437.0 299.6 682.8 602.4 1510.7 1241.2
768 514.9 363.9 887.6 874.1 2155.2 1843.5
1024 581.3 489.9 1095.5 1154.3 2810.4 2442.3

(zipf: Zipf 1.2 expert popularity; hot: every route to rank 0's experts.) At 1024 the kernel is 5 % slower than main under Zipf routing, hence the 768 cutoff. Per ROCm/aiter#8368's roofline analysis, up to ~192 tokens per rank the kernel streams the expert weights at 87-97 % of the measured HBM ceiling in its GEMM loops, and from ~384 it is bound by the GEMM2 return stores over xGMI.

End-to-end: DeepSeek-V4.1-Flash DEP8 AgentX results are pending.

Details

AI assistance (Claude Code) was used to write this change; Fangzhou Ai is the human owner and will review/defend it end-to-end.


Pull Request Checklist
  • I used vLLM's /pr-checklist skill. (Mandatory for agents, optional for humans).

  • AI assistance was used during the creation of this PR.

  • Design Fit: Minimizes impact on core components, reuses existing functionality, and justifies added complexity.

  • Testing and Validation: Validates the change and ensures any added tests are meaningful and reliable, with CI coverage or documented CI resource constraints and validation performed outside CI.

  • Code Quality and Style: Keeps code and comments clear and concise, and updates relevant documentation and examples.

  • Pull Request Contents: Includes a brief summary and relevant links, supports claims with evidence, explains root causes and implementation trade-offs, and follows the contributing guide. (End-to-end serving results pending.)

🤖 Generated with Claude Code

…r small batches

With --moe-backend aiter_mega_moe and VLLM_ROCM_USE_AITER_FUSED_EP_MOE=1,
DeepseekV4AiterMegaMoEExperts runs a layer that AITER's FusedEPMoE
supports (DeepSeek-V4.1-Flash: hidden 5120, intermediate 2304, top 6,
2/4/8 EP ranks, no fused shared expert, gfx950 with 256 CUs) as one
persistent launch per rank when the DP-group max tokens per rank is at
most 768 (512 when MegaMoEV2 has its large-input route), and on
MegaMoEV2 otherwise. The decision comes from the DP-group max, so every
EP rank takes the same collective path, also under CUDA graph capture.

FusedEPMoE reads the shuffled MXFP4 tensors MegaMoEV2 is built with (no
copy). One instance serves every layer; it is created and prepared
(compiles all tile tiers) once in finalize_weights, before graph
capture. The unfused shared expert runs serially while FusedEPMoE is
selected, since the kernel must not share the GPU.

The op comes from ROCm/aiter#8368 and is imported lazily; without it
(or for other shapes) every layer keeps MegaMoEV2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Fangzhou Ai <fangzhou.ai@amd.com>
@mergify mergify Bot added deepseek Related to DeepSeek models rocm Related to AMD ROCm labels Nov 20, 2026
@github-project-automation github-project-automation Bot moved this to Todo in AMD Nov 20, 2026
- V4.1 decoder: keep the FFN seam's mHC gates off the aux stream when the
  MoE runs FusedEPMoE, so nothing runs beside its persistent workgroups
  (FULL graphs, <= 128 tokens). The attention seam still overlaps.
- Decide the DP-group max once per layer in DeepseekV4MoE and pass it
  to the experts; pass it to FusedEPMoE as rows_hint, so eager steps
  with uneven DP batches size the tiles as a padded graph would.
- Drop the 512-token cutoff tied to MegaMoEV2's unmerged large-input
  route; catch any import failure of the AITER op and fall back.
- Tests: drop the CPU tests built on a fake AITER module; the 2-GPU test
  now runs under real DP/EP parallel state and forward contexts with
  uneven per-rank counts (one rank with no tokens) and the 768 / 769
  cutoff; the ROCm decoder overlap test covers the FusedEPMoE case.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Fangzhou Ai <fangzhou.ai@amd.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek Related to DeepSeek models rocm Related to AMD ROCm

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

1 participant