Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
4b612cc
perf(moe_ep): SM90 Hopper FP8 MegaMoE CGA, ping-pong scheduling, and …
inocsin Aug 23, 2026
687e85c
bench(moe_ep): align SM90 mega benchmark with the drop harness and ar…
inocsin Aug 23, 2026
1ad1a30
feat(moe_ep): SM90 FP8 mega tuning stack (knob cache + autotune) and …
inocsin Aug 24, 2026
fe6ddc6
chore(moe_ep): refresh SM90 pull-style vendored sweep harness
inocsin Aug 24, 2026
4fe4392
feat(moe_ep): SM90 pull mega top-k dedup (dispatch + combine) and qua…
inocsin Aug 29, 2026
9cf13ef
feat(moe_ep): SM90 pull mega active_dispatch_warps knob (default 1)
inocsin Aug 31, 2026
685393d
docs(moe_ep): refresh SM90 pull mega TUNING.md sweep numbers
inocsin Aug 31, 2026
259dd24
feat(moe_ep): SM90 pull mega empty-warp FC1 store offload + early pub…
inocsin Sep 2, 2026
1e41349
feat(moe_ep): SM90 pull mega fold producer warps into dispatch WG; re…
inocsin Sep 3, 2026
b1b6b39
Merge remote-tracking branch 'origin/main' into sm90_megamoe_optimiza…
inocsin Sep 3, 2026
2915cd6
feat(moe_ep): SM90 pull mega swap-AB token tile N=8 and heuristic rows
inocsin Sep 10, 2026
3ddfc5b
feat(moe_ep): SM90 pull mega generate_c training-forward output
inocsin Sep 12, 2026
bcd84b8
perf(moe_ep): SM90 pull mega 16-byte generate_c stores + compact disp…
inocsin Sep 12, 2026
b66f879
Sync Hopper FP8 generate_c sweep comparisons and N=8 validation
inocsin Sep 12, 2026
0c8522d
Sync Hopper FP8 register allocation and blockwise FC2 overlap
inocsin Sep 13, 2026
242012b
Address Hopper MoE review feedback and fix FC2 completion ordering
inocsin Sep 16, 2026
f605c14
fix(moe_ep): SM90 pull mega grouped combine SMEM slot per pull warp
inocsin Sep 16, 2026
27bf240
chore(moe_ep): fix pre-commit for the SM90 pull mega tree
inocsin Sep 16, 2026
2b8daed
fix(moe_ep): address SM90 pull mega review feedback
inocsin Sep 16, 2026
2ae8fc6
test(moe_ep): run SM90 pull tuner tests in their own interpreter
inocsin Sep 16, 2026
c969e2c
Merge branch 'main' into sm90_megamoe_optimization
inocsin Sep 17, 2026
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
368 changes: 299 additions & 69 deletions benchmarks/bench_moe_ep_sm90_mega.py

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,41 @@ class Sm90PullFp8MegaKernelBackend(MegaKernelBackend):
def __init__(self, config: Sm90_Fp8_Fp8_Bf16_PullCutedsl_MegaMoeConfig) -> None:
super().__init__(config)
self._kernel_config: Sm90_Fp8_Fp8_Bf16_PullCutedsl_MegaMoeConfig = config
if config.knobs is not None:
if not (isinstance(config.knobs, dict) or config.knobs == "auto"):
raise ValueError(
"knobs must be None, a knob dict, or 'auto'; "
f"got {config.knobs!r}"
)
if any(
v is not None
for v in (
config.swap_ab,
config.pingpong,
config.mma_tiler_mnk,
config.cluster_shape_mnk,
)
):
raise ValueError(
"knobs= is mutually exclusive with the explicit geometry "
"fields (swap_ab / pingpong / mma_tiler_mnk / "
"cluster_shape_mnk)"
)
# knobs="auto": tune at the first compute() (weights + staged inputs
# exist there), then keep the winner for the session.
self._autotune_pending = config.knobs == "auto"
if self._autotune_pending:
import warnings

