# Fused expert-parallel MoE layer (`mega_moe`) | ServingStudio Kernel Library

One kernel per GPU that dispatches tokens to expert GPUs, runs both expert GEMMs and the shared expert, and combines the results.

DeepGEMM's mega MoE runs a whole expert-parallel MoE layer as one persistent kernel on each GPU. Every GPU writes its tokens and their top-k expert slots into a symmetric buffer; the kernel pulls the rows routed to its local slots from every GPU over NVLink, runs the gate/up GEMM, a clamped SwiGLU and the down GEMM, sends each result row back to its source GPU and sums the top-k rows there. The shared expert runs on the GPU's own tokens inside the same launch. Activations are MXFP8, routed weights MXFP4, the output bf16. The rows each slot receives are an input, drawn from the deployment's routing and expert placement, so a skewed router or an unbalanced placement loads the busiest GPU as it does in serving.

Category: MoE; group: Expert compute. Interactive page: https://servingstudio.cs.washington.edu/kernels.html?kind=mega_moe. All kernel kinds: https://servingstudio.cs.washington.edu/kernels.md.

## Formula

- `routed rows of GPU r = sum(per_slot_rows[r·L:(r+1)·L]), L = num_experts / ep_size`
- `FLOPs per GPU = 6 · hidden_size · intermediate_size · (routed rows + num_tokens · num_shared_experts)`
- `bytes per GPU = touched local expert weights + shared weights + routed activations (fp8 in, fp8 intermediate, bf16 out) + bf16 output`

## How it is measured

GPU kernel time from CUPTI activity records, averaged over repeated launches in one capture. The L2 cache is flushed before each launch, so the numbers are cold-cache times. All GPUs launch together: each launch follows a GPU sleep and a one-element NCCL all-reduce, so no GPU waits on another's late launch. The time is the median over launches of the slowest GPU's kernel time in that launch.

## Caveats

- Which source GPU a routed row comes from is not an input: the runner spreads each slot's rows over the source GPUs round-robin.
- Every GPU runs the same token count; unequal per-GPU counts are not measured.
- Energy is the mean per-GPU energy of back-to-back launches.

## Arguments

| Argument | Type | Unit | Meaning |
| --- | --- | --- | --- |
| `ep_size` | number | GPUs | GPUs in the expert-parallel group; 1 runs every expert on one GPU (no NVLink traffic). |
| `num_tokens` | number | tokens | Tokens entering the MoE layer on each GPU (every GPU has the same count). |
| `hidden_size` | number | elements | Width of each token's hidden state. |
| `intermediate_size` | number | elements | Width of each routed expert's intermediate state. |
| `num_experts` | number | experts | Physical routed expert slots across all GPUs, redundant (EPLB) slots included; each GPU holds num_experts / ep_size of them. |
| `num_shared_experts` | number | experts | Shared experts fused into the same launch, run on every token. |
| `top_k` | number | experts | Distinct expert slots selected for each token. |
| `activation_dtype` | dtype |  | Tensor-core precision of the activations: mxfp8_e4m3 (one UE8M0 scale per 32). |
| `weight_dtype` | dtype |  | Routed expert weight format: mxfp4_e2m1 (one UE8M0 scale per 32). The shared expert's weights are mxfp8_e4m3. |
| `per_slot_rows` | list | rows | Rows each physical slot receives over the whole group, rank-major (num_experts entries summing to ep_size * num_tokens * top_k). |

## Metrics

- Time (`time_ms`, ms)
- Throughput (`tflops`, TFLOPS)
- Memory bandwidth (`memory_bandwidth_gbps`, GB/s)
- Energy (`energy_j`, J)

## Backends

- `deepgemm_sm100`: DeepGEMM fp8_fp4_mega_moe as DeepInfer calls it: shared expert fused, SwiGLU clamp 10, fast math, MXFP8 x MXFP4 MMA. dtypes `mxfp4_e2m1`, SM targets `sm_100f`, GPUs B200-SXM-180GB, B300-SXM-288GB, GB200-Superchip. Source: https://github.com/deepseek-ai/DeepGEMM/blob/main/deep_gemm/mega/__init__.py

## Measured rows

11,336 rows in all.