warnings.warn(
"knobs='auto' runs a COLLECTIVE compile+timing sweep at the "
"first forward β€” never use it inside a serving engine. Tune "
"offline instead (python -m flashinfer.moe_ep.tune); winners "
"persist in the knob cache and knobs=None then resolves them "
"with a pure lookup.",
UserWarning,
stacklevel=3,
)

@classmethod
def kernel_name(cls) -> str:
Expand Down Expand Up @@ -134,13 +169,21 @@ def _allocate_workspace(self, fleet_params: FleetParams) -> Any:
kind=k.kind,
fp8_scale_mode=k.fp8_scale_mode,
fp8_accum_mode=k.fp8_accum_mode,
knobs=k.knobs if isinstance(k.knobs, dict) else None,
swap_ab=k.swap_ab,
pingpong=k.pingpong,
mma_tiler_mnk=k.mma_tiler_mnk,
cluster_shape_mnk=k.cluster_shape_mnk,
load_balance_mode=k.load_balance_mode,
gate_up_clamp=_resolve_gate_up_clamp(k),
activation_clamp=k.activation_clamp,
in_kernel_fc2_reduce=k.in_kernel_fc2_reduce,
token_back_by_dispatch=k.token_back_by_dispatch,
token_back_mode=k.token_back_mode,
dedup_dispatch=k.dedup_dispatch,
grouped_token_back=k.grouped_token_back,
combine_format=k.combine_format,
active_dispatch_warps=k.active_dispatch_warps,
)

def validate_forward(
Expand Down Expand Up @@ -240,6 +283,11 @@ def compute(
if output is not None:
num_tokens = output.shape[0]
else:
if self._autotune_pending:
raise ValueError(
"compute(output=None) is incompatible with knobs='auto' "
"(the autotune sweep needs a caller output buffer)"
)
staged = staged_tokens(workspace.topk_idx)
if staged is None:
raise ValueError(
Expand All @@ -249,6 +297,26 @@ def compute(
num_tokens = staged

kcfg = self._kernel_config
if self._autotune_pending:
# COLLECTIVE: every EP rank reaches this first compute() together,
# so the candidate sweep stays in lockstep (see shim/autotune.py).
from ......kernel_src.sm90.pull_style_cutedsl_megakernel import (
autotune_hopper_fp8_mega_moe,
)

autotune_hopper_fp8_mega_moe(
output,
transformed_weights[0],
transformed_weights[1],
workspace,
num_tokens=num_tokens,
gate_up_clamp=_resolve_gate_up_clamp(kcfg),
activation_clamp=kcfg.activation_clamp,
)
# Cleared only on success: if the collective tune raises, a retried
# compute() re-attempts it (all ranks fail together, so lockstep
# holds).
self._autotune_pending = False
view = hopper_fp8_mega_moe(
output,
transformed_weights[0],
Expand All @@ -265,9 +333,15 @@ def compute(
return output if output is not None else view

def _workspace_pool_key(self, fleet_params: FleetParams) -> Any:
k = self._kernel_config
if k.knobs == "auto":
# Autotune retunes (and recompiles) the workspace's shared
# frontend at first compute; give each session its own buffer.
return None
import torch

k = self._kernel_config
from ......core.kernel.workspace_pool import knobs_pool_key

fp = fleet_params
return (
"sm90_fp8_fp8_bf16_pull_cutedsl",
Expand All @@ -284,9 +358,17 @@ def _workspace_pool_key(self, fleet_params: FleetParams) -> Any:
k.fp8_scale_mode,
k.fp8_accum_mode,
k.swap_ab,
k.pingpong,
k.mma_tiler_mnk,
k.cluster_shape_mnk,
k.load_balance_mode,
_resolve_gate_up_clamp(k),
k.in_kernel_fc2_reduce,
k.token_back_by_dispatch,
k.token_back_mode,
k.dedup_dispatch,
k.grouped_token_back,
k.combine_format,
k.active_dispatch_warps,
knobs_pool_key(k.knobs),
)
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ class Sm90_Fp8_Fp8_Bf16_PullCutedsl_MegaMoeConfig:
``MoEWeightPack`` and enable ``MegaConfig.preprocess_weights`` (default),
or pass kernel-ready transformed weights with ``preprocess_weights=False``.

PORT NOTE: no ``knobs`` field yet β€” the sm90 tree has no tuner/knob-cache
module (see the shim's PORT NOTE); geometry knobs (``swap_ab``,
``mma_tiler_mnk``) are explicit fields instead.
Launch tuning is resolved through the ``knobs`` field (knob cache /
heuristic table / explicit dict / ``"auto"`` autotune β€” see the field
comment below) or, mutually exclusively, through the explicit geometry
fields (``swap_ab`` / ``pingpong`` / ``mma_tiler_mnk`` /
``cluster_shape_mnk``).
"""

intermediate_size: int
Expand All @@ -45,19 +47,58 @@ class Sm90_Fp8_Fp8_Bf16_PullCutedsl_MegaMoeConfig:
kind: Literal["fp8_e4m3", "fp8_e5m2"] = "fp8_e4m3"
fp8_scale_mode: Literal["per_tensor", "blockwise"] = "per_tensor"
fp8_accum_mode: Literal["1xacc", "2xacc"] = "1xacc"
# Kernel geometry: swap_ab selects the swap-A/B specialization;
# mma_tiler_mnk=None uses the drop driver's default for the geometry
# ((64, 128, 128) native, (256, 32, 128) swap-AB).
swap_ab: bool = False
# Kernel tuning knobs (see kernel_src...pull_style_cutedsl_megakernel
# shim/tuner.py). None -> knob-cache lookup, else the drop's
# token-bucket heuristic table; a dict applies those knobs; "auto" runs
# the collective autotune sweep at the first compute (never inside a
# serving engine β€” tune offline with python -m flashinfer.moe_ep.tune).
# Mutually exclusive with the explicit geometry fields below.
knobs: dict | str | None = None
# Launch geometry / scheduling: leave ALL of swap_ab / pingpong /
# mma_tiler_mnk / cluster_shape_mnk as None to use the drop driver's
# token-bucket heuristics (keyed on fp8_scale_mode and max tokens per
# rank); setting any one switches to manual mode with the drop driver's
# defaults for the rest (swap_ab=False, pingpong=False, (64, 128, 128)
# native / (256, 32, 128) swap-AB / (128, 32, 128) swap-AB ping-pong,
# cluster (1, 1, 1)).
swap_ab: bool | None = None
pingpong: bool | None = None
mma_tiler_mnk: tuple[int, int, int] | None = None
cluster_shape_mnk: tuple[int, int, int] | None = None
# Scheduler token-tile assignment; "atomic_counter" is the drop's
# perf-run setting (run_perf_test.sh), "static" the kernel default.
load_balance_mode: Literal["static", "atomic_counter"] = "static"
gate_up_clamp: float | None = None
activation_clamp: float | None = None
fast_math: bool = True
in_kernel_fc2_reduce: bool = False
# Legacy alias: True maps to token_back_mode="reuse_dispatch_warps".
token_back_by_dispatch: bool = False
# Explicit token-back placement; overrides token_back_by_dispatch when set.
token_back_mode: (
Literal["epi_warps", "standalone_warps", "reuse_dispatch_warps"] | None
) = None
# Wire-level top-k dedup on dispatch: a token routed to several experts on
# the same remote rank crosses NVLink once; duplicate pool rows are
# re-materialized locally from the carrier row (bit-exact either way).
# COLLECTIVE: changes the route-word wire format, so it MUST match on
# every EP rank (like the geometry knobs).
dedup_dispatch: bool = False
# Combine dedup: fc2 rows of one (src_rank, src_token) group are
# pre-reduced in fp32 on the expert rank; one row per contributing rank
# crosses the wire. Requires token_back_mode="reuse_dispatch_warps";
# COLLECTIVE like dedup_dispatch.
grouped_token_back: bool = False
# Combine wire format: "bf16" (default) or per-32 e8m0 fp8
# ("32e4m3xe8m0" / "32e5m2xe8m0"; halved return bytes, receiver
# dequantizes to fp32 before accumulating). Quantized formats require
# grouped_token_back. COLLECTIVE.
combine_format: Literal["bf16", "32e4m3xe8m0", "32e5m2xe8m0"] = "bf16"
# How many of the 4 dispatch warps do token-comm work at all (1/2/4);
# the rest stay fully idle (reserved for future in-kernel work). The
# physical warp layout stays at 4. Output-invariant work partitioning
# (rank-local -- no cross-rank agreement needed).
active_dispatch_warps: int = 1
# Per-tensor static calibration scales (see class docstring).
fc1_activation_dequant_scale: float = 1.0
fc2_activation_dequant_scale: float = 1.0
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""Offline knob tuner for the SM90 pull-style FP8 mega kernel.

Invoked through the :mod:`flashinfer.moe_ep.tune` CLI shim (``--dtype
sm90_fp8_e4m3`` / ``sm90_fp8_e5m2``). Kernel-specific pieces (dummy input
creation, candidate enumeration, knob resolution, the autotune entry point)
live here, next to the backend that consumes the recorded winners; the sweep
loop and shared helpers come from ``backends/mega/kernel/tuning.py``.
"""

from __future__ import annotations

from typing import Any

from ...tuning import finish_sweep, run_tuning as _run_tuning, schedule_candidates


def _kind(args) -> str:
# CLI dtype "sm90_fp8_e4m3" -> shim kind "fp8_e4m3".
return args.dtype.removeprefix("sm90_")
Comment thread
inocsin marked this conversation as resolved.
Resolved


def tune_one(args, rank: int, world_size: int, max_tokens: int) -> dict:
from ......kernel_src.sm90.pull_style_cutedsl_megakernel import (
autotune_hopper_fp8_mega_moe,
create_dummy_hopper_fp8_inputs,
hopper_fp8_candidates,
resolve_knobs,
)

live_tokens = args.live_tokens if args.live_tokens is not None else max_tokens
if live_tokens > max_tokens:
raise SystemExit("--live-tokens must be <= --max-tokens")
symm_buffer: Any = None
try:
y, l1, l2, symm_buffer = create_dummy_hopper_fp8_inputs(
rank,
world_size,
args.num_experts,
max_tokens,
live_tokens,
args.topk,
args.hidden,
args.intermediate,
kind=_kind(args),
fp8_scale_mode=args.fp8_scale_mode,
gate_up_clamp=args.gate_up_clamp,
seed=args.seed,
)
candidates = hopper_fp8_candidates(
fp8_scale_mode=args.fp8_scale_mode,
max_tokens=max_tokens,
)

if args.sweep == "schedule":
import json

if args.base_knobs:
base = json.loads(args.base_knobs)
base = {
k: tuple(v) if isinstance(v, list) else v for k, v in base.items()
}
else:
base, src = resolve_knobs(
dtype=_kind(args),
fp8_scale_mode=args.fp8_scale_mode,
world_size=world_size,
hidden=args.hidden,
intermediate=args.intermediate,
num_experts=args.num_experts,
topk=args.topk,
max_tokens=max_tokens,
)
if rank == 0:
print(f"[moe_ep-tune] schedule sweep base ({src}): {base}")
candidates = schedule_candidates(base)

return finish_sweep(
args,
rank,
max_tokens,
live_tokens,
symm_buffer,
y,
l1,
l2,
candidates,
autotune_hopper_fp8_mega_moe,
)
finally:
if symm_buffer is not None:
symm_buffer.destroy()


def run_tuning(args) -> int:
from ......kernel_src.sm90 import pull_style_cutedsl_megakernel as pkg

return _run_tuning(args, tune_one, pkg=pkg)
25 changes: 15 additions & 10 deletions flashinfer/moe_ep/backends/mega/kernel/tuning.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,24 +122,29 @@ def finish_sweep(
return winner


def run_tuning(args, tune_one: Callable[[Any, int, int, int], dict]) -> int:
"""Dist lifecycle + per-bucket sweep loop shared by the cutedsl tuners."""
def run_tuning(
args, tune_one: Callable[[Any, int, int, int], dict], *, pkg: Any = None
) -> int:
"""Dist lifecycle + per-bucket sweep loop shared by the cutedsl tuners.

``pkg`` is the kernel_src package providing ``init_dist`` /
``finalize_dist`` / ``knob_cache_path`` (default: the SM100
``cutedsl_megamoe`` tree; the SM90 tuner passes its own tree β€” the two
trees' modules cannot be active in one process).
"""
import torch

from ....kernel_src.cutedsl_megamoe import (
finalize_dist,
init_dist,
knob_cache_path,
)
if pkg is None:
from ....kernel_src import cutedsl_megamoe as pkg

rank, world_size = init_dist()
rank, world_size = pkg.init_dist()
try:
for max_tokens in args.max_tokens:
tune_one(args, rank, world_size, max_tokens)
torch.cuda.synchronize()
finally:
finalize_dist()
pkg.finalize_dist()
if rank == 0:
path = knob_cache_path()
path = pkg.knob_cache_path()
print(f"[moe_ep-tune] done; cache: {path or 'DISABLED'}", flush=True)
return 0
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,37 @@ The two trees are **separate backends**:
either Hopper or Blackwell, never both, so this is not a practical limit.
- drops are updated independently; never "sync" shared files across the trees.

Current drop: kernel repo commit `1275b8b` ("Merge branch
'vincent/hopper_megamoe' into 'main'", 2026-07).
Current drop: kernel repo commit `c3e2c2a` ("Add token-based launch
heuristics for Hopper FP8 MegaMoE", 2026-08), **minus commit `4f9c042`**
("Add Green Context execution", reverted by decision β€” no
`green_context.py`, no `execution_phase` kwarg, no `split_*` workspace
regions / token_comm bodies). Re-exclude that commit's content when
syncing future drops.

Local extensions pending upstream (re-apply when syncing a drop that has
not picked them up):

- `moe_hopper_fp8/heuristic_config.py` carries a `token_back_mode` field
per bucket (2026-08-23 FI-layer epi-vs-reuse sweep winners).
- Wire-level top-k dedup (`dedup_dispatch`, 2026-08-24, design in
`dedup_topk_design.md`): `src/token_comm.py` (carrier election in
`dispatch_prep`, carrier-table rendezvous in `dispatch_pull`,
`TokenCommArgs.carrier_row_table`) and
`moe_hopper_fp8/megamoe_kernel_fp8.py` (ctor knob + workspace region).
- Combine dedup + quantized combine wire (`grouped_token_back` /
`combine_format`, 2026-08-27, design in `dedup_topk_design.md` Β§4):
`src/token_comm.py` (group table + `grouped_reduce_push` with the
in-reduction per-32 e8m0/fp8 encoder), `moe_hopper_fp8/
megamoe_kernel_fp8.py` (ctor knobs, group/mask/combine_sf regions,
rank-indexed TopkReduce call), and `moe_nvfp4_swapab/topk_reduce.py`
(SM90 scalar mxfp8 decode via f16 + bit-math e8m0, `slot_mask`
rank-masked reduce -- keep NVFP4-compatible when re-syncing).
- `active_dispatch_warps` (2026-08-30): `src/token_comm.py` ctor knob
(default 1) sizing the WORKING subset of the 4 dispatch warps (prep /
barrier / pull / reuse token-back all follow it; barrier and grid-sync
arrival counts scale with it, and the base kernels route the idle warps
straight to kernel_tail). Touches `kernel_fp8_glu_fc12{,_swapab}.py`
(dispatch-body gating) too; the drop tree still hardcodes 4.

## Layout

Expand Down
Loading
Loading