| GPU | Backend | Precision | Rows |
| --- | --- | --- | --- |
| NVIDIA B200 | `deepgemm_sm100` | `mxfp4_e2m1` | 11,336 |

## Used by these deployments

- [DeepSeek V4.1 Flash 1017: vLLM or DeepInfer, DP attention, EP MoE](https://servingstudio.cs.washington.edu/models/DeepSeek-V4.1-Flash-1017/deepseek_v41_vllm_dp_attn_ep_moe.md) (`DeepSeek-V4.1-Flash-1017/deepseek_v41_vllm_dp_attn_ep_moe`)
- [DeepSeek V4.1 Flash 1017: vLLM, DP attention, EP MoE, DSpark speculative decoding](https://servingstudio.cs.washington.edu/models/DeepSeek-V4.1-Flash-1017/deepseek_v41_vllm_dp_attn_ep_moe_dspark.md) (`DeepSeek-V4.1-Flash-1017/deepseek_v41_vllm_dp_attn_ep_moe_dspark`)

## API

- This kind: https://servingstudio.cs.washington.edu/api/public/v1/kernels/mega_moe
- Measured rows: https://servingstudio.cs.washington.edu/api/public/v1/kernels/mega_moe/rows (filter by any column, such as `?gpu=NVIDIA%20H200`; `format=csv` for CSV)
- Configs the public deployments ask of it: https://servingstudio.cs.washington.edu/api/public/v1/kernels/mega_moe/configs

## Torch reference

What the kind computes, as Torch code (`profiling/runners/moe/mega_moe_reference.py` in ServingStudio Sim):

```python
"""Torch reference for the fused expert-parallel MoE layer (``mega_moe``).

Independent of DeepGEMM: it takes dequantized FP32 tensors in checkpoint order
(``[gate; up]`` gate/up rows, no interleave) and computes, for every token,

    y = sum_k w_k · down_e( q8( clamped_swiglu(gate_up_e(x)) · w_k ) )
        + sum_s down_s( q8( clamped_swiglu(gate_up_s(x)) ) )

where ``q8`` is the MXFP8 round trip the kernel applies to the down GEMM's
input and the shared experts take weight 1. ``expert_partial`` evaluates only
the slots one rank owns, so the EP layer is the sum of every rank's partial
over all tokens; the runner all-reduces those partials.
"""

from __future__ import annotations

from typing import Any

from profiling.runners.moe.mxfp4_fused_moe_reference import (
    clamped_swiglu,
    quantize_dequantize_mxfp8,
)


def _expert(torch: Any, x: Any, gate_up: Any, down: Any, limit: float, scale: Any) -> Any:
    gate, up = (x @ gate_up.T).chunk(2, dim=-1)
    act = clamped_swiglu(torch, gate, up, limit) * scale
    return quantize_dequantize_mxfp8(torch, act) @ down.T


def expert_partial(
    torch: Any,
    x: Any,
    topk_idx: Any,
    topk_weights: Any,
    gate_up: Any,
    down: Any,
    first_slot: int,
    limit: float,
) -> Any:
    """Contribution of slots ``[first_slot, first_slot + len(gate_up))`` to every token.

    ``x`` [T, H] fp32, ``topk_idx`` [T, K] global slot ids, ``topk_weights``
    [T, K], ``gate_up`` [E_local, 2I, H], ``down`` [E_local, H, I].
    """

    out = torch.zeros_like(x)
    for local in range(gate_up.shape[0]):
        token, choice = (topk_idx == first_slot + local).nonzero(as_tuple=True)
        if token.numel() == 0:
            continue
        scale = topk_weights[token, choice].unsqueeze(-1)
        out.index_add_(
            0, token, _expert(torch, x[token], gate_up[local], down[local], limit, scale)
        )
    return out


def shared_experts(torch: Any, x: Any, gate_up: Any, down: Any, limit: float) -> Any:
    """Shared experts packed along the intermediate axis, as the kernel takes them:
    ``gate_up`` [2·S·I, H] (``[gate; up]``), ``down`` [H, S·I]."""

    return _expert(torch, x, gate_up, down, limit, 1.0)
```

---

This page as Markdown: https://servingstudio.cs.washington.edu/kernels/mega_moe.md. A guide to the whole site for AI agents: [llms.txt](https://servingstudio.cs.washington.edu/llms.txt).
